Friday, November 8, 2013

Use event receivers to handle events in apps for SharePoint 2013, Create an event receiver for an app for SharePoint 2013


vs2012 -> file -> new -> project c# -> office/SharePoint -> apps -> apps for SharePoint 2013 -> "BasicDataOperations"

Solution 'BasicDataOperations' -> BasicDataOperations -> Right Click -> Add -> New Item.. -> select List Template and name it as 'List1'

Solution 'BasicDataOperations' -> BasicDataOperations -> Right Click -> Add -> New Item.. -> select 'Remote Event Receiver' Template and name it as 'RemoteEventReceiver1'

Solution 'BasicDataOperations' -> BasicDataOperations -> Press F4(Function key to open Properties of BasicDataOperations)
Go to 'Handle App Installed' boolean property value as 'True' 
After done this we can observe visual studio can add new service namely 'AppEventReceiver.svc' added in this path "Solution 'BasicDataOperations' -> BasicDataOperationsWeb -> Services -> 'AppEventReceiver.svc' "

Solution 'BasicDataOperations' -> BasicDataOperationsWeb -> Services -> AppEventReceiver.svc -> AppEventReceiver.svc.cs
Add below custom code to this 'AppEventReceiver.svc.cs' file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;

namespace BasicDataOperationsWeb.Services
{
    public class AppEventReceiver : IRemoteEventService
    {
        public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties)
        {
            LogAppEvents(properties.EventType.ToString());
            return new SPRemoteEventResult();
        }

        public void ProcessOneWayEvent(SPRemoteEventProperties properties)
        {
            // This method is not used by app events.
        }

        public static void LogAppEvents(string eventType)
        {
            try
            {
                string folder = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "SPAppEventLog");
                if (!System.IO.Directory.Exists(folder))
                    System.IO.Directory.CreateDirectory(folder);
                string path = string.Format("{0}\\{1}{2}.log", folder, eventType, DateTime.Now.ToString("yyyyMMddhhmmssfff"));
                using (System.IO.FileStream fs = System.IO.File.Create(path))
                {
                    fs.Flush();
                    fs.Close();
                }
            }
            catch (Exception)
            {
            }
            return;
        }
    }
}

Solution 'BasicDataOperations' -> BasicDataOperationsWeb -> Services -> RemoteEventReceiver1.svc -> RemoteEventReceiver1.svc.cs
Add below custom code to this 'RemoteEventReceiver1.svc.cs' file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;

namespace BasicDataOperationsWeb.Services
{
    public class RemoteEventReceiver1 : IRemoteEventService
    {
        public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties)
        {
            ListRemoteEventReceiver(properties);
            return new SPRemoteEventResult();
        }

        public void ProcessOneWayEvent(SPRemoteEventProperties properties)
        {
        }

        public static void ListRemoteEventReceiver(SPRemoteEventProperties properties)
        {
            string logListTitle = "EventLog";
            if (string.Equals(properties.ItemEventProperties.ListTitle, logListTitle, StringComparison.OrdinalIgnoreCase))
                return;
            HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)OperationContext.Current.IncomingMessageProperties[HttpRequestMessageProperty.Name];
            string contextTokenString = requestProperty.Headers["X-SP-ContextToken"];
            if (contextTokenString != null)
            {
                SharePointContextToken contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, requestProperty.Headers[HttpRequestHeader.Host]);
                Uri sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
                string accessToken = TokenHelper.GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
                bool exists = false;
                using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken))
                {
                    clientContext.Load(clientContext.Web);
                    clientContext.ExecuteQuery();
                    List logList = clientContext.Web.Lists.GetByTitle(logListTitle);
                    try
                    {
                        clientContext.Load(logList);
                        clientContext.ExecuteQuery();
                        exists = true;
                    }
                    catch (Microsoft.SharePoint.Client.ServerUnauthorizedAccessException)
                    {
                        return;
                    }
                    catch (Microsoft.SharePoint.Client.ServerException)
                    {
                        exists = false;
                    }
                    if (!exists)
                    {
                        ListCreationInformation listInfo = new ListCreationInformation();
                        listInfo.Title = logListTitle;
                        listInfo.TemplateType = 100;
                        clientContext.Web.Lists.Add(listInfo);
                        clientContext.Web.Context.ExecuteQuery();
                    }
                    string itemTitle = "Event: " + properties.EventType.ToString() + " occurred on: " + DateTime.Now.ToString(" yyyy/MM/dd/HH:mm:ss:fffffff");
                    ListCollection lists = clientContext.Web.Lists;
                    List selectedList = lists.GetByTitle(logListTitle);
                    clientContext.Load<ListCollection>(lists);
                    clientContext.Load<List>(selectedList);
                    ListItemCreationInformation listItemCreationInfo = new ListItemCreationInformation();
                    var listItem = selectedList.AddItem(listItemCreationInfo);
                    listItem["Title"] = itemTitle;
                    listItem.Update();
                    clientContext.ExecuteQuery();
                }
            }
        }
    }

}

