private static void RegisterExpectedShipmentsEventHandler(HttpRequest request) { using (var clientContext = sPContext.CreateUserClientContextForSPHost()) { var query = from list in clientContext.Web.Lists where list.Title == "Expected Shipments" select list; IEnumerable <List> matchingLists = clientContext.LoadQuery(query); clientContext.ExecuteQuery(); List expectedShipmentsList = matchingLists.Single(); EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation(); receiver.ReceiverName = "ExpectedShipmentsItemUpdated"; receiver.EventType = EventReceiverType.ItemUpdated; #if DEBUG receiver.ReceiverUrl = WebConfigurationManager.AppSettings["RERdebuggingServiceBusUrl"].ToString(); #else receiver.ReceiverUrl = "https://" + request.Headers["Host"] + "/Services/RemoteEventReceiver1.svc"; #endif expectedShipmentsList.EventReceivers.Add(receiver); clientContext.ExecuteQuery(); } }
public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties) { SPRemoteEventResult result = new SPRemoteEventResult(); using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, false)) { if (clientContext != null) { clientContext.Load(clientContext.Web); clientContext.ExecuteQuery(); var requestProperty = (System.ServiceModel.Channels.HttpRequestMessageProperty)System.ServiceModel.OperationContext.Current.IncomingMessageProperties[System.ServiceModel.Channels.HttpRequestMessageProperty.Name]; string opContext = System.ServiceModel.OperationContext.Current.Channel.LocalAddress.Uri.AbsoluteUri.Substring(0, System.ServiceModel.OperationContext.Current.Channel.LocalAddress.Uri.AbsoluteUri.LastIndexOf("/")); string remoteUrl = string.Format("{0}/CreateSite.svc", opContext); //string remoteUrl = string.Format("{0}/CreateSite2.svc", System.ServiceModel.OperationContext.Current.Channel.LocalAddress.Uri.DnsSafeHost + "/services"); var appWebUrl = "https://" + requestProperty.Headers[System.Net.HttpRequestHeader.Host]; List createSiteRequests = clientContext.Web.Lists.GetByTitle("SiteCreationRequests"); if (properties.EventType == SPRemoteEventType.AppInstalled) { EventReceiverDefinitionCreationInformation newEventReceiver = new EventReceiverDefinitionCreationInformation() { EventType = EventReceiverType.ItemUpdated, ReceiverName = "CreateSite", ReceiverUrl = remoteUrl, SequenceNumber = 1000 //Should be higher number if lower priority, particularly for async events }; createSiteRequests.EventReceivers.Add(newEventReceiver); clientContext.ExecuteQuery(); } } } return(result); }
private void HandleAppInstalled(SPRemoteEventProperties properties) { using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, false)) { if (clientContext != null) { List myList = clientContext.Web.Lists.GetByTitle(ListName); clientContext.Load(myList, p => p.EventReceivers); clientContext.ExecuteQuery(); bool rerExists = false; foreach (var rer in myList.EventReceivers) { if (rer.ReceiverName == ReceiverName) { rerExists = true; System.Diagnostics.Trace.WriteLine("Found existing ItemAdded receiver at " + rer.ReceiverUrl); } } if (!rerExists) { EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation(); receiver.EventType = EventReceiverType.ItemAdded; //Get WCF URL where this message was handled OperationContext op = OperationContext.Current; Message msg = op.RequestContext.RequestMessage; receiver.ReceiverUrl = msg.Headers.To.ToString(); receiver.ReceiverName = ReceiverName; receiver.Synchronization = EventReceiverSynchronization.Synchronous; myList.EventReceivers.Add(receiver); clientContext.ExecuteQuery(); System.Diagnostics.Trace.WriteLine("Added ItemAdded receiver at " + msg.Headers.To.ToString()); } } } }
private void AttachEventHandler(string handlerEndpoint, Web web, string name, EventReceiverType receiverType, ClientContext clientContext) { clientContext.Load(web, w => w.EventReceivers.Include(e => e.ReceiverName)); clientContext.ExecuteQueryRetry(); foreach (var eventReciever in web.EventReceivers) { if (eventReciever.ReceiverName == name) { return; } } var eventReceiver = new EventReceiverDefinitionCreationInformation { EventType = receiverType, ReceiverName = name, ReceiverUrl = handlerEndpoint, SequenceNumber = 10000, Synchronization = EventReceiverSynchronization.Asynchronous }; web.EventReceivers.Add(eventReceiver); OnNotify(ProvisioningNotificationLevels.Verbose, "Attaching remote event handler to web | " + name); }
/// <summary> /// Registers a remote event receiver /// </summary> /// <param name="web">The web to process</param> /// <param name="name">The name of the event receiver (needs to be unique among the event receivers registered on this list)</param> /// <param name="url">The URL of the remote WCF service that handles the event</param> /// <param name="eventReceiverType"></param> /// <param name="synchronization"></param> /// <param name="sequenceNumber"></param> /// <param name="force">If True any event already registered with the same name will be removed first.</param> /// <returns>Returns an EventReceiverDefinition if succeeded. Returns null if failed.</returns> public static EventReceiverDefinition AddRemoteEventReceiver(this Web web, string name, string url, EventReceiverType eventReceiverType, EventReceiverSynchronization synchronization, int sequenceNumber, bool force) { var query = from receiver in web.EventReceivers where receiver.ReceiverName == name select receiver; web.Context.LoadQuery(query); web.Context.ExecuteQueryRetry(); var receiverExists = query.Any(); if (receiverExists && force) { var receiver = query.FirstOrDefault(); receiver.DeleteObject(); web.Context.ExecuteQueryRetry(); receiverExists = false; } EventReceiverDefinition def = null; if (!receiverExists) { EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation(); receiver.EventType = eventReceiverType; receiver.ReceiverUrl = url; receiver.ReceiverName = name; receiver.SequenceNumber = sequenceNumber; receiver.Synchronization = synchronization; def = web.EventReceivers.Add(receiver); web.Context.Load(def); web.Context.ExecuteQueryRetry(); } return(def); }
/// <summary> /// deployes event receiver at site level /// </summary> /// <param name="clientContext"></param> public void AssociateWebProvisionedEventReceiver(ClientContext clientContext) { Web web = clientContext.Web; clientContext.Load(web); clientContext.Load(clientContext.Site); clientContext.Load(clientContext.Site.EventReceivers); clientContext.ExecuteQuery(); EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation(); receiver.EventType = EventReceiverType.WebProvisioned; OperationContext op = OperationContext.Current; Message msg = op.RequestContext.RequestMessage; receiver.ReceiverUrl = msg.Headers.To.ToString(); receiver.ReceiverName = ReceiverName; receiver.Synchronization = EventReceiverSynchronization.Synchronous; receiver.SequenceNumber = 5000; //adding receiver the host web. // we are adding event receiver to site context so that event receriver fires for sub-sub-sites clientContext.Site.EventReceivers.Add(receiver); clientContext.ExecuteQuery(); //upload theme related files themeHelper.DeployFiles(web); //delete oob composed looks themeHelper.DeleteOOBComposedLooks(clientContext); //apply theme and set default theme themeHelper.AddComposedLooksAndSetDefaultTheme(clientContext); }
private void SetupEventReceiversOfList(ClientContext context, List setupList, ShList listConfig) { if (listConfig.AddMetadataDefaultsReceiver) { var metadataDefaultsEventReceiver = new EventReceiverDefinitionCreationInformation { ReceiverName = "LocationBasedMetadataDefaultsReceiver ItemAdded", EventType = EventReceiverType.ItemAdded, Synchronization = EventReceiverSynchronization.Synchronous, ReceiverAssembly = "Microsoft.Office.DocumentManagement, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c", ReceiverClass = "Microsoft.Office.DocumentManagement.LocationBasedMetadataDefaultsReceiver", SequenceNumber = 1000 }; if (setupList.GetEventReceiverByName(metadataDefaultsEventReceiver.ReceiverName) == null) { Log.DebugFormat("Adding Metadata Event Receiver to list {0}", listConfig.Title); setupList.EventReceivers.Add(metadataDefaultsEventReceiver); } else { Log.DebugFormat("Metadata Event Receiver already added to list {0}", listConfig.Title); } setupList.Update(); context.ExecuteQuery(); } }
public SPOEventReceiverDefinition AddEventReceiver(EventReceiverDefinitionCreationInformation erdci) { SPOEventReceiverDefinition erd = new SPOEventReceiverDefinition(_web.EventReceivers.Add(erdci), _web.EventReceivers); _web.EventReceivers.Context.ExecuteQuery(); return(erd); }
/// <summary> /// Registers a remote event receiver /// </summary> /// <param name="list">The list to process</param> /// <param name="name">The name of the event receiver (needs to be unique among the event receivers registered on this list)</param> /// <param name="url">The URL of the remote WCF service that handles the event</param> /// <param name="eventReceiverType"></param> /// <param name="synchronization"></param> /// <param name="force">If True any event already registered with the same name will be removed first.</param> /// <returns>Returns an EventReceiverDefinition if succeeded. Returns null if failed.</returns> public static EventReceiverDefinition AddRemoteEventReceiver(this List list, string name, string url, EventReceiverType eventReceiverType, EventReceiverSynchronization synchronization, bool force) { var query = from receiver in list.EventReceivers where receiver.ReceiverName == name select receiver; list.Context.LoadQuery(query); list.Context.ExecuteQuery(); var receiverExists = query.Any(); if (receiverExists && force) { var receiver = query.FirstOrDefault(); receiver.DeleteObject(); list.Context.ExecuteQuery(); receiverExists = false; } EventReceiverDefinition def = null; if (!receiverExists) { EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation(); receiver.EventType = eventReceiverType; receiver.ReceiverUrl = url; receiver.ReceiverName = name; receiver.Synchronization = synchronization; def = list.EventReceivers.Add(receiver); list.Context.Load(def); list.Context.ExecuteQuery(); } return def; }
public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties) { SPRemoteEventResult result = new SPRemoteEventResult(); if (properties.EventType == SPRemoteEventType.AppInstalled) { using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, false)) { if (clientContext != null) { //Get reference to the host web list by itsname var documentsList = clientContext.Web.Lists.GetByTitle("firstlist"); clientContext.Load(documentsList); clientContext.ExecuteQuery(); string remoteUrl = "http://azurewebappname.azurewebsites.net/Services/RemoteEventReceiver1.svc"; //Create the remote event receiver definition EventReceiverDefinitionCreationInformation newEventReceiver = new EventReceiverDefinitionCreationInformation() { EventType = EventReceiverType.ItemAdded, ReceiverAssembly = Assembly.GetExecutingAssembly().FullName, ReceiverName = "RemoteEventReceiver1", ReceiverClass = "RemoteEventReceiver1", ReceiverUrl = remoteUrl, SequenceNumber = 15000 }; //Add the remote event receiver to the host web list documentsList.EventReceivers.Add(newEventReceiver); clientContext.ExecuteQuery(); } } } else if (properties.EventType == SPRemoteEventType.AppUninstalling) { using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, false)) { var list = clientContext.Web.Lists.GetByTitle("firstlist"); clientContext.Load(list); clientContext.ExecuteQuery(); EventReceiverDefinitionCollection erdc = list.EventReceivers; clientContext.Load(erdc); clientContext.ExecuteQuery(); List <EventReceiverDefinition> toDelete = new List <EventReceiverDefinition>(); foreach (EventReceiverDefinition erd in erdc) { if (erd.ReceiverName == "RemoteEventReceiver1") { toDelete.Add(erd); } } //Delete the remote event receiver from the list, when the app gets uninstalled foreach (EventReceiverDefinition item in toDelete) { item.DeleteObject(); clientContext.ExecuteQuery(); } } } return(result); }
/// <summary> /// Add a Remote Event Receiver to a List /// </summary> /// <param name="ctx">An Authenticated ClientContext</param> /// <param name="list">The list</param> /// <param name="eventReceiverInfo"><see cref="Microsoft.SharePoint.Client.EventReceiverDefinitionCreationInformation"/></param> public static void AddEventReceiver(ClientContext ctx, List list, EventReceiverDefinitionCreationInformation eventReceiverInfo) { if (!DoesEventReceiverExistByName(ctx, list, eventReceiverInfo.ReceiverName)) { list.EventReceivers.Add(eventReceiverInfo); ctx.ExecuteQuery(); } }
/// <summary> /// Add a Remote Event Receiver to a List /// </summary> /// <param name="ctx">An Authenticated ClientContext</param> /// <param name="list">The list</param> /// <param name="eventReceiverInfo"><see cref="Microsoft.SharePoint.Client.EventReceiverDefinitionCreationInformation"/></param> public static void AddEventReceiver(ClientContext ctx, List list, EventReceiverDefinitionCreationInformation eventReceiverInfo) { if (!DoesEventReceiverExistByName(ctx, list, eventReceiverInfo.ReceiverName)) { list.EventReceivers.Add(eventReceiverInfo); ctx.ExecuteQuery(); } }
public static EventReceiverDefinitionCreationInformation CreateEventReciever(string receiverName, EventReceiverType type) { EventReceiverDefinitionCreationInformation _rer = new EventReceiverDefinitionCreationInformation(); _rer.EventType = type; _rer.ReceiverName = receiverName; _rer.ReceiverClass = "ECM.AutoTaggingWeb.Services.AutoTaggingService"; _rer.ReceiverUrl = "https://localhost:44382/Services/AppEventReceiver.svc"; _rer.Synchronization = EventReceiverSynchronization.Synchronous; return(_rer); }
/// <summary> /// Creates a Remote Event Receiver /// </summary> /// <param name="receiverName">The name of the remote event receiver</param> /// <param name="type"><see cref="Microsoft.SharePoint.Client.EventReceiverType"/></param> /// <returns><see cref="Microsoft.SharePoint.Client.EventReceiverDefinitionRemoCreationInformation"/></returns> public static EventReceiverDefinitionCreationInformation CreateEventReciever(string receiverName, EventReceiverType type) { EventReceiverDefinitionCreationInformation _rer = new EventReceiverDefinitionCreationInformation(); _rer.EventType = type; _rer.ReceiverName = receiverName; _rer.ReceiverClass = "ECM.AutoTaggingWeb.Services.AutoTaggingService"; _rer.ReceiverUrl = "https://amsecm.azurewebsites.net/Services/AutoTaggingService.svc"; _rer.Synchronization = EventReceiverSynchronization.Synchronous; return _rer; }
/// <summary> /// Register the remote event receiver /// </summary> /// <param name="clientContext"></param> /// <param name="list"></param> /// <param name="name"></param> /// <param name="serviceUrl"></param> /// <param name="eventType"></param> /// <param name="sequence"></param> private void RegisterEventReceiver(ClientContext clientContext, List list, string name, string serviceUrl, EventReceiverType eventType, int sequence) { EventReceiverDefinitionCreationInformation newEventReceiver = new EventReceiverDefinitionCreationInformation() { EventType = eventType, ReceiverName = name, ReceiverUrl = serviceUrl, SequenceNumber = sequence }; list.EventReceivers.Add(newEventReceiver); clientContext.ExecuteQuery(); }
private void HandleAppInstalled(SPRemoteEventProperties properties) { using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, false)) { if (clientContext != null) { List pdfList = clientContext.Web.Lists.GetByTitle(ListName); clientContext.Load(pdfList, p => p.EventReceivers); clientContext.ExecuteQuery(); foreach (var receiver in pdfList.EventReceivers.Where(receiver => receiver.ReceiverName == ReceiverNameAdded)) { Trace.WriteLine("Found existing ItemAdded receiver at " + receiver.ReceiverUrl); DeleteReceiver(clientContext, receiver); break; } foreach (var receiver in pdfList.EventReceivers.Where(receiver => receiver.ReceiverName == ReceiverNameUpdated)) { Trace.WriteLine("Found existing ItemAdded receiver at " + receiver.ReceiverUrl); DeleteReceiver(clientContext, receiver); break; } Message msg = OperationContext.Current.RequestContext.RequestMessage; EventReceiverDefinitionCreationInformation receiverAdded = new EventReceiverDefinitionCreationInformation { EventType = EventReceiverType.ItemAdded, ReceiverUrl = msg.Headers.To.ToString(), ReceiverName = ReceiverNameAdded, Synchronization = EventReceiverSynchronization.Synchronous }; pdfList.EventReceivers.Add(receiverAdded); clientContext.ExecuteQuery(); Trace.WriteLine("Added ItemAdded receiver at " + msg.Headers.To); EventReceiverDefinitionCreationInformation receiverUpdating = new EventReceiverDefinitionCreationInformation { EventType = EventReceiverType.ItemUpdating, ReceiverUrl = msg.Headers.To.ToString(), ReceiverName = ReceiverNameUpdated, Synchronization = EventReceiverSynchronization.Synchronous }; pdfList.EventReceivers.Add(receiverUpdating); clientContext.ExecuteQuery(); Trace.WriteLine("Added ItemUpdating receiver at " + msg.Headers.To); } } }
private static void AddEventReceiverToList(ClientContext clientContext, string listTitle, EventReceiverType eventType) { var list = clientContext.Web.Lists.GetByTitle(listTitle); var requestProperty = (HttpRequestMessageProperty)OperationContext.Current.IncomingMessageProperties[HttpRequestMessageProperty.Name]; var appWebUrl = "https://" + requestProperty.Headers[HttpRequestHeader.Host]; var receiverName = listTitle + "_" + eventType.ToString(); var eventReceiver = new EventReceiverDefinitionCreationInformation(); eventReceiver.EventType = eventType; eventReceiver.ReceiverName = receiverName; eventReceiver.ReceiverClass = receiverName; eventReceiver.ReceiverUrl = appWebUrl + "/Services/" + receiverName + ".svc"; eventReceiver.SequenceNumber = 10000; list.EventReceivers.Add(eventReceiver); clientContext.ExecuteQuery(); TraceHelper.RemoteLog("RER attached: " + receiverName); }
private void HandleAppInstalled(SPRemoteEventProperties properties) { using (ClientContext ctx = TokenHelper.CreateAppEventClientContext(properties, false)) { if (ctx != null) { //Add a list to the host web List eventReceiverList = LabHelper.AddList(ctx, ctx.Web, Microsoft.SharePoint.Client.ListTemplateType.GenericList, ListName); //Remove existing event handlers ctx.Load(eventReceiverList, x => x.EventReceivers); ctx.ExecuteQuery(); foreach (var rer in eventReceiverList.EventReceivers) { if (rer.ReceiverName == ReceiverName) { System.Diagnostics.Trace.WriteLine("Found existing ItemAdded receiver at " + rer.ReceiverUrl); try { //This will fail when deploying via F5, but works when deployed to production rer.DeleteObject(); ctx.ExecuteQuery(); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); } } } //Get WCF URL where this message was handled OperationContext op = OperationContext.Current; Message msg = op.RequestContext.RequestMessage; //Create a new event receiver EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation(); receiver.EventType = EventReceiverType.ItemAdded; receiver.ReceiverUrl = msg.Headers.To.ToString(); receiver.ReceiverName = ReceiverName; receiver.Synchronization = EventReceiverSynchronization.Synchronous; //Add the new event receiver to a list in the host web eventReceiverList.EventReceivers.Add(receiver); ctx.ExecuteQuery(); } } }
private void HandleAppInstalled(SPRemoteEventProperties properties) { using (ClientContext ctx = TokenHelper.CreateAppEventClientContext(properties, false)) { if (ctx != null) { //Add a list to the host web List eventReceiverList = LabHelper.AddList(ctx, ctx.Web, Microsoft.SharePoint.Client.ListTemplateType.GenericList, ListName); //Remove existing event handlers ctx.Load(eventReceiverList, x => x.EventReceivers); ctx.ExecuteQuery(); foreach (var rer in eventReceiverList.EventReceivers) { if (rer.ReceiverName == ReceiverName) { System.Diagnostics.Trace.WriteLine("Found existing ItemAdded receiver at " + rer.ReceiverUrl); try { //This will fail when deploying via F5, but works when deployed to production rer.DeleteObject(); ctx.ExecuteQuery(); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); } } } //Get WCF URL where this message was handled OperationContext op = OperationContext.Current; Message msg = op.RequestContext.RequestMessage; //Create a new event receiver EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation(); receiver.EventType = EventReceiverType.ItemAdded; receiver.ReceiverUrl = msg.Headers.To.ToString(); receiver.ReceiverName = ReceiverName; receiver.Synchronization = EventReceiverSynchronization.Synchronous; //Add the new event receiver to a list in the host web eventReceiverList.EventReceivers.Add(receiver); ctx.ExecuteQuery(); } } }
private static void AddEventReceiverToList(ClientContext clientContext, string listTitle, EventReceiverType eventType) { var list = clientContext.Web.Lists.GetByTitle(listTitle); var requestProperty = (HttpRequestMessageProperty)OperationContext.Current.IncomingMessageProperties[HttpRequestMessageProperty.Name]; var appWebUrl = "https://" + requestProperty.Headers[HttpRequestHeader.Host]; var receiverName = listTitle + "_" + eventType.ToString(); var eventReceiver = new EventReceiverDefinitionCreationInformation(); eventReceiver.EventType = eventType; eventReceiver.ReceiverName = receiverName; eventReceiver.ReceiverClass = receiverName; eventReceiver.ReceiverUrl = appWebUrl + "/Services/" + receiverName + ".svc"; eventReceiver.SequenceNumber = 10000; list.EventReceivers.Add(eventReceiver); clientContext.ExecuteQuery(); TraceHelper.RemoteLog("RER attached: " + receiverName); }
private static bool ContainsECMRecordEventReceiver(EventReceiverDefinitionCreationInformation receiverToAdd, List <EventReceiverDefinition> currentEventReceivers) { foreach (var eventReceiver in currentEventReceivers) { if (eventReceiver.EventType.Equals(receiverToAdd.EventType) && eventReceiver.ReceiverAssembly.Equals(receiverToAdd.ReceiverAssembly) && eventReceiver.ReceiverClass.Equals(receiverToAdd.ReceiverClass) && eventReceiver.ReceiverName.Equals(receiverToAdd.ReceiverName) && eventReceiver.SequenceNumber.Equals(receiverToAdd.SequenceNumber) && eventReceiver.Synchronization.Equals(receiverToAdd.Synchronization)) { return(true); } } return(false); }
public static void AddListItemRemoteEventReceiver(ClientContext context, string listName, EventReceiverType eventType, EventReceiverSynchronization synchronization, string receiverName, string receiverUrl, int sequence, string receiverAssemblyName = "", string receiverClassName = "") { var list = context.Web.Lists.GetByTitle(listName); context.Load(list); var eventReceivers = list.EventReceivers; context.Load(eventReceivers); context.ExecuteQuery(); var newRER = new EventReceiverDefinitionCreationInformation(); newRER.EventType = eventType; newRER.ReceiverName = receiverName; newRER.ReceiverClass = receiverClassName; newRER.ReceiverAssembly = receiverAssemblyName; newRER.ReceiverUrl = receiverUrl; newRER.Synchronization = synchronization; newRER.SequenceNumber = sequence; list.EventReceivers.Add(newRER); list.Update(); context.ExecuteQuery(); }
public void Bind(ClientContext clientContext, string listName, string eventRecieverName, string remoteUrl, int sequencyId, EventReceiverType eventType) { try { List olist = clientContext.Web.Lists.GetByTitle(listName); clientContext.Load(olist, o => o.EventReceivers); clientContext.ExecuteQuery(); bool isReRExsist = false; foreach (var receiver in olist.EventReceivers) { if (receiver.ReceiverName == eventRecieverName) { isReRExsist = true; break; } } if (!isReRExsist) { EventReceiverDefinitionCreationInformation eventReDefCreation = new EventReceiverDefinitionCreationInformation() { EventType = eventType, ReceiverAssembly = Assembly.GetExecutingAssembly().FullName, ReceiverName = eventRecieverName, ReceiverClass = eventRecieverName, ReceiverUrl = remoteUrl, SequenceNumber = sequencyId }; olist.EventReceivers.Add(eventReDefCreation); clientContext.ExecuteQuery(); } } catch (Exception ex) { } }
private void HandleAppInstalled(SPRemoteEventProperties properties) { using (ClientContext cc = TokenHelper.CreateAppEventClientContext(properties, false)) { if (cc != null) { bool rerExists = false; cc.Load(cc.Web.EventReceivers); cc.ExecuteQuery(); foreach (var rer in cc.Web.EventReceivers) { if (rer.ReceiverName == RECEIVER_NAME) { rerExists = true; System.Diagnostics.Trace.WriteLine("Found existing ListAdded receiver at " + rer.ReceiverUrl); } } if (!rerExists) { EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation(); receiver.EventType = EventReceiverType.ListAdded; //Get WCF URL where this message was handled OperationContext op = OperationContext.Current; Message msg = op.RequestContext.RequestMessage; receiver.ReceiverUrl = msg.Headers.To.ToString(); receiver.ReceiverName = RECEIVER_NAME; receiver.Synchronization = EventReceiverSynchronization.Synchronous; cc.Web.EventReceivers.Add(receiver); cc.ExecuteQuery(); System.Diagnostics.Trace.WriteLine("Added ListAdded receiver at " + msg.Headers.To.ToString()); } } } }
public SPOEventReceiverDefinition AddEventReceiver( EventReceiverType eventType, string receiverAssembly, string receiverClass, string receiverName, string receiverUrl, int sequenceNumber, EventReceiverSynchronization synchronization) { EventReceiverDefinitionCreationInformation erdci = new EventReceiverDefinitionCreationInformation { EventType = eventType, ReceiverAssembly = receiverAssembly, ReceiverClass = receiverClass, ReceiverName = receiverName, ReceiverUrl = receiverUrl, SequenceNumber = sequenceNumber, Synchronization = synchronization }; return(AddEventReceiver(erdci)); }
public static void AddEventReceivers(List list, string receiverName, string receiverUrl) { ClientContext context = (ClientContext)list.Context; string receiverAssembly = Assembly.GetExecutingAssembly().FullName; EventReceiverDefinitionCollection eventReceivers = list.EventReceivers; string receiverClass = RECEIVERCLASSPREFIX + receiverName; EventReceiverDefinitionCreationInformation updatedEventReceiver = new EventReceiverDefinitionCreationInformation() { ReceiverAssembly = receiverAssembly, ReceiverName = receiverName, ReceiverClass = receiverClass, ReceiverUrl = receiverUrl, SequenceNumber = 1000, EventType = EventReceiverType.ItemUpdated }; context.Load(eventReceivers); context.ExecuteQuery(); list.EventReceivers.Add(updatedEventReceiver); context.ExecuteQuery(); EventReceiverDefinitionCreationInformation addedEventReceiver = new EventReceiverDefinitionCreationInformation() { ReceiverAssembly = receiverAssembly, ReceiverName = receiverName, ReceiverClass = receiverClass, ReceiverUrl = receiverUrl, SequenceNumber = 1000, EventType = EventReceiverType.ItemAdded }; context.Load(eventReceivers); context.ExecuteQuery(); list.EventReceivers.Add(addedEventReceiver); context.ExecuteQuery(); }
public void AssociateRemoteEventsToHostWeb(ClientContext clientContext) { var rerList = clientContext.Web.Lists.GetByTitle(LIST_TITLE); clientContext.Load(rerList); clientContext.ExecuteQuery(); bool rerExists = false; if (!rerExists) { //Get WCF URL where this message was handled OperationContext op = OperationContext.Current; Message msg = op.RequestContext.RequestMessage; EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation(); receiver.EventType = EventReceiverType.ItemAdded; receiver.ReceiverUrl = msg.Headers.To.ToString(); receiver.ReceiverName = EventReceiverType.ItemAdded.ToString(); receiver.Synchronization = EventReceiverSynchronization.Synchronous; receiver.SequenceNumber = 400; rerList.EventReceivers.Add(receiver); clientContext.ExecuteQuery(); System.Diagnostics.Trace.WriteLine("Added ItemAdded receiver at " + receiver.ReceiverUrl); receiver = new EventReceiverDefinitionCreationInformation(); receiver.EventType = EventReceiverType.ItemUpdated; receiver.ReceiverUrl = msg.Headers.To.ToString(); receiver.ReceiverName = EventReceiverType.ItemUpdated.ToString(); receiver.Synchronization = EventReceiverSynchronization.Synchronous; receiver.SequenceNumber = 400; rerList.EventReceivers.Add(receiver); clientContext.ExecuteQuery(); System.Diagnostics.Trace.WriteLine("Added ItemUpdated receiver at " + receiver.ReceiverUrl); } }
private void ProvisionNewServiceDeskRequestList() { using (var ctx = SPClientContext.Instance.GetContext()) { Web site = ctx.Web; List targetList = site.Lists.GetByTitle("ServiceDesk Requests"); try { ctx.Load(targetList); ctx.ExecuteQuery(); } catch (Exception ex) { ListCreationInformation listCreationInfo = new ListCreationInformation(); listCreationInfo.Title = "ServiceDesk Requests"; listCreationInfo.TemplateType = (int)ListTemplateType.GenericList; List oList = site.Lists.Add(listCreationInfo); ctx.ExecuteQuery(); oList.Fields.AddFieldAsXml("<Field DisplayName='Subject' Type='Text' />", true, AddFieldOptions.AddFieldToDefaultView); oList.Fields.AddFieldAsXml("<Field DisplayName='Body' Type='Note' />", true, AddFieldOptions.AddFieldToDefaultView); oList.Fields.AddFieldAsXml("<Field DisplayName='From' Type='User' List='UserInfo' />", true, AddFieldOptions.AddFieldToDefaultView); ctx.ExecuteQuery(); var eventRecievers = oList.EventReceivers; ctx.Load(eventRecievers); ctx.ExecuteQuery(); EventReceiverDefinitionCreationInformation eventReceiverInfo = new EventReceiverDefinitionCreationInformation(); eventReceiverInfo.EventType = EventReceiverType.ItemAdded; eventReceiverInfo.ReceiverClass = typeof(NewServiceDeskRequest).FullName; eventReceiverInfo.ReceiverName = "NewServiceDeskRequest Created"; eventReceiverInfo.ReceiverUrl = $"{ConfigurationManager.AppSettings["RemoteWebUrl"]}/Services/NewServiceDeskRequest.svc"; eventReceiverInfo.SequenceNumber = 1001; eventReceiverInfo.ReceiverAssembly = Assembly.GetExecutingAssembly().FullName; oList.EventReceivers.Add(eventReceiverInfo); oList.Update(); ctx.ExecuteQuery(); } } }
private void AttachEventHandler(string handlerEndpoint, List list, string name, EventReceiverType receiverType, ClientContext clientContext) { clientContext.Load(list, l => l.Title, l => l.EventReceivers.Include(e => e.ReceiverName)); clientContext.ExecuteQueryRetry(); var handlersToDelete = new List <EventReceiverDefinition>(); foreach (var eventReciever in list.EventReceivers) { if (eventReciever.ReceiverName == name) { handlersToDelete.Add(eventReciever); } } if (handlersToDelete.Count > 0) { foreach (var eventReceiverDefinition in handlersToDelete) { eventReceiverDefinition.DeleteObject(); } clientContext.ExecuteQueryRetry(); } var eventReceiver = new EventReceiverDefinitionCreationInformation { EventType = receiverType, ReceiverName = name, ReceiverUrl = handlerEndpoint, SequenceNumber = 10000, Synchronization = EventReceiverSynchronization.DefaultSynchronization }; list.EventReceivers.Add(eventReceiver); OnNotify(ProvisioningNotificationLevels.Verbose, "Attaching remote event handler to list " + list.Title + " | " + name); }
public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties) { SPRemoteEventResult result = new SPRemoteEventResult(); using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, false)) { if (clientContext != null) { clientContext.Load(clientContext.Web); clientContext.ExecuteQuery(); var requestProperty = (System.ServiceModel.Channels.HttpRequestMessageProperty)System.ServiceModel.OperationContext.Current.IncomingMessageProperties[System.ServiceModel.Channels.HttpRequestMessageProperty.Name]; string opContext = System.ServiceModel.OperationContext.Current.Channel.LocalAddress.Uri.AbsoluteUri.Substring(0, System.ServiceModel.OperationContext.Current.Channel.LocalAddress.Uri.AbsoluteUri.LastIndexOf("/")); string remoteUrl = string.Format("{0}/CreateSite.svc", opContext); //string remoteUrl = string.Format("{0}/CreateSite2.svc", System.ServiceModel.OperationContext.Current.Channel.LocalAddress.Uri.DnsSafeHost + "/services"); var appWebUrl = "https://" + requestProperty.Headers[System.Net.HttpRequestHeader.Host]; List createSiteRequests = clientContext.Web.Lists.GetByTitle("SiteCreationRequests"); if (properties.EventType == SPRemoteEventType.AppInstalled) { EventReceiverDefinitionCreationInformation newEventReceiver = new EventReceiverDefinitionCreationInformation() { EventType = EventReceiverType.ItemUpdated, ReceiverName = "CreateSite", ReceiverUrl = remoteUrl, SequenceNumber = 1000 //Should be higher number if lower priority, particularly for async events }; createSiteRequests.EventReceivers.Add(newEventReceiver); clientContext.ExecuteQuery(); } } } return result; }
/// <summary> /// Used to create a library & Rer for ItemAdded /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnScenario2_Click(object sender, EventArgs e) { var _libraryToCreate = this.GetLibaryInformationItemAdded(); var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var ctx = spContext.CreateUserClientContextForSPHost()) { try { if (!ctx.Web.ListExists(_libraryToCreate.Title)) { ScenarioHandler _scenario = new ScenarioHandler(); _scenario.CreateContosoDocumentLibrary(ctx, _libraryToCreate); } List _list = ctx.Web.Lists.GetByTitle(_libraryToCreate.Title); EventReceiverDefinitionCreationInformation _rec = ReceiverHelper.CreateEventReciever(ScenarioHandler.AUTOTAGGING_ITEM_ADDED_RERNAME, EventReceiverType.ItemAdded); ReceiverHelper.AddEventReceiver(ctx, _list, _rec); } catch (Exception) { } } }
public void AddEventRecieverToWorkflow(string listName) { var context = SPClientContext.Instance.GetContext(); Web site = context.Web; List serviceMarketingList = site.Lists.GetByTitle(listName); context.Load(serviceMarketingList.EventReceivers); context.ExecuteQuery(); bool eventAlreadyExists = serviceMarketingList.EventReceivers.Any(eventReceiver => eventReceiver.ReceiverName.Equals("Workflow Updated")); if (!eventAlreadyExists) { EventReceiverDefinitionCreationInformation eventReceiverInfo = new EventReceiverDefinitionCreationInformation(); eventReceiverInfo.EventType = EventReceiverType.ItemUpdated; eventReceiverInfo.ReceiverClass = typeof(WorkflowService).FullName; eventReceiverInfo.ReceiverName = "Workflow Updated"; eventReceiverInfo.ReceiverUrl = $"{ConfigurationManager.AppSettings["RemoteWebUrl"]}/Services/WorkflowService.svc"; eventReceiverInfo.SequenceNumber = 1001; eventReceiverInfo.ReceiverAssembly = Assembly.GetExecutingAssembly().FullName; serviceMarketingList.EventReceivers.Add(eventReceiverInfo); serviceMarketingList.Update(); context.ExecuteQuery(); } }
public void AssociateRemoteEventsToHostWeb(ClientContext clientContext) { var rerList = clientContext.Web.Lists.GetByTitle(LIST_TITLE); clientContext.Load(rerList); clientContext.ExecuteQuery(); bool rerExists = false; if (!rerExists) { //Get WCF URL where this message was handled OperationContext op = OperationContext.Current; Message msg = op.RequestContext.RequestMessage; EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation(); receiver.EventType = EventReceiverType.ItemAdding; receiver.ReceiverUrl = msg.Headers.To.ToString(); receiver.ReceiverName = EventReceiverType.ItemAdding.ToString(); receiver.Synchronization = EventReceiverSynchronization.Synchronous; receiver.SequenceNumber = 350; rerList.EventReceivers.Add(receiver); clientContext.ExecuteQuery(); System.Diagnostics.Trace.WriteLine("Added ItemAdded receiver at " + receiver.ReceiverUrl); receiver = new EventReceiverDefinitionCreationInformation(); receiver.EventType = EventReceiverType.ItemUpdated; receiver.ReceiverUrl = msg.Headers.To.ToString(); receiver.ReceiverName = EventReceiverType.ItemUpdated.ToString(); receiver.Synchronization = EventReceiverSynchronization.Synchronous; receiver.SequenceNumber = 350; rerList.EventReceivers.Add(receiver); clientContext.ExecuteQuery(); System.Diagnostics.Trace.WriteLine("Added ItemUpdated receiver at " + receiver.ReceiverUrl); } }
static public void CreateAnnouncementsList(ClientContext clientContext) { string listTitle = "Announcements"; // delete list if it exists ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext); using (scope.StartScope()) { using (scope.StartTry()) { clientContext.Web.Lists.GetByTitle(listTitle).DeleteObject(); } using (scope.StartCatch()) { } } // create and initialize ListCreationInformation object ListCreationInformation listInformation = new ListCreationInformation(); listInformation.Title = listTitle; listInformation.Url = "Lists/Announcements"; listInformation.QuickLaunchOption = QuickLaunchOptions.On; listInformation.TemplateType = (int)ListTemplateType.Announcements; // Add ListCreationInformation to lists collection and return list object List list = clientContext.Web.Lists.Add(listInformation); // modify additional list properties and update list.OnQuickLaunch = true; list.EnableAttachments = false; list.Update(); // send command to server to create list clientContext.ExecuteQuery(); clientContext.Load(list); clientContext.ExecuteQuery(); string urlEventReceiver = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + @"/Services/AnnouncementsEventReceiver.svc"; EventReceiverDefinitionCreationInformation erci1 = new EventReceiverDefinitionCreationInformation(); erci1.ReceiverName = "ItemAdding"; erci1.EventType = EventReceiverType.ItemAdding; erci1.ReceiverUrl = urlEventReceiver; erci1.SequenceNumber = 1000; EventReceiverDefinition er1 = list.EventReceivers.Add(erci1); er1.Update(); EventReceiverDefinitionCreationInformation erci2 = new EventReceiverDefinitionCreationInformation(); erci2.ReceiverName = "ItemUpdating"; erci2.EventType = EventReceiverType.ItemUpdating; erci2.ReceiverUrl = urlEventReceiver; erci2.SequenceNumber = 1000; EventReceiverDefinition er2 = list.EventReceivers.Add(erci2); er2.Update(); clientContext.ExecuteQuery(); ListItemCreationInformation lici = new ListItemCreationInformation(); var item1 = list.AddItem(lici); item1["Title"] = "SharePoint introduces new app model"; item1["Body"] = "<div>Developers wonder what happened to solutions.</div>"; item1["Expires"] = DateTime.Today.AddYears(10); item1.Update(); var item2 = list.AddItem(lici); item2["Title"] = "All SharePoint developers must now learn JavaScript"; item2["Body"] = "<div>Some developers are more excited than others.</div>"; item2["Expires"] = DateTime.Today.AddYears(1); item2.Update(); var item3 = list.AddItem(lici); item3["Title"] = "CSOM programming is super fun"; item3["Body"] = "<div>Just ask my mom.</div>"; item3["Expires"] = DateTime.Today.AddDays(7); item3.Update(); clientContext.ExecuteQuery(); }
public void AssociateRemoteEventsToHostWeb(ClientContext clientContext) { //Add Push Notification Feature to HostWeb //Not required here, just a demonstration that you //can activate features. clientContext.Web.Features.Add( new Guid("41e1d4bf-b1a2-47f7-ab80-d5d6cbba3092"), true, FeatureDefinitionScope.None); //Get the Title and EventReceivers lists clientContext.Load(clientContext.Web.Lists, lists => lists.Include( list => list.Title, list => list.EventReceivers).Where (list => list.Title == LIST_TITLE)); clientContext.ExecuteQuery(); List jobsList = clientContext.Web.Lists.FirstOrDefault(); #if (DEBUG) // In debug mode we will delete the existing list, so we prevent our system from orphaned event receicers. // RemoveEventReceiversFromHostWeb is sometimes not called in debug mode and/or the app id has changed. // On RER registration SharePoint adds the app id to the event registration information, and you are only able // to remove the event with the same app where it was registered. Also note that you would need to completely // uninstall an app before SharePoint will trigger the appuninstalled event. From the documentation: // The **AppUninstalling** event only fires when a user completely removes the add-in: the add-in needs to be deleted // from the site recycle bins in an end-user scenario. In a development scenario the add-in needs to be removed from // the “Apps in testing” library. if (null != jobsList) { jobsList.DeleteObject(); clientContext.ExecuteQuery(); jobsList = null; } #endif bool rerExists = false; if (null == jobsList) { //List does not exist, create it jobsList = CreateJobsList(clientContext); } else { foreach (var rer in jobsList.EventReceivers) { if (rer.ReceiverName == RECEIVER_NAME) { rerExists = true; System.Diagnostics.Trace.WriteLine("Found existing ItemAdded receiver at " + rer.ReceiverUrl); } } } if (!rerExists) { EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation(); receiver.EventType = EventReceiverType.ItemAdded; //Get WCF URL where this message was handled OperationContext op = OperationContext.Current; Message msg = op.RequestContext.RequestMessage; receiver.ReceiverUrl = msg.Headers.To.ToString(); receiver.ReceiverName = RECEIVER_NAME; receiver.Synchronization = EventReceiverSynchronization.Synchronous; //Add the new event receiver to a list in the host web jobsList.EventReceivers.Add(receiver); clientContext.ExecuteQuery(); System.Diagnostics.Trace.WriteLine("Added ItemAdded receiver at " + receiver.ReceiverUrl); } }
public static EventReceiverDefinition RegisterEventReceiver(List list, string name, string url, EventReceiverType eventReceiverType, EventReceiverSynchronization synchronization, bool force, ClientContext clientContext) { clientContext.Load(list.EventReceivers); clientContext.ExecuteQuery(); bool receiverExists = false; foreach (var receiver in list.EventReceivers) { if (receiver.ReceiverName == name) { receiverExists = true; if (force) { receiver.DeleteObject(); clientContext.ExecuteQuery(); receiverExists = false; } } } EventReceiverDefinition def = null; if (!receiverExists) { EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation(); receiver.EventType = eventReceiverType; receiver.ReceiverUrl = url; receiver.ReceiverName = name; receiver.Synchronization = synchronization; def = list.EventReceivers.Add(receiver); clientContext.Load(def); clientContext.ExecuteQuery(); } return def; }
private static bool ContainsECMRecordEventReceiver(EventReceiverDefinitionCreationInformation receiverToAdd, List<EventReceiverDefinition> currentEventReceivers) { foreach(EventReceiverDefinition eventReceiver in currentEventReceivers) { if (eventReceiver.EventType.Equals(receiverToAdd.EventType) && eventReceiver.ReceiverAssembly.Equals(receiverToAdd.ReceiverAssembly) && eventReceiver.ReceiverClass.Equals(receiverToAdd.ReceiverClass) && eventReceiver.ReceiverName.Equals(receiverToAdd.ReceiverName) && eventReceiver.SequenceNumber.Equals(receiverToAdd.SequenceNumber) && eventReceiver.Synchronization.Equals(receiverToAdd.Synchronization)) { return true; } } return false; }
private static void RegisterExpectedShipmentsEventHandler(HttpRequest request) { using (var clientContext = sPContext.CreateUserClientContextForSPHost()) { var query = from list in clientContext.Web.Lists where list.Title == "Expected Shipments" select list; IEnumerable<List> matchingLists = clientContext.LoadQuery(query); clientContext.ExecuteQuery(); List expectedShipmentsList = matchingLists.Single(); EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation(); receiver.ReceiverName = "ExpectedShipmentsItemUpdated"; receiver.EventType = EventReceiverType.ItemUpdated; #if DEBUG receiver.ReceiverUrl = WebConfigurationManager.AppSettings["RERdebuggingServiceBusUrl"].ToString(); #else receiver.ReceiverUrl = "https://" + request.Headers["Host"] + "/Services/RemoteEventReceiver1.svc"; #endif expectedShipmentsList.EventReceivers.Add(receiver); clientContext.ExecuteQuery(); } }
public void AssociateRemoteEventsToHostWeb(ClientContext clientContext) { try { //Getting Host Web var hostWeb = clientContext.Web; clientContext.Load(hostWeb); //Getting event receivers on the web clientContext.Load(hostWeb.EventReceivers); clientContext.ExecuteQuery(); bool rerExists = false; if(null != hostWeb && hostWeb.EventReceivers.Count > 0) { foreach(var rer in hostWeb.EventReceivers) { if(rer.ReceiverName == RECEIVER_NAME) { rerExists = true; System.Diagnostics.Trace.WriteLine("Found existing event receiver at " + rer.ReceiverUrl); break; } } } if(!rerExists) { //registering ListAdding event on the web EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation(); receiver.EventType = EventReceiverType.ListAdded; //Get WCF URL where this message was handled OperationContext op = OperationContext.Current; Message msg = op.RequestContext.RequestMessage; receiver.ReceiverUrl = msg.Headers.To.ToString(); receiver.ReceiverName = RECEIVER_NAME; receiver.Synchronization = EventReceiverSynchronization.Asynchronous; hostWeb.EventReceivers.Add(receiver); clientContext.ExecuteQuery(); System.Diagnostics.Trace.WriteLine("Added ListAdded event at " + receiver.ReceiverUrl); } } catch (Exception ex) { } //get the title and event receiver list /*clientContext.Load(clientContext.Web.Lists, lists => lists.Include(list => list.Title, list => list.EventReceivers) .Where(list => list.Title == LIST_TITLE)); clientContext.ExecuteQuery(); List targetList = clientContext.Web.Lists.FirstOrDefault(); bool rerExists = false; if( null != targetList) { foreach(var rer in targetList.EventReceivers) { if(rer.ReceiverName == RECEIVER_NAME) { rerExists = true; System.Diagnostics.Trace.WriteLine("Found existing event receiver at " + rer.ReceiverUrl); } } } if(!rerExists) { EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation(); receiver.EventType = EventReceiverType.ItemAdding; //Get WCF URL where this message was handled OperationContext op = OperationContext.Current; Message msg = op.RequestContext.RequestMessage; receiver.ReceiverUrl = msg.Headers.To.ToString(); receiver.ReceiverName = RECEIVER_NAME; receiver.Synchronization = EventReceiverSynchronization.Synchronous; targetList.EventReceivers.Add(receiver); clientContext.ExecuteQuery(); System.Diagnostics.Trace.WriteLine("Added ItemAdding event at " + receiver.ReceiverUrl); }*/ }
public SPOEventReceiverDefinition AddEventReceiver( EventReceiverType eventType, string receiverAssembly, string receiverClass, string receiverName, string receiverUrl, int sequenceNumber, EventReceiverSynchronization synchronization) { EventReceiverDefinitionCreationInformation erdci = new EventReceiverDefinitionCreationInformation { EventType = eventType, ReceiverAssembly = receiverAssembly, ReceiverClass = receiverClass, ReceiverName = receiverName, ReceiverUrl = receiverUrl, SequenceNumber = sequenceNumber, Synchronization = synchronization }; return AddEventReceiver(erdci); }
public SPOEventReceiverDefinition AddEventReceiver(EventReceiverDefinitionCreationInformation erdci) { SPOEventReceiverDefinition erd = new SPOEventReceiverDefinition(_web.EventReceivers.Add(erdci), _web.EventReceivers); _web.EventReceivers.Context.ExecuteQuery(); return erd; }
private void HandleAppInstalled(SPRemoteEventProperties properties) { using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, false)) { if (clientContext != null) { //Check for fields that need adding Web rootWeb = clientContext.Site.RootWeb; clientContext.Load(rootWeb, w => w.Fields); clientContext.ExecuteQuery(); ListCreationInformation listCreationInfo = new ListCreationInformation(); listCreationInfo.Title = ListHtmlToPdf; listCreationInfo.TemplateType = (int)ListTemplateType.GenericList; List oList = rootWeb.Lists.Add(listCreationInfo); clientContext.ExecuteQuery(); //Title included by default. //Field for HTML Field oField = oList.Fields.AddFieldAsXml("<Field DisplayName='HtmlToConvert' Name='HtmlToConvert' Type='Note' RichText='FALSE' />", true, AddFieldOptions.AddFieldInternalNameHint); //Field for FileName for resulting PDF oField = oList.Fields.AddFieldAsXml("<Field DisplayName='DocFileName' Name='DocFileName' Type='Text' />", true, AddFieldOptions.AddFieldInternalNameHint); //Field for doc library name for resulting PDF oField = oList.Fields.AddFieldAsXml("<Field DisplayName='DocLibraryName' Name='DocLibraryName' Type='Text' />", true, AddFieldOptions.AddFieldInternalNameHint); //Field for folder name for resulting PDF oField = oList.Fields.AddFieldAsXml("<Field DisplayName='FolderName' Name='FolderName' Type='Text' />", true, AddFieldOptions.AddFieldInternalNameHint); //Field for metadata oField = oList.Fields.AddFieldAsXml("<Field DisplayName='DocMetaData' Name='DocMetaData' Description='Name value pairs' Type='Note' RichText='FALSE' />", true, AddFieldOptions.AddFieldInternalNameHint); //Field for PDF options oField = oList.Fields.AddFieldAsXml("<Field DisplayName='ConversionOptions' Name='ConversionOptions' Description='Bitwise numeric value' Type='Number' />", true, AddFieldOptions.AddFieldInternalNameHint); //Field for error if conversion fails oField = oList.Fields.AddFieldAsXml("<Field DisplayName='ErrorMessage' Name='ErrorMessage' Type='Note' RichText='FALSE' />", true, AddFieldOptions.AddFieldInternalNameHint); clientContext.ExecuteQuery(); //Add event receiver EventReceiverDefinitionCreationInformation receiver = null; receiver = new EventReceiverDefinitionCreationInformation { EventType = EventReceiverType.ItemAdded, Synchronization = EventReceiverSynchronization.Asynchronous }; OperationContext op = OperationContext.Current; Message msg = op.RequestContext.RequestMessage; receiver.ReceiverUrl = msg.Headers.To.ToString(); receiver.ReceiverName = ListHtmlToPdf + "-ListItemAddedEvent"; oList.EventReceivers.Add(receiver); clientContext.ExecuteQuery(); System.Diagnostics.Trace.WriteLine("Added ItemAdded receiver at " + msg.Headers.To.ToString()); } } }
private void CreateSiteRequestList(ClientContext ctx) { bool rerExists = false; var web = ctx.Web; ctx.Load(ctx.Web.Lists, lists => lists.Include( list => list.Title, list => list.EventReceivers).Where (list => list.Title == Lists.SiteRepositoryTitle)); ctx.ExecuteQuery(); List requestList = ctx.Web.Lists.FirstOrDefault(); if(requestList == null) { var newList = new ListCreationInformation() { Title = Lists.SiteRepositoryTitle, Description = Lists.SiteRepositoryDesc, TemplateType = (int)ListTemplateType.GenericList, Url = Lists.SiteRepositoryUrl }; requestList = ctx.Web.Lists.Add(newList); ctx.Load(requestList); ctx.ExecuteQuery(); // add fields (replace the second field with the display name AddFieldAsXml(requestList, SiteRequestFields.Description, SiteRequestFields.DescriptionDisplayName, SiteRequestFields.DescriptionId, "Note", options: AddFieldOptions.AddFieldCheckDisplayName); AddFieldAsXml(requestList, SiteRequestFields.Template, SiteRequestFields.TemplateDisplayName, SiteRequestFields.TemplateId); AddFieldAsXml(requestList, SiteRequestFields.Policy, SiteRequestFields.PolicyDisplayName, SiteRequestFields.PolicyId); AddFieldAsXml(requestList, SiteRequestFields.Url, SiteRequestFields.UrlDisplayName, SiteRequestFields.UrlId); AddFieldAsXml(requestList, SiteRequestFields.Owner, SiteRequestFields.OwnerDisplayName, SiteRequestFields.OwnerId, "User", "List='UserInfo' UserSelectionMode='0' ShowField='ImnName'"); AddFieldAsXml(requestList, SiteRequestFields.AdditionalOwners, SiteRequestFields.AdditionalOwnersDisplayName, SiteRequestFields.AdditionalOwnersId, "UserMulti", "Mult='TRUE' List='UserInfo' UserSelectionMode='1' ShowField='ImnName'"); AddFieldAsXml(requestList, SiteRequestFields.Lcid, SiteRequestFields.LcidDisplayName, SiteRequestFields.LcidId); AddFieldAsXml(requestList, SiteRequestFields.StatusMessage, SiteRequestFields.StatusMessageDisplayName, SiteRequestFields.StatusMessageId, "Note", options: AddFieldOptions.AddFieldCheckDisplayName); AddFieldAsXml(requestList, SiteRequestFields.TimeZone, SiteRequestFields.TimeZoneDisplayName, SiteRequestFields.TimeZoneId); AddFieldAsXml(requestList, SiteRequestFields.State, SiteRequestFields.StateDisplayName, SiteRequestFields.StatusId); requestList.Update(); ctx.ExecuteQuery(); } else { foreach (var rer in requestList.EventReceivers) { if (rer.ReceiverName == RECEIVER_NAME) { rerExists = true; System.Diagnostics.Trace.WriteLine("Found existing ItemAdded receiver at " + rer.ReceiverUrl); } } } if (!rerExists) { EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation(); receiver.EventType = EventReceiverType.ItemUpdated; //Get WCF URL where this message was handled OperationContext op = OperationContext.Current; Message msg = op.RequestContext.RequestMessage; receiver.ReceiverUrl = msg.Headers.To.ToString(); receiver.ReceiverName = RECEIVER_NAME; //Add the new event receiver to a list in the host web requestList.EventReceivers.Add(receiver); ctx.ExecuteQuery(); } }
public static void EnableDisableTagging(ClientContext ctx,List TargetList,bool AttachEvents,AppWebHelper hlp) { LogHelper.Log("Entering EnableDisableTagging"); if (!AttachEvents) { try { var TargetItemAddedEvent = TargetList.EventReceivers.Where( ev => ev.ReceiverName == Constants.ItemAddedEventReceiverName).SingleOrDefault(); if (TargetItemAddedEvent != null) { TargetItemAddedEvent.DeleteObject(); } var TargetFieldAddedEvent = TargetList.EventReceivers.Where( ev => ev.ReceiverName == Constants.FieldDeletedEventReceiverName).SingleOrDefault(); if (TargetFieldAddedEvent != null) { TargetFieldAddedEvent.DeleteObject(); } if(TargetItemAddedEvent != null || TargetFieldAddedEvent != null) { ctx.ExecuteQuery(); } } catch (Exception ex) { LogHelper.Log(ex.Message + ex.StackTrace, LogSeverity.Error); } } else { try { int Sequence = 10; EventReceiverDefinitionCreationInformation ItemAddedDef = new EventReceiverDefinitionCreationInformation(); ItemAddedDef.EventType = EventReceiverType.ItemAdded; ItemAddedDef.ReceiverName = Constants.ItemAddedEventReceiverName; ItemAddedDef.ReceiverUrl = ConfigurationHelper.GetReceiverUrl(); ItemAddedDef.ReceiverAssembly = Assembly.GetExecutingAssembly().FullName; ItemAddedDef.ReceiverClass = ConfigurationHelper.GetReceiverClass(); if(!hlp.ListsInfo.ContainsKey(TargetList.Id.ToString())) { ItemAddedDef.Synchronization = EventReceiverSynchronization.Asynchronous; } else { if (hlp.ListsInfo[TargetList.Id.ToString()].Asynchronous) { ItemAddedDef.Synchronization = EventReceiverSynchronization.Asynchronous; } else { ItemAddedDef.Synchronization = EventReceiverSynchronization.Synchronous; } } ItemAddedDef.SequenceNumber = Sequence; EventReceiverDefinitionCreationInformation FieldDeletedDef = new EventReceiverDefinitionCreationInformation(); FieldDeletedDef.EventType = EventReceiverType.FieldDeleted; FieldDeletedDef.ReceiverName = Constants.FieldDeletedEventReceiverName; FieldDeletedDef.ReceiverUrl = ConfigurationHelper.GetReceiverUrl(); FieldDeletedDef.ReceiverAssembly = Assembly.GetExecutingAssembly().FullName; FieldDeletedDef.ReceiverClass = ConfigurationHelper.GetReceiverClass(); FieldDeletedDef.Synchronization = EventReceiverSynchronization.Asynchronous; TargetList.EventReceivers.Add(ItemAddedDef); TargetList.EventReceivers.Add(FieldDeletedDef); TargetList.Update(); ctx.ExecuteQuery(); LogHelper.Log("Attached AutoTagging for " + ItemAddedDef.EventType.ToString() + " on " + TargetList.Id); } catch (Exception ex) { LogHelper.Log(ex.Message+ex.StackTrace,LogSeverity.Error); } } }
public void AssociateRemoteEventsToHostWeb(ClientContext clientContext) { //Add Push Notification Feature to HostWeb //Not required here, just a demonstration that you //can activate features. clientContext.Web.Features.Add( new Guid("41e1d4bf-b1a2-47f7-ab80-d5d6cbba3092"), true, FeatureDefinitionScope.None); //Get the Title and EventReceivers lists clientContext.Load(clientContext.Web.Lists, lists => lists.Include( list => list.Title, list => list.EventReceivers).Where (list => list.Title == LIST_TITLE)); clientContext.ExecuteQuery(); List jobsList = clientContext.Web.Lists.FirstOrDefault(); bool rerExists = false; if (null == jobsList) { //List does not exist, create it jobsList = CreateJobsList(clientContext); } else { foreach (var rer in jobsList.EventReceivers) { if (rer.ReceiverName == RECEIVER_NAME) { rerExists = true; System.Diagnostics.Trace.WriteLine("Found existing ItemAdded receiver at " + rer.ReceiverUrl); } } } if (!rerExists) { EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation(); receiver.EventType = EventReceiverType.ItemAdded; //Get WCF URL where this message was handled OperationContext op = OperationContext.Current; Message msg = op.RequestContext.RequestMessage; receiver.ReceiverUrl = msg.Headers.To.ToString(); receiver.ReceiverName = RECEIVER_NAME; receiver.Synchronization = EventReceiverSynchronization.Synchronous; //Add the new event receiver to a list in the host web jobsList.EventReceivers.Add(receiver); clientContext.ExecuteQuery(); System.Diagnostics.Trace.WriteLine("Added ItemAdded receiver at " + receiver.ReceiverUrl); } }
public void AssociateRemoteEventsToHostWeb(ClientContext clientContext) { //Get the Title and EventReceivers lists clientContext.Load(clientContext.Web.Lists, lists => lists.Include( list => list.Title, list => list.EventReceivers).Where (list => list.Title == LIST_TITLE)); clientContext.ExecuteQuery(); List jobsList = clientContext.Web.Lists.FirstOrDefault(); //#if (DEBUG) // // In debug mode we will delete the existing list, so we prevent our system from orphaned event receicers. // // RemoveEventReceiversFromHostWeb is sometimes not called in debug mode and/or the app id has changed. // // On RER registration SharePoint adds the app id to the event registration information, and you are only able // // to remove the event with the same app where it was registered. Also note that you would need to completely // // uninstall an app before SharePoint will trigger the appuninstalled event. From the documentation: // // The **AppUninstalling** event only fires when a user completely removes the add-in: the add-in needs to be deleted // // from the site recycle bins in an end-user scenario. In a development scenario the add-in needs to be removed from // // the “Apps in testing” library. // if (null != jobsList) // { // jobsList.DeleteObject(); // clientContext.ExecuteQuery(); // jobsList = null; // } //#endif bool rerExists = false; if (null == jobsList) { //List does not exist, create it jobsList = CreateJobsList(clientContext); } else { foreach (var rer in jobsList.EventReceivers) { if (rer.ReceiverName == RECEIVER_NAME) { rerExists = true; System.Diagnostics.Trace.WriteLine("Found existing ItemAdded receiver at " + rer.ReceiverUrl); } } } ////Add eventreceiver if (!rerExists) { EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation(); receiver.EventType = EventReceiverType.ItemAdded; //Get WCF URL where this message was handled OperationContext op = OperationContext.Current; Message msg = op.RequestContext.RequestMessage; receiver.ReceiverUrl = msg.Headers.To.ToString(); receiver.ReceiverName = RECEIVER_NAME; receiver.Synchronization = EventReceiverSynchronization.Synchronous; //Add the new event receiver to a list in the host web jobsList.EventReceivers.Add(receiver); clientContext.ExecuteQuery(); System.Diagnostics.Trace.WriteLine("Added ItemAdded receiver at " + receiver.ReceiverUrl); } }
public void AssociateRemoteEventsToHostWeb(ClientContext clientContext) { //Add Push Notification Feature to HostWeb //Not required here, just a demonstration that you //can activate features. clientContext.Web.Features.Add( new Guid("41e1d4bf-b1a2-47f7-ab80-d5d6cbba3092"), true, FeatureDefinitionScope.None); //Get the Title and EventReceivers lists clientContext.Load(clientContext.Web.Lists, lists => lists.Include( list => list.Title, list => list.EventReceivers).Where (list => list.Title == LIST_TITLE)); clientContext.ExecuteQuery(); List jobsList = clientContext.Web.Lists.FirstOrDefault(); bool rerExists = false; if (null == jobsList) { //List does not exist, create it jobsList = CreateJobsList(clientContext); } else { foreach (var rer in jobsList.EventReceivers) { if (rer.ReceiverName == RECEIVER_NAME) { rerExists = true; System.Diagnostics.Trace.WriteLine("Found existing ItemAdded receiver at " + rer.ReceiverUrl); } } } if (!rerExists) { EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation(); receiver.EventType = EventReceiverType.ItemAdded; //Get WCF URL where this message was handled OperationContext op = OperationContext.Current; Message msg = op.RequestContext.RequestMessage; receiver.ReceiverUrl = msg.Headers.To.ToString(); receiver.ReceiverName = RECEIVER_NAME; receiver.Synchronization = EventReceiverSynchronization.Synchronous; //Add the new event receiver to a list in the host web jobsList.EventReceivers.Add(receiver); clientContext.ExecuteQuery(); System.Diagnostics.Trace.WriteLine("Added ItemAdded receiver at " + receiver.ReceiverUrl); } }
public void AssociateRemoteEventsToHostWeb(ClientContext clientContext) { Helper.AddLog("RemoteEventReceiverManager-AssociateRemoteEventsToHostWeb", "On Started"); try { List jobsList = clientContext.Web.Lists.GetByTitle(LIST_TITLE); clientContext.Load(jobsList, l => l.Title, l => l.EventReceivers); clientContext.ExecuteQuery(); Helper.AddLog("RemoteEventReceiverManager-AssociateRemoteEventsToHostWeb", "Read List"); bool rerExists = false; foreach (var rer in jobsList.EventReceivers) { if (rer.ReceiverName.Contains("RemoteEventReceiver1Item")) { Helper.AddLog("RemoteEventReceiverManager-AssociateRemoteEventsToHostWeb", "Removing Event Receiver : " + rer.ReceiverName); RemoveEventReceiversFromHostWeb(clientContext, rer.ReceiverName); Helper.AddLog("RemoteEventReceiverManager-AssociateRemoteEventsToHostWeb", "Removed Event Receiver : " + rer.ReceiverName); //rerExists = true; System.Diagnostics.Trace.WriteLine("Found existing ItemAdded receiver at " + rer.ReceiverUrl); } } if (!rerExists) { Helper.AddLog("RemoteEventReceiverManager-AssociateRemoteEventsToHostWeb", "Adding Event Receiver 1"); //should be in config string url = "https://remoteeventreceiverfortaskbs.azurewebsites.net/Services/AppEventReceiver.svc"; Helper.AddLog("RemoteEventReceiverManager-AssociateRemoteEventsToHostWeb", url); EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation(); receiver.EventType = EventReceiverType.ItemUpdating; receiver.ReceiverUrl = url; Helper.AddLog("RemoteEventReceiverManager-AssociateRemoteEventsToHostWeb", Assembly.GetExecutingAssembly().FullName); receiver.ReceiverAssembly = Assembly.GetExecutingAssembly().FullName; receiver.ReceiverClass = "AppEventReceiver"; receiver.ReceiverName = "RemoteEventReceiver1ItemUpdating"; receiver.SequenceNumber = 1009; receiver.Synchronization = EventReceiverSynchronization.Synchronous; //Add the new event receiver to a list in the host web jobsList.EventReceivers.Add(receiver); //clientContext.ExecuteQuery(); Helper.AddLog("RemoteEventReceiverManager-AssociateRemoteEventsToHostWeb", "Adding Event Receiver 2"); EventReceiverDefinitionCreationInformation receiver2 = new EventReceiverDefinitionCreationInformation(); receiver2.EventType = EventReceiverType.ItemUpdated; receiver2.ReceiverUrl = url; Helper.AddLog("RemoteEventReceiverManager-AssociateRemoteEventsToHostWeb", Assembly.GetExecutingAssembly().FullName); receiver2.ReceiverAssembly = Assembly.GetExecutingAssembly().FullName; receiver2.ReceiverClass = "AppEventReceiver"; receiver2.ReceiverName = "RemoteEventReceiver1ItemUpdated"; receiver2.SequenceNumber = 1008; receiver2.Synchronization = EventReceiverSynchronization.Synchronous; //Add the new event receiver to a list in the host web jobsList.EventReceivers.Add(receiver2); clientContext.ExecuteQuery(); EventReceiverDefinitionCreationInformation receiver3 = new EventReceiverDefinitionCreationInformation(); receiver3.EventType = EventReceiverType.ItemAdded; receiver3.ReceiverUrl = url; Helper.AddLog("RemoteEventReceiverManager-AssociateRemoteEventsToHostWeb", Assembly.GetExecutingAssembly().FullName); receiver3.ReceiverAssembly = Assembly.GetExecutingAssembly().FullName; receiver3.ReceiverClass = "AppEventReceiver"; receiver3.ReceiverName = "RemoteEventReceiver1ItemAdded"; receiver3.SequenceNumber = 1007; receiver3.Synchronization = EventReceiverSynchronization.Asynchronous; jobsList.EventReceivers.Add(receiver3); clientContext.ExecuteQuery(); Helper.AddLog("RemoteEventReceiverManager-AssociateRemoteEventsToHostWeb", "Added Event Receiver 1 , 2 and 3"); System.Diagnostics.Trace.WriteLine("Added ItemAdded receiver at " + receiver.ReceiverUrl); } } catch (Exception ex) { Helper.AddLog("RemoteEventReceiverManager-AssociateRemoteEventsToHostWeb", "Adding Event Receiver Error " + ex.ToString()); } }
/// <summary> /// Defines if auto record declaration is active for this list: all added items will be automatically declared as a record if active /// </summary> /// <param name="list">List to operate on</param> /// <param name="autoDeclareRecords">True to automatically declare all added items as record, false otherwise</param> public static void SetListAutoRecordDeclaration(this List list, bool autoDeclareRecords) { //Determine the SharePoint version based on the loaded CSOM library var asm = Assembly.GetAssembly(typeof(Site)); var sharePointVersion = asm.GetName().Version.Major; if (autoDeclareRecords) { //Set the property that dictates custom list record settings to true list.SetPropertyBagValue(ECM_IPR_LIST_USE_LIST_SPECIFIC, true.ToString()); //Prevent manual declaration list.SetPropertyBagValue(ECM_ALLOW_MANUAL_DECLARATION, false.ToString()); //Hookup the needed event handlers list.Context.Load(list.EventReceivers); list.Context.ExecuteQueryRetry(); List <EventReceiverDefinition> currentEventReceivers = new List <EventReceiverDefinition>(list.EventReceivers.Count); currentEventReceivers.AddRange(list.EventReceivers); // Track changes to see if an list.Update is needed bool eventReceiverAdded = false; //ItemUpdating receiver EventReceiverDefinitionCreationInformation newEventReceiver = CreateECMRecordEventReceiverDefinition(EventReceiverType.ItemUpdating, 1000, sharePointVersion); if (!ContainsECMRecordEventReceiver(newEventReceiver, currentEventReceivers)) { list.EventReceivers.Add(newEventReceiver); eventReceiverAdded = true; } //ItemDeleting receiver newEventReceiver = CreateECMRecordEventReceiverDefinition(EventReceiverType.ItemDeleting, 1000, sharePointVersion); if (!ContainsECMRecordEventReceiver(newEventReceiver, currentEventReceivers)) { list.EventReceivers.Add(newEventReceiver); eventReceiverAdded = true; } //ItemFileMoving receiver newEventReceiver = CreateECMRecordEventReceiverDefinition(EventReceiverType.ItemFileMoving, 1000, sharePointVersion); if (!ContainsECMRecordEventReceiver(newEventReceiver, currentEventReceivers)) { list.EventReceivers.Add(newEventReceiver); eventReceiverAdded = true; } //ItemAdded receiver newEventReceiver = CreateECMRecordEventReceiverDefinition(EventReceiverType.ItemAdded, 1005, sharePointVersion); if (!ContainsECMRecordEventReceiver(newEventReceiver, currentEventReceivers)) { list.EventReceivers.Add(newEventReceiver); eventReceiverAdded = true; } //ItemUpdated receiver newEventReceiver = CreateECMRecordEventReceiverDefinition(EventReceiverType.ItemUpdated, 1007, sharePointVersion); if (!ContainsECMRecordEventReceiver(newEventReceiver, currentEventReceivers)) { list.EventReceivers.Add(newEventReceiver); eventReceiverAdded = true; } //ItemCheckedIn receiver newEventReceiver = CreateECMRecordEventReceiverDefinition(EventReceiverType.ItemCheckedIn, 1006, sharePointVersion); if (!ContainsECMRecordEventReceiver(newEventReceiver, currentEventReceivers)) { list.EventReceivers.Add(newEventReceiver); eventReceiverAdded = true; } if (eventReceiverAdded) { list.Update(); list.Context.ExecuteQueryRetry(); } //Set the property that dictates the auto declaration list.SetPropertyBagValue(ECM_AUTO_DECLARE_RECORDS, autoDeclareRecords.ToString()); } else { //Set the property that dictates the auto declaration list.SetPropertyBagValue(ECM_AUTO_DECLARE_RECORDS, autoDeclareRecords.ToString()); //Note: existing list event handlers will just stay as they are, no need to remove them } }
public static void EnableDisableTagging(ClientContext ctx, List TargetList, bool AttachEvents, AppWebHelper hlp) { LogHelper.Log("Entering EnableDisableTagging"); if (!AttachEvents) { try { var TargetItemAddedEvent = TargetList.EventReceivers.Where( ev => ev.ReceiverName == Constants.ItemAddedEventReceiverName).SingleOrDefault(); if (TargetItemAddedEvent != null) { TargetItemAddedEvent.DeleteObject(); } var TargetFieldAddedEvent = TargetList.EventReceivers.Where( ev => ev.ReceiverName == Constants.FieldDeletedEventReceiverName).SingleOrDefault(); if (TargetFieldAddedEvent != null) { TargetFieldAddedEvent.DeleteObject(); } if (TargetItemAddedEvent != null || TargetFieldAddedEvent != null) { ctx.ExecuteQuery(); } } catch (Exception ex) { LogHelper.Log(ex.Message + ex.StackTrace, LogSeverity.Error); } } else { try { int Sequence = 10; EventReceiverDefinitionCreationInformation ItemAddedDef = new EventReceiverDefinitionCreationInformation(); ItemAddedDef.EventType = EventReceiverType.ItemAdded; ItemAddedDef.ReceiverName = Constants.ItemAddedEventReceiverName; ItemAddedDef.ReceiverUrl = ConfigurationHelper.GetReceiverUrl(); ItemAddedDef.ReceiverAssembly = Assembly.GetExecutingAssembly().FullName; ItemAddedDef.ReceiverClass = ConfigurationHelper.GetReceiverClass(); if (!hlp.ListsInfo.ContainsKey(TargetList.Id.ToString())) { ItemAddedDef.Synchronization = EventReceiverSynchronization.Asynchronous; } else { if (hlp.ListsInfo[TargetList.Id.ToString()].Asynchronous) { ItemAddedDef.Synchronization = EventReceiverSynchronization.Asynchronous; } else { ItemAddedDef.Synchronization = EventReceiverSynchronization.Synchronous; } } ItemAddedDef.SequenceNumber = Sequence; EventReceiverDefinitionCreationInformation FieldDeletedDef = new EventReceiverDefinitionCreationInformation(); FieldDeletedDef.EventType = EventReceiverType.FieldDeleted; FieldDeletedDef.ReceiverName = Constants.FieldDeletedEventReceiverName; FieldDeletedDef.ReceiverUrl = ConfigurationHelper.GetReceiverUrl(); FieldDeletedDef.ReceiverAssembly = Assembly.GetExecutingAssembly().FullName; FieldDeletedDef.ReceiverClass = ConfigurationHelper.GetReceiverClass(); FieldDeletedDef.Synchronization = EventReceiverSynchronization.Asynchronous; TargetList.EventReceivers.Add(ItemAddedDef); TargetList.EventReceivers.Add(FieldDeletedDef); TargetList.Update(); ctx.ExecuteQuery(); LogHelper.Log("Attached AutoTagging for " + ItemAddedDef.EventType.ToString() + " on " + TargetList.Id); } catch (Exception ex) { LogHelper.Log(ex.Message + ex.StackTrace, LogSeverity.Error); } } }
public void AssociateRemoteEventsToHostWeb(ClientContext clientContext) { if (Global.globalY != 1) { Global.globalError += "28-"; //Add Push Notification Feature to HostWeb //Not required here, just a demonstration that you //can activate features. clientContext.Web.Features.Add( new Guid("41e1d4bf-b1a2-47f7-ab80-d5d6cbba3092"), true, FeatureDefinitionScope.None); Global.globalError += "36-"; //Get the Title and EventReceivers lists clientContext.Load(clientContext.Web.Lists, lists => lists.Include( list => list.Title, list => list.EventReceivers).Where (list => list.Title == LIST_TITLE)); clientContext.ExecuteQuery(); Global.globalError += "45-"; List jobsList = clientContext.Web.Lists.FirstOrDefault(); #if (DEBUG) // In debug mode we will delete the existing list, so we prevent our system from orphaned event receicers. // RemoveEventReceiversFromHostWeb is sometimes not called in debug mode and/or the app id has changed. // On RER registration SharePoint adds the app id to the event registration information, and you are only able // to remove the event with the same app where it was registered. Also note that you would need to completely // uninstall an app before SharePoint will trigger the appuninstalled event. From the documentation: // The **AppUninstalling** event only fires when a user completely removes the add-in: the add-in needs to be deleted // from the site recycle bins in an end-user scenario. In a development scenario the add-in needs to be removed from // the “Apps in testing” library. if (null != jobsList) { jobsList.DeleteObject(); clientContext.ExecuteQuery(); jobsList = null; } #endif Global.globalError += "65-"; bool rerExists = false; if (null == jobsList) { //List does not exist, create it jobsList = CreateJobsList(clientContext); Global.globalError += "72-"; } else { foreach (var rer in jobsList.EventReceivers) { if (rer.ReceiverName == RECEIVER_NAME) { rerExists = true; System.Diagnostics.Trace.WriteLine("Found existing ItemAdded receiver at " + rer.ReceiverUrl); } } } Global.globalError += "87-"; if (!rerExists) { EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation(); receiver.EventType = EventReceiverType.ItemAdded; //Get WCF URL where this message was handled //System.ServiceModel.OperationContext op = System.ServiceModel.OperationContext.Current; //Message msg = op.RequestContext.RequestMessage; //receiver.ReceiverUrl = msg.Headers.To.ToString(); //Simons Instance //receiver.ReceiverUrl = "https://serviceberra.servicebus.windows.net/314700446/821505743/obj/d91500b0-1033-4876-bf0c-fa8a607e8eca/Services/AppEventReceiver.svc"; receiver.ReceiverUrl = "https://serviceberra.servicebus.windows.net/73036694/1885843836/obj/d91500b0-1033-4876-bf0c-fa8a607e8eca/Services/AppEventReceiver.svc"; Global.globalError += "101"; receiver.ReceiverName = RECEIVER_NAME; receiver.Synchronization = EventReceiverSynchronization.Synchronous; //Add the new event receiver to a list in the host web jobsList.EventReceivers.Add(receiver); clientContext.ExecuteQuery(); Global.globalError += "109-"; Global.globalError += (" Added ItemAdded receiver at " + receiver.ReceiverUrl + " - "); } Global.globalY++; FirstTimeInstall(clientContext); } }
static public void CreateAnnouncementsList(ClientContext clientContext) { string listTitle = "Announcements"; // delete list if it exists ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext); using (scope.StartScope()) { using (scope.StartTry()) { clientContext.Web.Lists.GetByTitle(listTitle).DeleteObject(); } using (scope.StartCatch()) { } } // create and initialize ListCreationInformation object ListCreationInformation listInformation = new ListCreationInformation(); listInformation.Title = listTitle; listInformation.Url = "Lists/Announcements"; listInformation.QuickLaunchOption = QuickLaunchOptions.On; listInformation.TemplateType = (int)ListTemplateType.Announcements; // Add ListCreationInformation to lists collection and return list object List list = clientContext.Web.Lists.Add(listInformation); // modify additional list properties and update list.OnQuickLaunch = true; list.EnableAttachments = false; list.Update(); // send command to server to create list clientContext.ExecuteQuery(); clientContext.Load(list); clientContext.ExecuteQuery(); string urlEventReceiver = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + @"/Services/AnnouncementsEventReceiver.svc"; EventReceiverDefinitionCreationInformation erci1 = new EventReceiverDefinitionCreationInformation(); erci1.ReceiverName = "ItemAdding"; erci1.EventType = EventReceiverType.ItemAdding; erci1.ReceiverUrl = urlEventReceiver; erci1.SequenceNumber = 1000; EventReceiverDefinition er1 = list.EventReceivers.Add(erci1); er1.Update(); EventReceiverDefinitionCreationInformation erci2 = new EventReceiverDefinitionCreationInformation(); erci2.ReceiverName = "ItemUpdating"; erci2.EventType = EventReceiverType.ItemUpdating; erci2.ReceiverUrl = urlEventReceiver; erci2.SequenceNumber = 1000; EventReceiverDefinition er2 = list.EventReceivers.Add(erci2); er2.Update(); clientContext.ExecuteQuery(); ListItemCreationInformation lici = new ListItemCreationInformation(); var item1 = list.AddItem(lici); item1["Title"] = "SharePoint introduces new app model"; item1["Body"] = "<div>Developers wonder what happened to solutions.</div>"; item1["Expires"] = DateTime.Today.AddYears(10); item1.Update(); var item2 = list.AddItem(lici); item2["Title"] = "All SharePoint developers must now learn JavaScript"; item2["Body"] = "<div>Some developers are more excited than others.</div>"; item2["Expires"] = DateTime.Today.AddYears(1); item2.Update(); var item3 = list.AddItem(lici); item3["Title"] = "CSOM programming is super fun"; item3["Body"] = "<div>Just ask my mom.</div>"; item3["Expires"] = DateTime.Today.AddDays(7); item3.Update(); clientContext.ExecuteQuery(); }
private void CreateSiteRequestList(ClientContext ctx) { bool rerExists = false; var web = ctx.Web; ctx.Load(ctx.Web.Lists, lists => lists.Include( list => list.Title, list => list.EventReceivers).Where (list => list.Title == Lists.SiteRepositoryTitle)); ctx.ExecuteQuery(); List requestList = ctx.Web.Lists.FirstOrDefault(); if (requestList == null) { var newList = new ListCreationInformation() { Title = Lists.SiteRepositoryTitle, Description = Lists.SiteRepositoryDesc, TemplateType = (int)ListTemplateType.GenericList, Url = Lists.SiteRepositoryUrl }; requestList = ctx.Web.Lists.Add(newList); ctx.Load(requestList); ctx.ExecuteQuery(); // add fields (replace the second field with the display name AddFieldAsXml(requestList, SiteRequestFields.Description, SiteRequestFields.DescriptionDisplayName, SiteRequestFields.DescriptionId, "Note", options: AddFieldOptions.AddFieldCheckDisplayName); AddFieldAsXml(requestList, SiteRequestFields.Template, SiteRequestFields.TemplateDisplayName, SiteRequestFields.TemplateId); AddFieldAsXml(requestList, SiteRequestFields.Policy, SiteRequestFields.PolicyDisplayName, SiteRequestFields.PolicyId); AddFieldAsXml(requestList, SiteRequestFields.Url, SiteRequestFields.UrlDisplayName, SiteRequestFields.UrlId); AddFieldAsXml(requestList, SiteRequestFields.Owner, SiteRequestFields.OwnerDisplayName, SiteRequestFields.OwnerId, "User", "List='UserInfo' UserSelectionMode='0' ShowField='ImnName'"); AddFieldAsXml(requestList, SiteRequestFields.AdditionalOwners, SiteRequestFields.AdditionalOwnersDisplayName, SiteRequestFields.AdditionalOwnersId, "UserMulti", "Mult='TRUE' List='UserInfo' UserSelectionMode='1' ShowField='ImnName'"); AddFieldAsXml(requestList, SiteRequestFields.Lcid, SiteRequestFields.LcidDisplayName, SiteRequestFields.LcidId); AddFieldAsXml(requestList, SiteRequestFields.StatusMessage, SiteRequestFields.StatusMessageDisplayName, SiteRequestFields.StatusMessageId, "Note", options: AddFieldOptions.AddFieldCheckDisplayName); AddFieldAsXml(requestList, SiteRequestFields.TimeZone, SiteRequestFields.TimeZoneDisplayName, SiteRequestFields.TimeZoneId); AddFieldAsXml(requestList, SiteRequestFields.State, SiteRequestFields.StateDisplayName, SiteRequestFields.StatusId); requestList.Update(); ctx.ExecuteQuery(); } else { foreach (var rer in requestList.EventReceivers) { if (rer.ReceiverName == RECEIVER_NAME) { rerExists = true; System.Diagnostics.Trace.WriteLine("Found existing ItemAdded receiver at " + rer.ReceiverUrl); } } } if (!rerExists) { EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation(); receiver.EventType = EventReceiverType.ItemUpdated; //Get WCF URL where this message was handled OperationContext op = OperationContext.Current; Message msg = op.RequestContext.RequestMessage; receiver.ReceiverUrl = msg.Headers.To.ToString(); receiver.ReceiverName = RECEIVER_NAME; //Add the new event receiver to a list in the host web requestList.EventReceivers.Add(receiver); ctx.ExecuteQuery(); } }