private static void UpdateListItemEventReceivers(SPSite site) { //Upgrade All Lists Instances with new Event Receiver Assembly for //Lists based on the Training Course Content Type string newAssembly = "Contoso.TrainingManagement, Version=2.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5"; //our new assembly info string newClass = "Contoso.TrainingManagement.TrainingCourseItemEventReceiver"; SPContentTypeId contentTypeId = new SPContentTypeId(ContentTypes.TrainingCourse); //our custom ctype foreach (SPWeb web in site.AllWebs) { using ( web ) { for (int i = 0; i < web.Lists.Count; i++) { SPList list = web.Lists[i]; SPContentTypeId bestMatch = list.ContentTypes.BestMatch(contentTypeId); if (bestMatch.IsChildOf(contentTypeId)) { for (int j = 0; j < list.EventReceivers.Count; j++) { SPEventReceiverDefinition eventReceiverDefinition = list.EventReceivers[j]; if (String.Compare(eventReceiverDefinition.Assembly, newAssembly, true) != 0) { list.EventReceivers.Add(eventReceiverDefinition.Type, newAssembly, newClass); eventReceiverDefinition.Delete(); list.Update(); } } } } } } }
// 取消对以下方法的注释,以便处理激活某个功能后引发的事件。 public override void FeatureActivated(SPFeatureReceiverProperties properties) { SPSite site = (SPSite)properties.Feature.Parent; using (SPWeb web = site.OpenWeb(webName)) { SPList typeList = web.GetList(usertypeListName); string className1 = "CMICT.CSP.Web.CategoryEvents.LookupTypesEvent"; SPEventReceiverDefinition eventReceiverDefinition = typeList.EventReceivers.Add(); eventReceiverDefinition.Class = className1; // String eventReceiverDefinition.Assembly = assemblyName1; // String eventReceiverDefinition.Type = SPEventReceiverType.ItemDeleting; // SPEventReceiverType eventReceiverDefinition.Update(); typeList.Update(true); SPList valueList = web.GetList(uservalueListName); string className2 = "CMICT.CSP.Web.CategoryEvents.LookupValuesEvent"; SPEventReceiverDefinition eventReceiverDefinition2 = valueList.EventReceivers.Add(); eventReceiverDefinition2.Class = className2; // String eventReceiverDefinition2.Assembly = assemblyName1; // String eventReceiverDefinition2.Type = SPEventReceiverType.ItemDeleting; // SPEventReceiverType eventReceiverDefinition2.Update(); valueList.Update(true); } }
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); }
private void AddEventReceivers(SPList calendar) { string assemblyName = "WorkBoxFramework, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=4554acfc19d83350"; string className = "WorkBoxFramework.WBLinkedCalendarUpdatesEventReceiver"; SPEventReceiverDefinition itemAddedEventReceiver = calendar.EventReceivers.Add(); itemAddedEventReceiver.Name = WorkBox.LINKED_CALENDAR_EVENT_RECEIVER__ITEM_ADDED; itemAddedEventReceiver.Type = SPEventReceiverType.ItemAdded; itemAddedEventReceiver.SequenceNumber = 1000; itemAddedEventReceiver.Assembly = assemblyName; itemAddedEventReceiver.Class = className; itemAddedEventReceiver.Update(); SPEventReceiverDefinition itemUpdatedEventReceiver = calendar.EventReceivers.Add(); itemUpdatedEventReceiver.Name = WorkBox.LINKED_CALENDAR_EVENT_RECEIVER__ITEM_UPDATED; itemUpdatedEventReceiver.Type = SPEventReceiverType.ItemUpdated; itemUpdatedEventReceiver.SequenceNumber = 1000; itemUpdatedEventReceiver.Assembly = assemblyName; itemUpdatedEventReceiver.Class = className; itemUpdatedEventReceiver.Update(); SPEventReceiverDefinition itemDeletedEventReceiver = calendar.EventReceivers.Add(); itemDeletedEventReceiver.Name = WorkBox.LINKED_CALENDAR_EVENT_RECEIVER__ITEM_DELETING; itemDeletedEventReceiver.Type = SPEventReceiverType.ItemDeleting; itemDeletedEventReceiver.SequenceNumber = 1000; itemDeletedEventReceiver.Assembly = assemblyName; itemDeletedEventReceiver.Class = className; itemDeletedEventReceiver.Update(); }
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 EventReceiverDefinitionNode(object parent, SPEventReceiverDefinition eventReceiverDefinition) { this.Tag = eventReceiverDefinition; this.SPParent = parent; Setup(); }
private void TreeViewItemsNodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) { try { if (e.Node.Tag is SPEventReceiverDefinition) { SPEventReceiverDefinition er = (SPEventReceiverDefinition)e.Node.Tag; textBoxAssemlby.Text = er.Assembly; comboBoxClasses.Items.Clear(); comboBoxClasses.Text = er.Class; textBoxSequence.Text = er.SequenceNumber.ToString(); for (int i = 0; i < comboBoxEventType.Items.Count; i++) { if (comboBoxEventType.Items[i].ToString() == er.Type.ToString()) { comboBoxEventType.SelectedIndex = i; } } } } catch (Exception ex) { Logger(ex.Message, Color.LightBlue); } }
private void AddEventReceivers(SPList calendar) { string assemblyName = "WorkBoxFramework, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=4554acfc19d83350"; string className = "WorkBoxFramework.WBTeamSiteCalendarChangeEventReceiver"; SPEventReceiverDefinition itemAddedEventReceiver = calendar.EventReceivers.Add(); itemAddedEventReceiver.Name = TEAM_SITE_CALENDAR__ADDITIONS; itemAddedEventReceiver.Type = SPEventReceiverType.ItemAdded; itemAddedEventReceiver.SequenceNumber = 1000; itemAddedEventReceiver.Assembly = assemblyName; itemAddedEventReceiver.Class = className; itemAddedEventReceiver.Update(); SPEventReceiverDefinition itemUpdatedEventReceiver = calendar.EventReceivers.Add(); itemUpdatedEventReceiver.Name = TEAM_SITE_CALENDAR__UPDATES; itemUpdatedEventReceiver.Type = SPEventReceiverType.ItemUpdated; itemUpdatedEventReceiver.SequenceNumber = 1000; itemUpdatedEventReceiver.Assembly = assemblyName; itemUpdatedEventReceiver.Class = className; itemUpdatedEventReceiver.Update(); SPEventReceiverDefinition itemDeletedEventReceiver = calendar.EventReceivers.Add(); itemDeletedEventReceiver.Name = TEAM_SITE_CALENDAR__DELETIONS; itemDeletedEventReceiver.Type = SPEventReceiverType.ItemDeleting; itemDeletedEventReceiver.SequenceNumber = 1000; itemDeletedEventReceiver.Assembly = assemblyName; itemDeletedEventReceiver.Class = className; itemDeletedEventReceiver.Update(); }
public EventReceiverDefinitionNode(object parent, SPEventReceiverDefinition eventReceiverDefinition) { this.Tag = eventReceiverDefinition; this.SPParent = parent; Setup(); }
private Dictionary <string, string> GetListEventReceiverProperties(ISharePointCommandContext context, EventReceiverInfo eventReceiverInfo) { SPEventReceiverDefinition eventReceiver = null; Dictionary <string, string> eventReceiverProperties = new Dictionary <string, string>(); SPList list = context.Web.Lists[eventReceiverInfo.ListId]; if (eventReceiverInfo.Id != Guid.Empty) { eventReceiver = list.EventReceivers[eventReceiverInfo.Id]; } else if (!String.IsNullOrEmpty(eventReceiverInfo.Name)) { eventReceiver = (from SPEventReceiverDefinition er in list.EventReceivers where er.Name.Equals(eventReceiverInfo.Name) select er).FirstOrDefault(); } else { eventReceiver = (from SPEventReceiverDefinition er in list.EventReceivers where er.Assembly == eventReceiverInfo.Assembly && er.Class == eventReceiverInfo.Class && (int)er.Type == eventReceiverInfo.EventType select er).FirstOrDefault(); } if (eventReceiver != null) { eventReceiverProperties = SharePointCommandServices.GetProperties(eventReceiver); } return(eventReceiverProperties); }
private void ButtonRemoveClick(object sender, EventArgs e) { try { TreeNode node = treeViewItems.SelectedNode; SPEventReceiverDefinition er = (SPEventReceiverDefinition)node.Tag; if (MessageBox.Show("Are you sure you want to remove this event handler?", "Event Handler Explorer", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { er.Delete(); comboBoxEventType.SelectedIndex = -1; comboBoxClasses.Items.Clear(); node.Parent.Nodes.Remove(node); Logger(@"Event handler unregistered(iisreset needed)"); if (checkboxAutoIisReset.Checked) { LaunchPsCommand(Settings.ScriptIisReset); } } } catch (Exception ex) { Logger(ex.Message, Color.LightBlue); } }
/// <summary> /// Adds the event handler to the content type. /// </summary> /// <param name="contentType">The content type.</param> /// <param name="name">The name of the event.</param> /// <param name="assembly">The assembly containin the event receiver.</param> /// <param name="className">Name of the event receiver class.</param> /// <param name="type">The event receiver type.</param> /// <param name="sequence">The sequence.</param> /// <param name="sync">The synchronization type.</param> public void AddEventHandler( SPContentType contentType, string name, string assembly, string className, SPEventReceiverType type, int sequence, SPEventReceiverSynchronization sync) { // Guard if (contentType == null) { throw new ArgumentNullException("contentType"); } SPEventReceiverDefinition definition = GetEventHandler(contentType.EventReceivers, name, type); if (definition == null) { contentType.EventReceivers.Add(type, assembly, className); definition = GetEventHandler(contentType.EventReceivers, className, type); } definition.Name = name; definition.SequenceNumber = sequence; definition.Synchronization = sync; definition.Update(); }
private SPEventReceiverDefinition AddEventReceiverDefinition(SPList list, SPEventReceiverType type, string assemblyName, string className, SPEventReceiverSynchronization syncType, int sequenceNumber) { SPEventReceiverDefinition eventReceiverDefinition = null; // Try Parse the Assembly Name var classType = Type.GetType(string.Format(CultureInfo.InvariantCulture, "{0}, {1}", className, assemblyName)); if (classType != null) { var assembly = Assembly.GetAssembly(classType); var isAlreadyDefined = list.EventReceivers.Cast <SPEventReceiverDefinition>().Any(x => (x.Class == className) && (x.Type == type)); // If definition isn't already defined, add it to the list if (!isAlreadyDefined) { eventReceiverDefinition = list.EventReceivers.Add(); eventReceiverDefinition.Type = type; eventReceiverDefinition.Assembly = assembly.FullName; eventReceiverDefinition.Synchronization = syncType; eventReceiverDefinition.Class = className; eventReceiverDefinition.SequenceNumber = sequenceNumber; eventReceiverDefinition.Update(); list.Update(); } } return(eventReceiverDefinition); }
/// <summary> /// Добавить списку <paramref name="list"/> EventReceiver с именем <paramref name="name"/>. /// </summary> /// <param name="name">User friendly name for EventReceiver</param> /// <param name="list">SPList, к которому добавляется EventReceiver </param> /// <param name="typeClassReceiver">Тип (класс), в котором реализован метод-обработчик соответствующего EventReceiver'а</param> /// <param name="typeReceiver">Тип EventReceiver'а. Используйте только типы EventReceiver'ов, которые используются для СПИСКОВ (SPList)</param> /// <param name="synchronizationValue" >Синхронное или Асинхронное</param> /// <param name="sequenceNumber">Число, представляющее место данного события в последовательности событий</param> /// <exception cref="ArgumentNullException">Возникает если следующие параметры равны null: <paramref name="name"/>, <paramref name="list"/>, <paramref name="typeClassReceiver"/>. /// </exception> /// <exception cref="ArgumentException">Возникает если у списка уже есть Event ресивер типа <paramref name="typeReceiver"/> реализованный с помощью класса <paramref name="typeClassReceiver"/> /// </exception> public static void AddListEventReceiver(string name, SPList list, Type typeClassReceiver, SPEventReceiverType typeReceiver, SPEventReceiverSynchronization synchronizationValue, int sequenceNumber) { #region Проверка входящих параметров на null if (String.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } if (list == null) { throw new ArgumentNullException("list"); } if (typeClassReceiver == null) { throw new ArgumentNullException("typeClassReceiver"); } #endregion var eventReceiverAssembly = typeClassReceiver.Assembly.FullName; var eventReceiverClass = typeClassReceiver.FullName; #region Проверяем есть ли уже в списке такой Event Reciever. for (var i = 0; i < list.EventReceivers.Count; i++) { var eventReceiverDefinition = list.EventReceivers[i]; if (String.Equals(eventReceiverDefinition.Name, name)) { throw new ArgumentException("Event Receiver с таким именем уже существует.", "name"); } if (eventReceiverDefinition.Assembly == eventReceiverAssembly && eventReceiverDefinition.Class == eventReceiverClass && eventReceiverDefinition.Type == typeReceiver) { throw new ArgumentException( String.Format("Такой Event Receiver уже существует. eventReceiverClass = {0} eventReceiverAssembly = {1}, typeReceiver = {2}", eventReceiverClass, eventReceiverAssembly, typeReceiver)); } } #endregion // Создаём новый EventReceiver SPEventReceiverDefinition newEventReceiverDefinition = list.EventReceivers.Add(); newEventReceiverDefinition.Type = typeReceiver; newEventReceiverDefinition.Assembly = typeClassReceiver.Assembly.FullName; newEventReceiverDefinition.Class = typeClassReceiver.FullName; // Задаём правильное имя EventReceiver'у newEventReceiverDefinition.Name = name; // Задаём тип синхронизации newEventReceiverDefinition.Synchronization = synchronizationValue; newEventReceiverDefinition.SequenceNumber = sequenceNumber; newEventReceiverDefinition.Update(); }
/// <summary> /// Adds an event receiver to the specified target /// </summary> /// <param name="url">The URL.</param> /// <param name="contentTypeName">Name of the content type.</param> /// <param name="target">The target.</param> /// <param name="assembly">The assembly.</param> /// <param name="className">Name of the class.</param> /// <param name="type">The type.</param> /// <param name="sequence">The sequence.</param> /// <param name="name">The name.</param> public static void Add(string url, string contentTypeName, TargetEnum target, string assembly, string className, SPEventReceiverType type, int sequence, string name) { using (SPSite site = new SPSite(url)) using (SPWeb web = site.OpenWeb()) { SPContentType contentType = null; SPEventReceiverDefinitionCollection eventReceivers; if (target == TargetEnum.List) { SPList list = Utilities.GetListFromViewUrl(web, url); if (list == null) { throw new Exception("List not found."); } eventReceivers = list.EventReceivers; } else if (target == TargetEnum.Site) { eventReceivers = web.EventReceivers; } else { try { contentType = web.AvailableContentTypes[contentTypeName]; } catch (ArgumentException) { } if (contentType == null) { throw new SPSyntaxException("The specified content type could not be found."); } eventReceivers = contentType.EventReceivers; } SPEventReceiverDefinition def = Add(eventReceivers, type, assembly, className, name); if (sequence >= 0) { def.SequenceNumber = sequence; def.Update(); } if (contentType != null) { try { contentType.Update((contentType.ParentList == null)); } catch (Exception ex) { Exception ex1 = new Exception("An error occured updating the content type. Most likely the content type was updated but changes may not have been pushed down to any children.", ex); Logger.WriteException(new ErrorRecord(ex1, null, ErrorCategory.NotSpecified, contentType)); } } } }
public SPEventReceiverDefinitionInstance(ObjectInstance prototype, SPEventReceiverDefinition sPEventReceiverDefinition) : this(prototype) { if (sPEventReceiverDefinition == null) { throw new ArgumentNullException("sPEventReceiverDefinition"); } m_eventReceiverDefinition = sPEventReceiverDefinition; }
//public static List<SPFile> GetRelateddocuments(this SPListItem item) //{ // List<SPFile> listFile = new List<SPFile>(); // string contractNumberFieldName = item.Web.Site.GetFeaturePropertyValue(Constants.Workflow.INTEL_WF_FEATURE_ID, Constants.Workflow.CONTRACT_NUMBER_FIELD_NAME); // if (string.IsNullOrEmpty(contractNumberFieldName) || !item.Fields.ContainsField(contractNumberFieldName)) // return null; // if (item[contractNumberFieldName] == null) return null; // string contentTypeFieldName = item.Web.Site.GetFeaturePropertyValue(Constants.Workflow.INTEL_WF_FEATURE_ID, Constants.Workflow.CONTENT_TYPE_FIELD_NAME); // if (string.IsNullOrEmpty(contentTypeFieldName) || !item.Web.Site.RootWeb.AvailableFields.ContainsField(contentTypeFieldName)) // return null; // string includeWithDeliveryFieldName = item.Web.Site.GetFeaturePropertyValue(Constants.Workflow.INTEL_WF_FEATURE_ID, Constants.Workflow.INCLUDE_WITH_DELIVERY_FIELD_NAME); // if (string.IsNullOrEmpty(includeWithDeliveryFieldName) || !item.Web.Site.RootWeb.AvailableFields.ContainsField(includeWithDeliveryFieldName)) // return null; // string relatedContractNumberFieldName = item.Web.Site.GetFeaturePropertyValue(Constants.Workflow.INTEL_WF_FEATURE_ID, Constants.Workflow.RELATED_CONTRACT_NUMBER_FIELD_NAME); // if (string.IsNullOrEmpty(relatedContractNumberFieldName) || !item.Web.Site.RootWeb.AvailableFields.ContainsField(relatedContractNumberFieldName)) // return null; // SPField contractNumberField = item.Fields[contractNumberFieldName]; // SPField contentTypeField = item.Web.Site.RootWeb.AvailableFields[contentTypeFieldName]; // SPField includeWithDeliveryField = item.Web.Site.RootWeb.AvailableFields[includeWithDeliveryFieldName]; // SPField relatedContractNumberField = item.Web.Site.RootWeb.AvailableFields[relatedContractNumberFieldName]; // SearchCriteria criteriaContentType = new SearchCriteria(); // criteriaContentType.FieldId = contentTypeField.Id.ToString(); // criteriaContentType.FieldType = contentTypeField.Type; // criteriaContentType.Operator = Operators.Equal; // criteriaContentType.Value = "Attachment"; // SearchCriteria criteriaIncludeWithDelivery = new SearchCriteria(); // criteriaIncludeWithDelivery.FieldId = includeWithDeliveryField.Id.ToString(); // criteriaIncludeWithDelivery.FieldType = includeWithDeliveryField.Type; // criteriaIncludeWithDelivery.Operator = Operators.Equal; // criteriaIncludeWithDelivery.Value = "1"; // SearchCriteria criteriaRelatedContractNumber = new SearchCriteria(); // criteriaRelatedContractNumber.FieldId = relatedContractNumberField.Id.ToString(); // criteriaRelatedContractNumber.FieldType = relatedContractNumberField.Type; // criteriaRelatedContractNumber.Operator = Operators.Equal; // criteriaRelatedContractNumber.Value = item[contractNumberFieldName].ToString(); // List<SearchCriteria> searchCriteriaList = new List<SearchCriteria>(); // searchCriteriaList.Add(criteriaContentType); // searchCriteriaList.Add(criteriaIncludeWithDelivery); // searchCriteriaList.Add(criteriaRelatedContractNumber); // SearchDefinition searchDefinition = new SearchDefinition(); // searchDefinition.UseGlobalOperatorOR = false; // searchDefinition.SearchCriteriaList = searchCriteriaList; // FieldSetting contractNumberFieldResult = new FieldSetting(); // contractNumberFieldResult.FieldId = contractNumberField.Id.ToString(); // List<FieldSetting> resultFields = new List<FieldSetting>(); // resultFields.Add(contractNumberFieldResult); // string strCAML = CAMLHelper.GetCAMLQueryFromSearchDefinition(searchDefinition); // SPSiteDataQuery dataQuery = new SPSiteDataQuery(); // dataQuery.Query = strCAML; // dataQuery.Lists = CAMLHelper.GetCAMLListBaseTypeSearch(SearchListBaseType.DocumentLibrary); // dataQuery.ViewFields = CAMLHelper.GetCAMLFieldsResult(item.Web, null, resultFields); // dataQuery.Webs = CAMLHelper.GetCAMLScopeSearch(0); // try // { // DataTable searchResultsData = null; // searchResultsData = item.Web.GetSiteData(dataQuery); // foreach (DataRow row in searchResultsData.Rows) // { // SPList list = item.Web.Lists.GetList(new Guid(row["ListId"].ToString()), false); // SPListItem itemGet = list.GetItemById(Convert.ToInt32(row["ID"].ToString())); // if (itemGet.File != null) // listFile.Add(itemGet.File); // } // } // catch { } // return listFile; //} public static void AddEventReceiver(this SPList list, string eventName, SPEventReceiverType type, string assemblyName, string className) { SPEventReceiverDefinition eventDefinition = list.EventReceivers.Add(); eventDefinition.Name = eventName; eventDefinition.Type = type; eventDefinition.Synchronization = SPEventReceiverSynchronization.Synchronous; eventDefinition.Assembly = assemblyName; eventDefinition.Class = className; eventDefinition.Update(); }
private void BindEventReceiver(SPContentType contentType, string eventClassName, SPEventReceiverType eventType) { SPEventReceiverDefinition eventReceiver = contentType.EventReceivers.Add(); eventReceiver.Class = eventClassName; eventReceiver.Assembly = _assemblyName; eventReceiver.Type = eventType; eventReceiver.Data = string.Empty; eventReceiver.Update(); contentType.Update(true); }
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(); } }
public void DisableDiscussionBoardProcessing(SPList list) { SPEventReceiverDefinition receiver = null; do { receiver = list.EventReceivers.OfType <SPEventReceiverDefinition>().Where(p => string.Equals(p.Class, ReceiverType.FullName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); if (receiver != null) { receiver.Delete(); } } while (receiver != null); }
private static void AddReceiverToList(SPList list, string rName, SPEventReceiverType rType, int seq) { if (!list.EventReceivers.Cast <SPEventReceiverDefinition>().Any(r => r.Name == rName)) { SPEventReceiverDefinition _def = list.EventReceivers.Add(); _def.Assembly = Assembly.GetExecutingAssembly().FullName; _def.Class = "Roster.Presentation.EventReceivers.SyncDataReceiver"; _def.Name = rName; _def.Type = rType; _def.SequenceNumber = seq; _def.Synchronization = SPEventReceiverSynchronization.Default; _def.Update(); } }
private SPEventReceiverDefinition AddEventReceiverDefinition(SPContentType contentType, SPEventReceiverType type, string assemblyName, string className, SPEventReceiverSynchronization syncType) { SPEventReceiverDefinition eventReceiverDefinition = null; var classType = Type.GetType(string.Format(CultureInfo.InvariantCulture, "{0}, {1}", className, assemblyName)); if (classType != null) { var assembly = Assembly.GetAssembly(classType); eventReceiverDefinition = this.AddEventReceiverDefinition(contentType, type, assembly, className, syncType); } return(eventReceiverDefinition); }
internal void CreateJobsList(SPWeb spWeb) { string listTitle = "Jobs"; string listDescription = "List of jobs and assignments."; Dictionary <string, SPFieldType> columns = new Dictionary <string, SPFieldType>(); // The "Title" column will be added based on the GenericList template. That field // will be used as the category name for the job (e.g., Shopping), so only need to add // the remaining fields. columns.Add("Description", SPFieldType.Text); columns.Add("AssignedTo", SPFieldType.Text); // Creating list (or retrieving GUID for list if it already exists). Guid listId = CreateCustomList(spWeb, listTitle, listDescription, columns, false); if (listId.Equals(Guid.Empty)) { return; } SPList list = spWeb.Lists[listId]; // Add event receiver (if the current Jobs list is not already associated with the receiver). bool ReceiverExists = false; string receiverClassName = "PushNotificationsList.ListItemEventReceiver"; for (int i = 0; i < list.EventReceivers.Count; i++) { SPEventReceiverDefinition rd = list.EventReceivers[i]; if (rd.Class == receiverClassName && rd.Type == SPEventReceiverType.ItemAdded) { ReceiverExists = true; break; } } if (ReceiverExists == false) { SPEventReceiverDefinition eventReceiver = list.EventReceivers.Add(); // Must specify information here for this specific assembly. eventReceiver.Assembly = "PushNotificationsList, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=c8c80701196c142d"; eventReceiver.Class = receiverClassName; eventReceiver.Name = "ItemAdded Event"; eventReceiver.Type = SPEventReceiverType.ItemAdded; eventReceiver.SequenceNumber = 10000; eventReceiver.Synchronization = SPEventReceiverSynchronization.Synchronous; eventReceiver.Update(); } }
static void Main(string[] args) { #region ItemAdded try { using (SPSite site = new SPSite("http://sp:1220/sites/SPSite/")) { using (SPWeb web = site.OpenWeb()) { SPList list = web.Lists["Country"]; SPEventReceiverDefinition def = list.EventReceivers.Add(); def.Assembly = "ConsoleApplicationExecutingEventReceiver, Version=1.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c";//604f58e28557db00 def.Class = "ConsoleApplicationExecutingEventReceiver.ASyncEvents"; def.Name = "ItemAdded Event"; def.Type = SPEventReceiverType.ItemAdded; def.SequenceNumber = 1000; def.Synchronization = SPEventReceiverSynchronization.Synchronous; def.Update(); } } } catch (Exception e) { Console.WriteLine(e.Message); } #endregion #region ItemDeleting // Console.ReadKey(); // SPSite collection = new SPSite(http://sitename/); // SPUser user = new SPUser(); // SPWeb site = collection.RootWeb; // SPList list = site.Lists["Program"]; // string asmName = "DeleteData, Version=1.0.0.0, Culture=neutral, PublicKeyToken=21ce19119994750e"; // string className = " DeleteData.DeleteRefrence"; // // Register the events with the list // list.EventReceivers.Add(SPEventReceiverType.ItemDeleting, asmName, className); //// Clean up the code // site.Dispose(); // collection.Dispose(); // Console.WriteLine("Sucessfully Registered"); // // Return to calling environment : Success // Environment.Exit(0); #endregion }
private void EventReceiverPropertyGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) { try { if (this.EventReceiverPropertyGrid.SelectedObject != null) { SPEventReceiverDefinition definition = (SPEventReceiverDefinition)this.EventReceiverPropertyGrid.SelectedObject; definition.Update(); } } catch (Exception ex) { this.HandleException(ex); } }
private SPEventReceiverDefinition GetEventReceiver(ref SPList list, Type receiverClassType, SPEventReceiverType receiverType) { SPEventReceiverDefinition def = null; foreach (SPEventReceiverDefinition iDef in list.EventReceivers) { if (iDef.Assembly == receiverClassType.Assembly.FullName && iDef.Class == receiverClassType.Name && iDef.Type == receiverType) { def = iDef; break; } } return(def); }
public void RegisterItemEventHandler(ref SPList list, Type receiverClassType, SPEventReceiverType receiverType, int sequence, SPEventReceiverSynchronization sync) { SPEventReceiverDefinition def = GetEventReceiver(ref list, receiverClassType, receiverType); if (def == null) { def = list.EventReceivers.Add(); def.Assembly = receiverClassType.Assembly.FullName; //"ERDefinition, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=704f58d28567dc00"; def.Class = receiverClassType.Name; // "ERDefinition.ItemEvents"; def.Name = receiverClassType.Name + "_" + receiverType.ToString(); //ItemAdded Event"; def.Type = receiverType; } def.SequenceNumber = sequence; def.Synchronization = sync; def.Update(); }
public override void DeployModel(object modelHost, DefinitionBase model) { var definition = model.WithAssertAndCast <EventReceiverDefinition>("model", value => value.RequireNotNull()); SPEventReceiverDefinition spObject = null; if (modelHost is ListModelHost) { spObject = FindEventReceiverDefinition((modelHost as ListModelHost).HostList.EventReceivers, definition); } else if (modelHost is WebModelHost) { spObject = FindEventReceiverDefinition((modelHost as WebModelHost).HostWeb.EventReceivers, definition); } else if (modelHost is SiteModelHost) { spObject = FindEventReceiverDefinition((modelHost as SiteModelHost).HostSite.EventReceivers, definition); } else if (modelHost is SPContentType) { spObject = FindEventReceiverDefinition((modelHost as SPContentType).EventReceivers, definition); } else { throw new SPMeta2UnsupportedModelHostException("model host should be ListModelHost or WebModelHost"); } var assert = ServiceFactory.AssertService .NewAssert(definition, spObject) .ShouldNotBeNull(spObject) .ShouldBeEqual(m => m.Name, o => o.Name) .ShouldBeEqual(m => m.Class, o => o.Class) .ShouldBeEqual(m => m.Assembly, o => o.Assembly) //.ShouldBeEqual(m => m.Data, o => o.Data) .ShouldBeEqual(m => m.SequenceNumber, o => o.SequenceNumber) .ShouldBeEqual(m => m.Synchronization, o => o.GetSynchronization()) .ShouldBeEqual(m => m.Type, o => o.GetEventReceiverType()); if (!string.IsNullOrEmpty(definition.Data)) { assert.ShouldBeEqual(m => m.Data, o => o.Data); } else { assert.SkipProperty(m => m.Data); } }
/// <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 RemoveEventReceiver(SPList list) { SPEventReceiverDefinition receiverToDelete = null; foreach (SPEventReceiverDefinition receiver in list.EventReceivers) { if (receiver.Class == "MyLocalBroadband.Activities.WSS.PublishedOriginalUpdatedReceiver") { receiverToDelete = receiver; } } if (receiverToDelete != null) { receiverToDelete.Delete(); } list.Update(); }
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(); } }
private static void MapEventReceiverProperties( EventReceiverDefinition definition, SPEventReceiverDefinition existingReceiver, bool isNew) { existingReceiver.Name = definition.Name; existingReceiver.Data = definition.Data; if (isNew) existingReceiver.Type = (SPEventReceiverType)Enum.Parse(typeof(SPEventReceiverType), definition.Type); existingReceiver.Assembly = definition.Assembly; existingReceiver.Class = definition.Class; existingReceiver.SequenceNumber = definition.SequenceNumber; existingReceiver.Synchronization = (SPEventReceiverSynchronization)Enum.Parse(typeof(SPEventReceiverSynchronization), definition.Synchronization); }
public bool IsSameAs(SPEventReceiverDefinition definition) { return this.IsSameAs(new SPGENEventReceiverProperties() { Assembly = definition.Assembly, Class = definition.Class, Type = definition.Type, Synchronization = definition.Synchronization }); }
public virtual void UpdateEventReceiver(SPEventReceiverDefinition eventReceiver, string eventReceiverName, string assembly, string className, SPEventReceiverType type, SPEventReceiverSynchronization sync, int? sequenceNumber) { eventReceiver.Name = eventReceiverName; eventReceiver.Assembly = assembly; eventReceiver.Class = className; eventReceiver.Synchronization = sync; if (sequenceNumber.HasValue) eventReceiver.SequenceNumber = sequenceNumber.Value; eventReceiver.Update(); }