Friday, April 5, 2013

SharePoint 2013- Creating App Event handlers

In my last post i have explained how to create remote event receiver. In this post i am talking about how to create app event receivers in share point 2013.

As shown in my last post i have created remote event handler. After adding a remote event receiver to my app, anew web app project got create, Web app project contains web service code files related to remote handlers.

To enable to app events for your app, select the app project, check the properties for app project as shown below images. you can see three handlers in the properties related to apps, Handle App Installed, Handle App Uninstalling, Handle App Upgraded. Make the property to True that you need to fire.





Here Iam selecting Handle App Installed event. After changing the value from False to true you can see the new Service file "AppEventReceiver.svc" in Appweb project as shown below image.



In AppManifest.xml file <Properties> tag, new property  <InstalledEventEndpoint> will be updated with the AppeventReceiver service file as shown the below image.




Write the code as per your requirement. Here iam just creating a text file and writing the text in the file when app got installed in my share point site. Code will be


      public SPRemoteEventResult ProcessEvent(RemoteEventProperties properties)
      {
            LogAppEvent(properties);
            return new SPRemoteEventResult();
      }   
    
      private void LogAppEvent(RemoteEventProperties properties)
      {
            try
            {
                FileStream fileStream = new FileStream("D:\\AppFile.txt", FileMode.OpenOrCreate,FileAccess.Write);
                StreamWriter writer = new StreamWriter(fileStream);
                if (properties.EventType == RemoteEventType.AppInstalled)
                {                    
                    writer.Write("App Installed");
                    writer.Close();
                }
            }
            catch (Exception ex)
            {   
            }
      }

Here AppEventReceiver class will inherit from IRemoteEventService as shown in the image below. By default there will be two methods ProcessEvent() and ProcessOneWayEvent() as same as Remote event handler. Code file will be 




write the code in ProcessEvent() method. Here code will fire for AppInstalled event. In case if you write the code for AppUnninstalling event, and in the properties value 'false', event will not be fired. If you need to disable the event, just make the property value from True to False.

Provide your comments and suggestion on this post.

Share this