Solution 'BasicDataOperations' -> BasicDataOperations -> Pages -> Default.aspx
Add below custom code to 'Default.aspx' file
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="BasicDataOperationsWeb.Pages.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <center>
                <h2>Site Lists</h2>
            </center>
            <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
            <asp:UpdatePanel ID="ListManagementPanel" runat="server" UpdateMode="Conditional">
                <ContentTemplate>
                    <center>
                        <asp:Button runat="server" ID="RefreshListButton" Text="Refresh Lists" OnClick="RefreshList_Click" />
                        <asp:Button runat="server" ID="AddListButton" Text="Add List" OnClick="AddList_Click" />
                        <asp:TextBox ID="AddListNameBox" runat="server" /></center>
                    <center>
                        <asp:Button runat="server" ID="RetrieveListButton" Text="Retrieve List Items" OnClick="RetrieveListButton_Click" /><asp:TextBox ID="RetrieveListNameBox" runat="server" />
                        <asp:Button runat="server" ID="AddItemButton" Text="Add Item" OnClick="AddItemButton_Click" />
                        <asp:TextBox ID="AddListItemBox" runat="server" /></center>
                    <center>
                        <asp:Button runat="server" ID="DeleteListButton" Text="Delete This List" OnClick="DeleteListButton_Click" Visible="false" />
                        <asp:Button runat="server" ID="ChangeListTitleButton" Text="Change List Title" OnClick="ChangeListTitleButton_Click" Visible="false" />
                        <asp:TextBox ID="ChangeListTitleBox" runat="server" Visible="false" />
                    </center>
                    <asp:Table ID="ListTable" GridLines="Both" HorizontalAlign="Center" CellPadding="18" CellSpacing="0" runat="server">
                        <asp:TableHeaderRow>
                            <asp:TableHeaderCell>List Title</asp:TableHeaderCell>
                            <asp:TableHeaderCell></asp:TableHeaderCell>
                        </asp:TableHeaderRow>
                    </asp:Table>
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
    </form>
</body>

</html>

Solution 'BasicDataOperations' -> BasicDataOperations -> Pages -> Default.aspx -> Default.aspx.cs
Add below custom code to 'Default.aspx.cs' file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Client;

namespace BasicDataOperationsWeb.Pages
{
    public partial class Default : System.Web.UI.Page
    {
        SharePointContextToken contextToken;
        string accessToken;
        Uri sharepointUrl;

        protected void Page_Load(object sender, EventArgs e)
        {
            TokenHelper.TrustAllCertificates();
            string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);

