private void OkButton_Click(object sender, EventArgs e) { try { foreach (string typeName in this.TypesCheckedListBox.CheckedItems) { try { Type selectedObjectType = this.SelectedObject.GetType(); SPEventReceiverType eventType = (SPEventReceiverType)Enum.Parse(typeof(SPEventReceiverType), typeName); int maxSequence = 9999; SPEventReceiverDefinitionCollection definitions = null; string parentName = string.Empty; if (typeof(SPWeb).IsAssignableFrom(selectedObjectType)) { SPWeb web = (SPWeb)this.SelectedObject; parentName = web.Name; definitions = web.EventReceivers; } else if (typeof(SPList).IsAssignableFrom(selectedObjectType)) { SPList list = (SPList)this.SelectedObject; parentName = list.Title; definitions = list.EventReceivers; } else { throw new NotSupportedException("The selected object type is not supported."); } if (definitions != null) { this.m_ParentForm.LastSelectedGACObjectType = this.SelectedType; Utility.ProcessEventHookAction(this, this.SelectedObject, typeName, this.SelectedAssembly, this.SelectedType, this.UseNextSequenceNumberCheckBox.Checked); } } catch (Exception exception) { MessageBox.Show(exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); } } MessageBox.Show(this, "The selected events have been hooked. The event sequence should be reviewed to ensure that events execute in the expected order.", "Event Hooks Added", MessageBoxButtons.OK, MessageBoxIcon.Information); this.DialogResult = System.Windows.Forms.DialogResult.OK; this.Close(); } catch (Exception ex) { this.HandleException(ex); } }
public override void FeatureDeactivating(SPFeatureReceiverProperties properties) { string assembly = "ExternalListEvents, Culture=neutral, Version=1.0.0.0, PublicKeyToken=f3e998418ec415ce"; using (SPSite siteCollection = new SPSite("http://dev.wingtip13.com/bcs")) { using (SPWeb site = siteCollection.OpenWeb()) { SPList customers = site.Lists["Customers"]; SPEventReceiverDefinitionCollection receivers = customers.EventReceivers; SPEventReceiverDefinition activityReceiver = null; foreach (SPEventReceiverDefinition receiver in receivers) { if (receiver.Assembly.Equals(assembly, StringComparison.OrdinalIgnoreCase)) { activityReceiver = receiver; break; } } if (activityReceiver != null) { activityReceiver.Delete(); } } } }
public bool EventReceiverDefinitionExist(SPEventReceiverDefinitionCollection collection, SPEventReceiverType type, string assemblyFullName, string classFullName) { if (collection == null) { throw new ArgumentNullException("collection"); } if (string.IsNullOrEmpty(assemblyFullName)) { throw new ArgumentNullException("assemblyFullName"); } if (string.IsNullOrEmpty(classFullName)) { throw new ArgumentNullException("classFullName"); } // If there is nothing in the collection we don't even need to check. if (collection.Count <= 0) { return(false); } // Get the event receiver if it exists. SPEventReceiverDefinition eventReceiver = this.GetEventReceiverDefinition(collection, type, assemblyFullName, classFullName); return(eventReceiver != null); }
protected void Page_Load(object sender, EventArgs e) { string url; try { objSPWeb = SPContext.Current.Web; listId = Page.Request.QueryString[GlobalConstants.LISTID]; if (listId != null) { objSPList = SPContext.Current.Web.Lists[new Guid(listId)]; objEventReceiversCollection = objSPList.EventReceivers; } else { objEventReceiversCollection = SPContext.Current.Web.EventReceivers; } BindGrid(objEventReceiversCollection); url = SPContext.Current.Web.Url + "/_layouts/BrickRed.OpenSource.EventHanlderManagement/RegisterNewEvent.aspx?ListId=" + listId; btAddNewEvent.Attributes.Add("onclick", "javascript:OpenDialog('" + url + "');return false;"); } catch (Exception ex) { throw ex; } }
public SPEventReceiverDefinition GetEventReceiverDefinition(SPEventReceiverDefinitionCollection collection, SPEventReceiverType type, string assemblyFullName, string classFullName) { if (collection == null) { throw new ArgumentNullException("collection"); } if (string.IsNullOrEmpty(assemblyFullName)) { throw new ArgumentNullException("assemblyFullName"); } if (string.IsNullOrEmpty(classFullName)) { throw new ArgumentNullException("classFullName"); } foreach (SPEventReceiverDefinition eventReceiver in collection) { bool isCorrectType = eventReceiver.Type == type; bool isCorrectAssembly = string.Compare(eventReceiver.Assembly, assemblyFullName, StringComparison.OrdinalIgnoreCase) == 0; bool isCorrectClass = string.Compare(eventReceiver.Class, classFullName, StringComparison.OrdinalIgnoreCase) == 0; if (isCorrectType && isCorrectAssembly && isCorrectClass) { return(eventReceiver); } } return(null); }
public bool EventReceiverDefinitionExist(SPEventReceiverDefinitionCollection collection, SPEventReceiverType type, string assemblyFullName, string classFullName) { if (collection == null) { throw new ArgumentNullException("collection"); } if (string.IsNullOrEmpty(assemblyFullName)) { throw new ArgumentNullException("assemblyFullName"); } if (string.IsNullOrEmpty(classFullName)) { throw new ArgumentNullException("classFullName"); } // If there is nothing in the collection we don't even need to check. if (collection.Count <= 0) { return false; } // Get the event receiver if it exists. SPEventReceiverDefinition eventReceiver = this.GetEventReceiverDefinition(collection, type, assemblyFullName, classFullName); return eventReceiver != null; }
/// <summary> /// Ensures the taxonomy event receivers. /// </summary> /// <param name="eventReceivers">The event receivers definition collection.</param> /// <exception cref="System.ArgumentNullException">All null parameters.</exception> public void EnsureTaxonomyEventReceivers(SPEventReceiverDefinitionCollection eventReceivers) { if (eventReceivers == null) { throw new ArgumentNullException("eventReceivers"); } // Check if the ItemAdding exists in the collection. bool hasItemAdding = this.eventReceiverHelper.EventReceiverDefinitionExist(eventReceivers, SPEventReceiverType.ItemAdding, AssemblyFullName, ClassFullName); if (!hasItemAdding) { // Add the ItemAdding event receiver. eventReceivers.Add(SPEventReceiverType.ItemAdding, AssemblyFullName, ClassFullName); } // Check if the ItemUpdating exists in the collection. bool hasItemUpdating = this.eventReceiverHelper.EventReceiverDefinitionExist(eventReceivers, SPEventReceiverType.ItemUpdating, AssemblyFullName, ClassFullName); if (!hasItemUpdating) { // Add the ItemUpdating event receiver. eventReceivers.Add(SPEventReceiverType.ItemUpdating, AssemblyFullName, ClassFullName); } }
public static void UnInstallAssignedToEvent(SPList list) { string assemblyName = "EPM Live Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5"; string className = "EPMLiveCore.AssignedToEvent"; SPEventReceiverDefinitionCollection eventColl = list.EventReceivers; List <SPEventReceiverDefinition> listsToDelete = new List <SPEventReceiverDefinition>(); foreach (SPEventReceiverDefinition eventDef in eventColl) { if (eventDef.Assembly.Equals(assemblyName) && eventDef.Class.Equals(className)) { listsToDelete.Add(eventDef); } } if (listsToDelete.Count > 0) { foreach (SPEventReceiverDefinition eventDel in listsToDelete) { eventDel.Delete(); } } list.Update(); }
public SPEventReceiverDefinition GetEventReceiverDefinition(SPEventReceiverDefinitionCollection collection, SPEventReceiverType type, string assemblyFullName, string classFullName) { if (collection == null) { throw new ArgumentNullException("collection"); } if (string.IsNullOrEmpty(assemblyFullName)) { throw new ArgumentNullException("assemblyFullName"); } if (string.IsNullOrEmpty(classFullName)) { throw new ArgumentNullException("classFullName"); } foreach (SPEventReceiverDefinition eventReceiver in collection) { bool isCorrectType = eventReceiver.Type == type; bool isCorrectAssembly = string.Compare(eventReceiver.Assembly, assemblyFullName, StringComparison.OrdinalIgnoreCase) == 0; bool isCorrectClass = string.Compare(eventReceiver.Class, classFullName, StringComparison.OrdinalIgnoreCase) == 0; if (isCorrectType && isCorrectAssembly && isCorrectClass) { return eventReceiver; } } return null; }
protected SPEventReceiverDefinition CreateNewEventReceiverDefinition( object modelHost, SPEventReceiverDefinitionCollection eventReceivers, out bool isNew) { var result = eventReceivers.Add(); isNew = true; if (modelHost is WebModelHost) { result.HostType = SPEventHostType.Web; } else if (modelHost is ListModelHost) { result.HostType = SPEventHostType.List; } else if (modelHost is SiteModelHost) { result.HostType = SPEventHostType.Site; } else if (modelHost is SPContentType) { result.HostType = SPEventHostType.ContentType; } else { throw new SPMeta2UnsupportedModelHostException("model host should be ListModelHost/WebModelHost/SiteModelHost"); } return(result); }
public EventReceiverDefinitionCollectionNode(object parent, SPEventReceiverDefinitionCollection eventReceiverCollection) { this.Tag = eventReceiverCollection; this.SPParent = parent; this.Setup(); this.Nodes.Add(new ExplorerNodeBase("Dummy")); }
protected SPEventReceiverDefinition FindEventReceiverDefinition(SPEventReceiverDefinitionCollection receivers, EventReceiverDefinition definition) { var receiverName = definition.Name.ToUpper(); return(receivers.OfType <SPEventReceiverDefinition>() .FirstOrDefault(r => !string.IsNullOrEmpty(r.Name) && r.Name.ToUpper() == receiverName)); }
protected SPEventReceiverDefinition FindEventReceiverDefinition(SPEventReceiverDefinitionCollection receivers, EventReceiverDefinition definition) { var receiverName = definition.Name.ToUpper(); return receivers.OfType<SPEventReceiverDefinition>() .FirstOrDefault(r => !string.IsNullOrEmpty(r.Name) && r.Name.ToUpper() == receiverName); }
public SPEventReceiverDefinitionCollectionInstance(ObjectInstance prototype, SPEventReceiverDefinitionCollection eventReceiverDefinitionCollection) : this(prototype) { if (eventReceiverDefinitionCollection == null) { throw new ArgumentNullException("eventReceiverDefinitionCollection"); } m_eventReceiverDefinitionCollection = eventReceiverDefinitionCollection; }
/// <summary> /// Gets the event receiver. /// </summary> /// <param name="eventReceivers">The event receivers.</param> /// <param name="eventReceiverType">Type of the event receiver.</param> /// <param name="assembly">The assembly.</param> /// <param name="className">Name of the class.</param> /// <returns></returns> private static SPEventReceiverDefinition GetEventReceiver(SPEventReceiverDefinitionCollection eventReceivers, SPEventReceiverType eventReceiverType, string assembly, string className) { foreach (SPEventReceiverDefinition erd in eventReceivers) { if (erd.Assembly.ToLower() == assembly.ToLower() && erd.Class.ToLower() == className.ToLower() && erd.Type == eventReceiverType) { return(erd); } } return(null); }
public static void Delete(this SPEventReceiverDefinitionCollection collection, string name) { SPEventReceiverDefinition receiverDefinition = collection.Cast <SPEventReceiverDefinition>() .SingleOrDefault(receiver => string.Equals(receiver.Name, name)); if (receiverDefinition != null) { receiverDefinition.Delete(); receiverDefinition.Update(); } }
internal void InstallEventHandlers(SPList list) { string assemblyName = "EPM Live Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5"; string className = "EPMLiveCore.IntegrateEvents"; bool del = false; bool add = false; bool upd = false; SPEventReceiverDefinitionCollection eventColl = list.EventReceivers; foreach (SPEventReceiverDefinition eventDef in eventColl) { if (eventDef.Assembly.Equals(assemblyName) && eventDef.Class.Equals(className)) { if (eventDef.Type.Equals(SPEventReceiverType.ItemAdded)) { add = true; } if (eventDef.Type.Equals(SPEventReceiverType.ItemUpdated)) { upd = true; } if (eventDef.Type.Equals(SPEventReceiverType.ItemDeleting)) { del = true; } } } if (!add) { list.EventReceivers.Add(SPEventReceiverType.ItemAdded, assemblyName, className); } if (!upd) { list.EventReceivers.Add(SPEventReceiverType.ItemUpdated, assemblyName, className); } if (!del) { list.EventReceivers.Add(SPEventReceiverType.ItemDeleting, assemblyName, className); } if (!add || !upd || !del) { list.Update(); } }
/// <summary> /// Adds an event receiver to a the specified event receiver definition collection. /// </summary> /// <param name="eventReceivers">The event receivers.</param> /// <param name="eventReceiverType">Type of the event receiver.</param> /// <param name="assembly">The assembly.</param> /// <param name="className">Name of the class.</param> /// <param name="name">The name.</param> /// <returns></returns> public static SPEventReceiverDefinition Add(SPEventReceiverDefinitionCollection eventReceivers, SPEventReceiverType eventReceiverType, string assembly, string className, string name) { SPEventReceiverDefinition def = GetEventReceiver(eventReceivers, eventReceiverType, assembly, className); if (def == null) { eventReceivers.Add(eventReceiverType, assembly, className); def = GetEventReceiver(eventReceivers, eventReceiverType, assembly, className); if (def != null && !String.IsNullOrEmpty(name)) { def.Name = name; def.Update(); } return(def); } return(def); }
public static void Register(this SPEventReceiverDefinitionCollection collection, string name, Type receiverType, SPEventReceiverType actionsToHandle, SPEventReceiverSynchronization synchronization = SPEventReceiverSynchronization.Synchronous, int sequenceNumber = 11000) { SPEventReceiverDefinition receiverDefinition = collection.Cast <SPEventReceiverDefinition>() .SingleOrDefault(receiver => string.Equals(receiver.Name, name)); if (receiverDefinition == null) { receiverDefinition = collection.Add(); receiverDefinition.Name = name; receiverDefinition.Synchronization = synchronization; receiverDefinition.Type = actionsToHandle; receiverDefinition.SequenceNumber = sequenceNumber; receiverDefinition.Assembly = receiverType.Assembly.ToString(); receiverDefinition.Class = receiverType.FullName; receiverDefinition.Update(); } }
public virtual SPEventReceiverDefinition RegisterEventReceiver(SPEventReceiverDefinitionCollection collection, string eventReceiverName, string assembly, string className, SPEventReceiverType type, SPEventReceiverSynchronization sync, int? sequenceNumber) { var result = collection.Add(); result.Name = eventReceiverName; result.Assembly = assembly; result.Class = className; result.Type = type; result.Synchronization = sync; if (sequenceNumber.HasValue) result.SequenceNumber = sequenceNumber.Value; result.Update(); return result; }
public static void InstallAssignedToEvent(SPList list) { string assemblyName = "EPM Live Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5"; string className = "EPMLiveCore.AssignedToEvent"; bool del = false; bool add = false; bool upd = false; SPEventReceiverDefinitionCollection eventColl = list.EventReceivers; foreach (SPEventReceiverDefinition eventDef in eventColl) { if (eventDef.Assembly.Equals(assemblyName) && eventDef.Class.Equals(className)) { if (eventDef.Type.Equals(SPEventReceiverType.ItemAdded)) { add = true; } if (eventDef.Type.Equals(SPEventReceiverType.ItemUpdating)) { upd = true; } } } if (!add) { list.EventReceivers.Add(SPEventReceiverType.ItemAdded, assemblyName, className); } if (!upd) { list.EventReceivers.Add(SPEventReceiverType.ItemUpdating, assemblyName, className); } list.EnableAssignToEmail = false; if (!add || !upd || !del) { list.Update(); } }
/// <summary> /// Gets a specific event handler. /// </summary> /// <param name="sperdcol">The event receiver definitions.</param> /// <param name="className">The event receiver class name.</param> /// <param name="type">The event type.</param> /// <returns>The existing event handler or <c>null</c> if the event handler was not found.</returns> private static SPEventReceiverDefinition GetEventHandler( SPEventReceiverDefinitionCollection sperdcol, string className, SPEventReceiverType type) { if (sperdcol == null) { throw new ArgumentNullException("sperdcol"); } for (int i = 0; i < sperdcol.Count; i++) { SPEventReceiverDefinition definition = sperdcol[i]; if ((definition.Type == type) && (definition.Class == className)) { return definition; } } return null; }
private void AuditWebs( SPEventReceiverDefinitionCollection eventReceivers, string siteRootWebUrl, string webUrl, string serverRelativeUrl) { if (eventReceivers == null) { throw new ArgumentNullException(nameof(eventReceivers)); } foreach (SPEventReceiverDefinition eventDefinition in eventReceivers) { UpdateEvents(itemEventTypes, eventDefinition, EPMLiveCore.Properties.Resources.ReportingClassName); // Check for top level rootweb. IF TRUE, THEN check for listdeleting and columndeleting events if (webUrl.Equals(siteRootWebUrl, StringComparison.InvariantCultureIgnoreCase)) { UpdateEvents(fieldEventTypes, eventDefinition, EPMLiveReportsAdminLstEvents); } } foreach (var eventType in itemEventTypes.Keys) { if (!itemEventTypes[eventType]) { AddAuditRecord(eventTypeCaption[eventType], _sListName, serverRelativeUrl); } } // Check for top level rootweb. if (webUrl.Equals(siteRootWebUrl, StringComparison.InvariantCultureIgnoreCase)) { foreach (var eventType in fieldEventTypes.Keys) { if (!fieldEventTypes[eventType]) { AddAuditRecord(eventTypeCaption[eventType], _sListName, serverRelativeUrl); } } } }
internal void RemoveEventHandlers(SPList list) { list.ParentWeb.AllowUnsafeUpdates = true; Hashtable hshParam = new Hashtable(); hshParam.Add("listid", list.ID); DataSet dsIntegrations = _core.GetDataSet("SELECT * from INT_LISTS where LIST_ID=@listid", hshParam); if (dsIntegrations.Tables[0].Rows.Count <= 0) { string assemblyName = "EPM Live Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5"; string className = "EPMLiveCore.IntegrateEvents"; ArrayList arrevents = new ArrayList(); SPEventReceiverDefinitionCollection eventColl = list.EventReceivers; foreach (SPEventReceiverDefinition eventDef in eventColl) { if (eventDef.Assembly.Equals(assemblyName) && eventDef.Class.Equals(className)) { arrevents.Add(eventDef); } } foreach (SPEventReceiverDefinition def in arrevents) { def.Delete(); } if (arrevents.Count > 0) { list.Update(); } } }
static void RemoverEventosDeListaDuplicados(string sitio, string lista) { int cont = 0; using (SPSite sps = new SPSite(sitio)) { using (SPWeb spw = sps.OpenWeb()) { SPList spList = spw.Lists[lista]; List <SPEventReceiverDefinition> eventosAEliminar = new List <SPEventReceiverDefinition>(); SPEventReceiverDefinitionCollection losEventos = spList.EventReceivers; for (int i = 0; i < losEventos.Count; i++) { for (int j = i + 1; j < losEventos.Count; j++) { if (losEventos[i].Class == losEventos[j].Class && losEventos[i].Name == losEventos[j].Name && losEventos[i].Type.ToString() == losEventos[j].Type.ToString()) { eventosAEliminar.Add(losEventos[i]); break; } } } foreach (SPEventReceiverDefinition elEvento in eventosAEliminar) { elEvento.Delete(); cont++; } } } Console.WriteLine(cont + " Eventos duplicados eliminados."); Console.WriteLine("Operación finalizada exitosamente."); Console.WriteLine(); }
private void BindGrid(SPEventReceiverDefinitionCollection objEventReceiversCollection) { try { EventHandler objEventHandler; List <EventHandler> objEventHandlerList = new List <EventHandler>(); if (objEventReceiversCollection.Count > 0) { foreach (SPEventReceiverDefinition def in objEventReceiversCollection) { objEventHandler = new EventHandler(); objEventHandler.EVENTTYPE = def.Type.ToString(); objEventHandler.ASSEMBLYINFO = def.Assembly; objEventHandler.CLASSNAME = def.Class; objEventHandler.DEFID = def.Id; objEventHandlerList.Add(objEventHandler); } objGridView.DataSource = null; objGridView.DataBind(); objGridView.DataSource = objEventHandlerList; objGridView.DataBind(); lblNoEventRegisteres.Visible = false; } else { objEventHandler = new EventHandler(); objEventHandlerList.Add(objEventHandler); objGridView.DataSource = objEventHandlerList; objGridView.DataBind(); objGridView.Rows[0].Visible = false; lblNoEventRegisteres.Visible = true; } } catch (Exception ex) { throw new Exception(ex.Message); } }
private void DeployEventReceiver(object modelHost, SPEventReceiverDefinitionCollection eventReceivers, EventReceiverDefinition definition) { var existingReceiver = FindEventReceiverDefinition(eventReceivers, definition); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = existingReceiver, ObjectType = typeof(SPEventReceiverDefinition), ObjectDefinition = definition, ModelHost = modelHost }); bool isNew = false; if (existingReceiver == null) { existingReceiver = CreateNewEventReceiverDefinition(modelHost, eventReceivers, out isNew); } MapEventReceiverProperties(definition, existingReceiver, isNew); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = existingReceiver, ObjectType = typeof(SPEventReceiverDefinition), ObjectDefinition = definition, ModelHost = modelHost }); existingReceiver.Update(); }
protected SPEventReceiverDefinition CreateNewEventReceiverDefinition( object modelHost, SPEventReceiverDefinitionCollection eventReceivers, out bool isNew) { var result = eventReceivers.Add(); isNew = true; if (modelHost is WebModelHost) result.HostType = SPEventHostType.Web; else if (modelHost is ListModelHost) result.HostType = SPEventHostType.List; else if (modelHost is SiteModelHost) result.HostType = SPEventHostType.Site; else if (modelHost is SPContentType) result.HostType = SPEventHostType.ContentType; else { throw new SPMeta2UnsupportedModelHostException("model host should be ListModelHost/WebModelHost/SiteModelHost"); } return result; }
private void RemoveEventReceiverFromList(SPWeb web) { SPList listM = web.GetList(web.ServerRelativeUrl + "/_catalogs/masterpage/"); bool oldAllowUnsafeUpdated = web.AllowUnsafeUpdates; try { web.AllowUnsafeUpdates = true; SPEventReceiverDefinitionCollection erdc = listM.EventReceivers; List <SPEventReceiverDefinition> eventsToDelete = new List <SPEventReceiverDefinition>(); foreach (SPEventReceiverDefinition erd in erdc) { if (erd.Type == SPEventReceiverType.ItemUpdated) { eventsToDelete.Add(erd); break; } } foreach (SPEventReceiverDefinition er in eventsToDelete) { er.Delete(); } listM.Update(); } catch (Exception ex) { Logger.WriteLog(Logger.Category.Unexpected, "RemoveEventReceiverFromList", ex.Message); } finally { // Remember to set AllowUnsafeUpdates to false again when you're done. web.AllowUnsafeUpdates = oldAllowUnsafeUpdated; } }
private void DeleteEventReceiverHook(Guid guid, ISecurableObject eventContiner) { SPEventReceiverDefinitionCollection definitions = null; if (typeof(SPWeb).IsAssignableFrom(eventContiner.GetType())) { SPWeb web = (SPWeb)eventContiner; definitions = web.EventReceivers; } else if (typeof(SPList).IsAssignableFrom(eventContiner.GetType())) { SPList list = (SPList)eventContiner; definitions = list.EventReceivers; } else { MessageBox.Show(this, "The current type is not supported.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } if (definitions != null) { foreach (SPEventReceiverDefinition definition in definitions) { if (guid == definition.Id) { string type = definition.Type.ToString(); string name = definition.Class; definition.Delete(); MessageBox.Show(this, string.Format("The event hook [{0}] to class [{1}] was deleted.", type, name), "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); break; } } } }
private void VerifyAllToolStripButton_Click(object sender, EventArgs e) { try { List <SPEventReceiverDefinition> invalidDefinitions = new List <SPEventReceiverDefinition>(); foreach (TreeNode objectNode in this.ObjectsTreeView.Nodes) { ParentType parentType = (ParentType)Enum.Parse(typeof(ParentType), objectNode.Name, false); foreach (TreeNode eventContainerNode in objectNode.Nodes) { Guid eventContainerId = new Guid(eventContainerNode.Name); SPEventReceiverDefinitionCollection definitions = null; switch (parentType) { case ParentType.Libraries: case ParentType.Lists: { definitions = this.m_Web.Lists[eventContainerId].EventReceivers; break; } case ParentType.Websites: { definitions = this.m_Web.Webs[eventContainerId].EventReceivers; break; } default: { throw new NotSupportedException("The specified parent type is not valid."); } } if (definitions != null) { foreach (SPEventReceiverDefinition definition in definitions) { MethodInfo methodHook = null; try { methodHook = Utility.ResolveEventHook(definition.Assembly, definition.Class, definition.Type); } catch { //Ignore Error } if (methodHook == null) { invalidDefinitions.Add(definition); } } } } } StringBuilder message = new StringBuilder(); MessageBoxButtons buttons = MessageBoxButtons.OK; if (invalidDefinitions.Count > 0) { buttons = MessageBoxButtons.YesNo; message.Append("The event hooks listed below in the current site are invalid. Do you want to remove these event hooks?"); message.Append(Environment.NewLine); foreach (SPEventReceiverDefinition definition in invalidDefinitions) { message.AppendFormat("[{0}, {1}] [{2}]{3}", definition.Class, definition.Assembly, definition.ContextItemUrl, Environment.NewLine); } } else { message.Append("No invalid event hooks were found in the current site."); } if (DialogResult.Yes == MessageBox.Show(this, message.ToString(), "Invalid Event hook Search Result", buttons)) { foreach (SPEventReceiverDefinition definition in invalidDefinitions) { definition.Delete(); } } } catch (Exception ex) { this.HandleException(ex); } }
/// <summary> /// Adds an event receiver to a the specified event receiver definition collection. /// </summary> /// <param name="eventReceivers">The event receivers.</param> /// <param name="eventReceiverType">Type of the event receiver.</param> /// <param name="assembly">The assembly.</param> /// <param name="className">Name of the class.</param> /// <param name="name">The name.</param> /// <returns></returns> public static SPEventReceiverDefinition Add(SPEventReceiverDefinitionCollection eventReceivers, SPEventReceiverType eventReceiverType, string assembly, string className, string name) { SPEventReceiverDefinition def = GetEventReceiver(eventReceivers, eventReceiverType, assembly, className); if (def == null) { eventReceivers.Add(eventReceiverType, assembly, className); def = GetEventReceiver(eventReceivers, eventReceiverType, assembly, className); if (def != null && !String.IsNullOrEmpty(name)) { def.Name = name; def.Update(); } return def; } return def; }
private void DeployEventReceiver(object modelHost, SPEventReceiverDefinitionCollection eventReceivers, EventReceiverDefinition definition) { var existingReceiver = FindEventReceiverDefinition(eventReceivers, definition); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = existingReceiver, ObjectType = typeof(SPEventReceiverDefinition), ObjectDefinition = definition, ModelHost = modelHost }); bool isNew = false; if (existingReceiver == null) existingReceiver = CreateNewEventReceiverDefinition(modelHost, eventReceivers, out isNew); MapEventReceiverProperties(definition, existingReceiver, isNew); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = existingReceiver, ObjectType = typeof(SPEventReceiverDefinition), ObjectDefinition = definition, ModelHost = modelHost }); existingReceiver.Update(); }
private void LoadEventReceivers() { EventReceiverFilter filter = this.GetEventReceiverFilter(); this.Cursor = Cursors.WaitCursor; this.EventReceiverTreeView.Nodes.Clear(); this.EventReceiverPropertyGrid.SelectedObject = null; string[] names = Enum.GetNames(typeof(SPEventReceiverType)); SortedDictionary <string, List <EventHook> > dictionary = new SortedDictionary <string, List <EventHook> >(); foreach (string name in names) { dictionary.Add(name, new List <EventHook>()); } if (this.m_SelectedObject != null) { SPEventReceiverDefinitionCollection definitions = null; if (typeof(SPWeb).IsAssignableFrom(this.m_SelectedObject.GetType())) { SPWeb web = (SPWeb)this.m_SelectedObject; definitions = web.EventReceivers; } else if (typeof(SPList).IsAssignableFrom(this.m_SelectedObject.GetType())) { SPList list = (SPList)this.m_SelectedObject; definitions = list.EventReceivers; } else { MessageBox.Show(this, "The current type is not supported.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } if (definitions != null) { foreach (SPEventReceiverDefinition definition in definitions) { string eventName = definition.Id.ToString("B").ToUpper(); MethodInfo methodHook = null; try { methodHook = Utility.ResolveEventHook(definition.Assembly, definition.Class, definition.Type); } catch { //Ignore Errror } EventHook hook = new EventHook(definition, methodHook); dictionary[eventName].Add(hook); } } foreach (KeyValuePair <string, List <EventHook> > pair in dictionary) { bool show = true; switch (filter) { case EventReceiverFilter.ShowHookedEvents: { if (pair.Value.Count == 0) { show = false; } break; } case EventReceiverFilter.ShowUnhookedEvents: { if (pair.Value.Count > 0) { show = false; } break; } default: { break; } } if (show) { this.EventReceiverTreeView.Nodes.Add(pair.Key, pair.Key, 6, 6); } foreach (EventHook hook in pair.Value) { string typeName = hook.EventDefinition.Type.ToString(); string eventName = hook.EventDefinition.Id.ToString("B").ToUpper(); this.EventReceiverTreeView.Nodes[typeName].Nodes.Add(eventName, hook.EventDefinition.Class, 7, 7); if (hook.MethodInfo == null) { this.EventReceiverTreeView.Nodes[typeName].Nodes[eventName].ForeColor = Color.Red; this.EventReceiverTreeView.Nodes[typeName].Nodes[eventName].ToolTipText = "Invalid Event Receiver. The specified type could not be resolved."; } } } this.EventReceiverTreeView.ExpandAll(); if (this.EventReceiverTreeView.Nodes.Count > 0) { this.EventReceiverTreeView.SelectedNode = this.EventReceiverTreeView.Nodes[0]; } } this.AddToolStripButton.Enabled = true; this.DeleteToolStripButton.Enabled = true; this.DeleteAllToolStripButton.Enabled = true; this.RemoveInvalidToolStripButton.Enabled = true; this.RefreshEventHooksToolStripButton.Enabled = true; this.Cursor = Cursors.Default; }
public static void ProcessEventHookAction(Form parent, ISecurableObject obj, string typeName, Assembly selectedAssembly, Type selectedType, bool useNextSequenceNumber) { Type selectedObjectType = obj.GetType(); SPEventReceiverType eventType = (SPEventReceiverType)Enum.Parse(typeof(SPEventReceiverType), typeName); int maxSequence = 9999; SPEventReceiverDefinitionCollection definitions = null; string parentName = string.Empty; if (typeof(SPWeb).IsAssignableFrom(selectedObjectType)) { SPWeb web = (SPWeb)obj; parentName = web.Name; definitions = web.EventReceivers; } else if (typeof(SPList).IsAssignableFrom(selectedObjectType)) { SPList list = (SPList)obj; parentName = list.Title; definitions = list.EventReceivers; } else { throw new NotSupportedException("The selected object type is not supported."); } if (definitions != null) { bool cancel = false; List <SPEventReceiverDefinition> pendingDelete = new List <SPEventReceiverDefinition>(); foreach (SPEventReceiverDefinition definition in definitions) { if ((definition.Type == eventType) && string.Equals(definition.Assembly, selectedAssembly.FullName) && string.Equals(definition.Class, selectedType.FullName)) { if (MessageBox.Show(parent, string.Format("The selected event receiver has already been hooked to the [{0}] objects [{1}] event. Do you wish to overwrite the existing event hook?", parentName, eventType), "Event Already Hooked", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) { pendingDelete.Add(definition); } else { cancel = true; break; } } if (definition.SequenceNumber > maxSequence) { maxSequence = definition.SequenceNumber; } } foreach (SPEventReceiverDefinition definition in pendingDelete) { definition.Delete(); } if (cancel) { return; } definitions.Add(eventType, selectedAssembly.FullName, selectedType.FullName); if (useNextSequenceNumber) { foreach (SPEventReceiverDefinition definition in definitions) { if ((definition.Type == eventType) && string.Equals(definition.Assembly, selectedAssembly.FullName) && string.Equals(definition.Class, selectedType.FullName)) { definition.SequenceNumber = (maxSequence + 1); definition.Update(); break; } } } } }
void saveButton_Click(object sender, EventArgs e) { if (PowerEventReceiversHelper.IsUserInPowerEventReceiversGroup == false) { throw new SecurityException("Access Denied! Current user is not a farm administrator."); } if (scriptProperty == null) { scriptProperty = new SPFeatureProperty(propNameScript, scriptBox.Text); feature.Properties.Add(scriptProperty); } else { scriptProperty.Value = scriptBox.Text; } if (sequenceProperty == null) { sequenceProperty = new SPFeatureProperty(propNameSequence, sequenceNumber.Text); feature.Properties.Add(sequenceProperty); } else { sequenceProperty.Value = sequenceNumber.Text; } if (synchronousProperty == null) { synchronousProperty = new SPFeatureProperty(propNameSynchronous, checkBoxSynchronous.Checked.ToString()); feature.Properties.Add(synchronousProperty); } else { synchronousProperty.Value = checkBoxSynchronous.Checked.ToString(); } feature.Properties.Update(); //clean power event receivers List <SPEventReceiverDefinition> receiversToDelete = new List <SPEventReceiverDefinition>(); SPEventReceiverDefinitionCollection receivers = null; if (eventType == PowerEventType.Item || eventType == PowerEventType.List) { receivers = list.EventReceivers; } else { receivers = web.EventReceivers; } foreach (SPEventReceiverDefinition receiver in receivers) { if (receiver.Class == typeof(PowerItemEventReceiver).FullName) { receiversToDelete.Add(receiver); } } foreach (SPEventReceiverDefinition receiver in receiversToDelete) { receiver.Delete(); } if (!String.IsNullOrEmpty(sequenceNumber.Text)) { Runspace runspace = null; try { SPSecurity.RunWithElevatedPrivileges(() => { runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); Pipeline pipe = runspace.CreatePipeline(scriptBox.Text); pipe.Invoke(); pipe = runspace.CreatePipeline("get-childitem function:\\"); Collection <PSObject> results = pipe.Invoke(); string[] receiverTypes = Enum.GetNames(typeof(SPEventReceiverType)); foreach (PSObject obj in results) { FunctionInfo func = (FunctionInfo)obj.BaseObject; if (receiverTypes.Contains(func.Name)) { SPEventReceiverDefinition eventReceiverDef = null; if (eventType == PowerEventType.Web) { eventReceiverDef = web.EventReceivers.Add(); } else { eventReceiverDef = list.EventReceivers.Add(); } eventReceiverDef.Assembly = Assembly.GetExecutingAssembly().FullName; eventReceiverDef.Class = eventDefinitionType; eventReceiverDef.Type = (SPEventReceiverType)Enum.Parse(typeof(SPEventReceiverType), func.Name); eventReceiverDef.SequenceNumber = int.Parse(sequenceNumber.Text); eventReceiverDef.Synchronization = (Boolean.Parse(synchronousProperty.Value) || func.Name.Contains("ing")) ? SPEventReceiverSynchronization.Synchronous : SPEventReceiverSynchronization.Asynchronous; eventReceiverDef.Update(); } } }); Response.Redirect(redirectUrl, true); } catch (Exception ex) { literalError.Text = String.Format("<div style='Color:red'><b>{0}</b></div>", ex.Message); literalError.Text += String.Format("<div>{0}</div>", HttpUtility.HtmlEncode(ex.StackTrace)); } finally { if (runspace != null && runspace.RunspaceStateInfo.State != RunspaceState.Closed) { runspace.Close(); runspace = null; } } } }
public virtual void UnRegisterEventReceiver(SPEventReceiverDefinitionCollection collection, Guid definitionId) { collection[definitionId].Delete(); }
/// <summary> /// Gets the event receiver. /// </summary> /// <param name="eventReceivers">The event receivers.</param> /// <param name="eventReceiverType">Type of the event receiver.</param> /// <param name="assembly">The assembly.</param> /// <param name="className">Name of the class.</param> /// <returns></returns> private static SPEventReceiverDefinition GetEventReceiver(SPEventReceiverDefinitionCollection eventReceivers, SPEventReceiverType eventReceiverType, string assembly, string className) { foreach (SPEventReceiverDefinition erd in eventReceivers) { if (erd.Assembly.ToLower() == assembly.ToLower() && erd.Class.ToLower() == className.ToLower() && erd.Type == eventReceiverType) { return erd; } } return null; }
void saveButton_Click(object sender, EventArgs e) { if (SPFarm.Local.CurrentUserIsAdministrator() == false) { throw new SecurityException("Access Denied! Current user is not a farm administrator."); } if (scriptProperty == null) { scriptProperty = new SPFeatureProperty(propNameScript, scriptBox.Text); feature.Properties.Add(scriptProperty); } else { scriptProperty.Value = scriptBox.Text; } if (sequenceProperty == null) { sequenceProperty = new SPFeatureProperty(propNameSequence, sequenceNumber.Text); feature.Properties.Add(sequenceProperty); } else { sequenceProperty.Value = sequenceNumber.Text; } feature.Properties.Update(); //clean power event receivers List <SPEventReceiverDefinition> receiversToDelete = new List <SPEventReceiverDefinition>(); SPEventReceiverDefinitionCollection receivers = null; if (eventType == PowerEventType.Item || eventType == PowerEventType.List) { receivers = list.EventReceivers; } else { receivers = web.EventReceivers; } foreach (SPEventReceiverDefinition receiver in receivers) { if (receiver.Class == typeof(PowerItemEventReceiver).FullName) { receiversToDelete.Add(receiver); } } foreach (SPEventReceiverDefinition receiver in receiversToDelete) { receiver.Delete(); } if (!String.IsNullOrEmpty(sequenceNumber.Text)) { Runspace runspace = null; try { runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); Pipeline pipe = runspace.CreatePipeline(scriptBox.Text); pipe.Invoke(); pipe = runspace.CreatePipeline("get-childitem function:\\"); Collection <PSObject> results = pipe.Invoke(); string[] receiverTypes = Enum.GetNames(typeof(SPEventReceiverType)); foreach (PSObject obj in results) { FunctionInfo func = (FunctionInfo)obj.BaseObject; if (receiverTypes.Contains(func.Name)) { SPEventReceiverDefinition eventReceiverDef = null; if (eventType == PowerEventType.Web) { eventReceiverDef = web.EventReceivers.Add(); } else { eventReceiverDef = list.EventReceivers.Add(); } eventReceiverDef.Assembly = Assembly.GetExecutingAssembly().FullName; eventReceiverDef.Class = eventDefinitionType; eventReceiverDef.Type = (SPEventReceiverType)Enum.Parse(typeof(SPEventReceiverType), func.Name); eventReceiverDef.SequenceNumber = int.Parse(sequenceNumber.Text); eventReceiverDef.Update(); } } } catch (Exception ex) { throw ex; } finally { if (runspace != null && runspace.RunspaceStateInfo.State != RunspaceState.Closed) { runspace.Close(); runspace = null; } } } Response.Redirect(redirectUrl, true); }