            if (contextTokenString != null)
            {
                contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);
                sharepointUrl = new Uri(Request.QueryString["SPAppWebUrl"]);
                accessToken = TokenHelper.GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
                AddListButton.CommandArgument = accessToken;
                RefreshListButton.CommandArgument = accessToken;
                RetrieveListButton.CommandArgument = accessToken;
                AddItemButton.CommandArgument = accessToken;
                DeleteListButton.CommandArgument = accessToken;
                ChangeListTitleButton.CommandArgument = accessToken;
                RetrieveLists(accessToken);
            }
            else if (!IsPostBack)
            {
                Response.Write("Could not find a context token.");
            }
        }

        private void RetrieveLists(string accessToken)
        {
            if (IsPostBack)
            {
                sharepointUrl = new Uri(Request.QueryString["SPAppWebUrl"]);
            }
            AddItemButton.Visible = false;
            AddListItemBox.Visible = false;
            RetrieveListNameBox.Enabled = true;
            DeleteListButton.Visible = false;
            ChangeListTitleButton.Visible = false;
            ChangeListTitleBox.Visible = false;
            ListTable.Rows[0].Cells[1].Text = "List ID";

            ClientContext clientContext =
            TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
            Web web = clientContext.Web;
            ListCollection lists = web.Lists;
            clientContext.Load<ListCollection>(lists);
            clientContext.ExecuteQuery();
            foreach (List list in lists)
            {
                TableRow tableRow = new TableRow();
                TableCell tableCell1 = new TableCell();
                tableCell1.Controls.Add(new LiteralControl(list.Title));
                LiteralControl idClick = new LiteralControl();
                string clickScript = "<a onclick=\"document.getElementById(\'RetrieveListNameBox\').value = '" + list.Id.ToString() + "';\" href=\"#\">" + list.Id.ToString() + "</a>";
                idClick.Text = clickScript;
                TableCell tableCell2 = new TableCell();
                tableCell2.Controls.Add(idClick);
                tableRow.Cells.Add(tableCell1);
                tableRow.Cells.Add(tableCell2);
                ListTable.Rows.Add(tableRow);
            }
        }

        private void RetrieveListItems(string accessToken, Guid listId)
        {
            if (IsPostBack)
            {
                sharepointUrl = new Uri(Request.QueryString["SPAppWebUrl"]);
            }

            AddItemButton.Visible = true;
            AddListItemBox.Visible = true;
            RetrieveListNameBox.Enabled = false;
            DeleteListButton.Visible = true;
            ChangeListTitleButton.Visible = true;
            ChangeListTitleBox.Visible = true;
            ListTable.Rows[0].Cells[1].Text = "List Items";

            ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
            Web web = clientContext.Web;
            ListCollection lists = web.Lists;
            List selectedList = lists.GetById(listId);

            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = "<View><RowLimit>100</RowLimit></View>";

            Microsoft.SharePoint.Client.ListItemCollection listItems = selectedList.GetItems(camlQuery);
            clientContext.Load<ListCollection>(lists);
            clientContext.Load<List>(selectedList);
            clientContext.Load<Microsoft.SharePoint.Client.ListItemCollection>(listItems);
            clientContext.ExecuteQuery();

            TableRow tableRow = new TableRow();
            TableCell tableCell1 = new TableCell();
            tableCell1.Controls.Add(new LiteralControl(selectedList.Title));
            TableCell tableCell2 = new TableCell();

            foreach (Microsoft.SharePoint.Client.ListItem item in listItems)
            {
                tableCell2.Text += item.FieldValues["Title"] + "<br>";
            }

            tableRow.Cells.Add(tableCell1);
            tableRow.Cells.Add(tableCell2);
            ListTable.Rows.Add(tableRow);
        }

        private void AddList(string accessToken, string newListName)
        {
            if (IsPostBack)
            {
                sharepointUrl = new Uri(Request.QueryString["SPAppWebUrl"]);
            }

            ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
            Web web = clientContext.Web;
            ListCollection lists = web.Lists;
            ListCreationInformation listCreationInfo = new ListCreationInformation();
            listCreationInfo.Title = newListName;
            listCreationInfo.TemplateType = (int)ListTemplateType.GenericList;
            lists.Add(listCreationInfo);
            clientContext.Load<ListCollection>(lists);
            try
            {
                clientContext.ExecuteQuery();
            }
            catch (Exception e)
            {
                AddListNameBox.Text = e.Message;
            }
            RetrieveLists(accessToken);
        }

        private void AddListItem(string accessToken, Guid listId, string newItemName)
        {
            if (IsPostBack)
            {
                sharepointUrl = new Uri(Request.QueryString["SPAppWebUrl"]);
            }

            ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
            Web web = clientContext.Web;
            ListCollection lists = web.Lists;
            List selectedList = lists.GetById(listId);
            clientContext.Load<ListCollection>(lists);
            clientContext.Load<List>(selectedList);
            ListItemCreationInformation listItemCreationInfo = new ListItemCreationInformation();
            var listItem = selectedList.AddItem(listItemCreationInfo);
            listItem["Title"] = newItemName;
            listItem.Update();
            clientContext.ExecuteQuery();
            RetrieveListItems(accessToken, listId);
        }

        private void ChangeListTitle(string accessToken, Guid listId, string newListTitle)
        {
            if (IsPostBack)
            {
                sharepointUrl = new Uri(Request.QueryString["SPAppWebUrl"]);
            }

            ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
            Web web = clientContext.Web;
            ListCollection lists = web.Lists;
            List selectedList = lists.GetById(listId);
            clientContext.Load<ListCollection>(lists);
            clientContext.Load<List>(selectedList);
            selectedList.Title = newListTitle;
            selectedList.Update();
            clientContext.ExecuteQuery();
            RetrieveListItems(accessToken, listId);
        }

        private void DeleteList(string accessToken, Guid listId)
        {
            if (IsPostBack)
            {
                sharepointUrl = new Uri(Request.QueryString["SPAppWebUrl"]);
            }

            ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
            Web web = clientContext.Web;
            ListCollection lists = web.Lists;
            List selectedList = lists.GetById(listId);
            clientContext.Load<ListCollection>(lists);
            clientContext.Load<List>(selectedList);
            selectedList.DeleteObject();
            clientContext.ExecuteQuery();
            RetrieveListNameBox.Text = "";
            RetrieveLists(accessToken);
        }

        protected void AddList_Click(object sender, EventArgs e)
        {

            string commandAccessToken = ((Button)sender).CommandArgument;
            if (AddListNameBox.Text != "")
            {
                AddList(commandAccessToken, AddListNameBox.Text);
            }
            else
            {
                AddListNameBox.Text = "Enter a list title";
            }
            AddListNameBox.Text = "";
        }

        protected void RefreshList_Click(object sender, EventArgs e)
        {

            string commandAccessToken = ((Button)sender).CommandArgument;
            RetrieveLists(commandAccessToken);
        }

        protected void RetrieveListButton_Click(object sender, EventArgs e)
        {
            string commandAccessToken = ((Button)sender).CommandArgument;

            Guid listId = new Guid();
            if (Guid.TryParse(RetrieveListNameBox.Text, out listId))
            {
                RetrieveListItems(commandAccessToken, listId);
            }
            else
            {
                RetrieveListNameBox.Text = "Enter a List GUID";
            }
        }

        protected void AddItemButton_Click(object sender, EventArgs e)
        {
            string commandAccessToken = ((Button)sender).CommandArgument;
            Guid listId = new Guid(RetrieveListNameBox.Text);
            if (AddListItemBox.Text != "")
            {
                AddListItem(commandAccessToken, listId, AddListItemBox.Text);
            }
            else
            {
                AddListItemBox.Text = "Enter an item title";
            }
            AddListItemBox.Text = "";
        }

        protected void DeleteListButton_Click(object sender, EventArgs e)
        {
            string commandAccessToken = ((Button)sender).CommandArgument;
            Guid listId = new Guid(RetrieveListNameBox.Text);
            DeleteList(commandAccessToken, listId);
        }

        protected void ChangeListTitleButton_Click(object sender, EventArgs e)
        {
            string commandAccessToken = ((Button)sender).CommandArgument;
            Guid listId = new Guid(RetrieveListNameBox.Text);
            if (ChangeListTitleBox.Text != null)
            {
                ChangeListTitle(commandAccessToken, listId, ChangeListTitleBox.Text);
            }
            else
            {
                ChangeListTitleBox.Text = "Enter a new list title";
            }
            ChangeListTitleBox.Text = "";
        }
    }
}

Solution 'BasicDataOperations' -> Right Click -> Deploy

Thank You.

No comments:

Post a Comment