Creating SharePoint Calendar All Day or Daily Recurring Event


This post is a contribution from Manish Joshi, an engineer with the SharePoint Developer Support team

Whether you are creating a daily recurring event using SharePoint web service lists.asmx or via REST calls, you will need to make sure that TimeZone property is set to 0 otherwise the SharePoint calendar recurring event will be created but on random instances of the events items you will get following error message:

“Item does not exist. It may have been deleted by another user”

Sample codes below:

Sample code using Lists.asmx web service

Below is the sample XML passed to SharePoint lists.asmx.

var sDoc = "<Batch OnError=\"Continue\">" +
            "               <Method ID=\"1\" Cmd=\"New\">" +
            "                  <Field Name=\"Category\"><![CDATA[Meeting]]></Field>" +
            "                  <Field Name=\"EndDate\"><![CDATA[2017-07-27T239:59:00Z]]></Field>" +
            "                  <Field Name=\"EventDate\"><![CDATA[2017-07-13T09:00:00Z]]></Field>" +
            "                  <Field Name=\"EventType\"><![CDATA[1]]></Field>" +
            "                  <Field Name=\"fAllDayEvent\"><![CDATA[1]]></Field>" +
            "                  <Field Name=\"fRecurrence\"><![CDATA[1]]></Field>" +
            "                  <Field Name=\"Location\"><![CDATA[Redmomd]]></Field>" +
            "                  <Field Name=\"RecurrenceData\"><![CDATA[<recurrence><rule><firstDayOfWeek>su</firstDayOfWeek><repeat><daily weekday='TRUE' /></repeat><windowEnd>2017-07-27T23:59:00Z</windowEnd></rule></recurrence>]]></Field>" +
            "                  <Field Name=\"Description\"><![CDATA[Daily Recurrence.]]></Field>" +
            "                  <Field Name=\"Title\"><![CDATA[Daily 6]]></Field>" +
            "                  <Field Name=\"UID\"><![CDATA[{" + Guid.NewGuid() + "}]]></Field>" +
            "                  <Field Name=\"TimeZone\"><![CDATA[0]]></Field>" +
            "               </Method>" +
            "            </Batch>";

 

Below is the complete sample code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace CreateRecurringEvent
{
    class Program
    {
        private static int GetWorkdays(DateTime start, DateTime end)
        {
            int days = 0;

            while (start <= end)
            {
                var day = start.DayOfWeek;
                if (!(day == DayOfWeek.Saturday || day == DayOfWeek.Sunday))
                {
                    days++;
                }

                start = start.AddDays(1);
            }

            return days;
        }

        static void Main(string[] args)
        {

            ListsService.Lists lists = new ListsService.Lists();
            lists.UseDefaultCredentials = true;
            lists.Url = "http://sp/_vti_bin/lists.asmx";


            var start = DateTime.Parse("2017-11-13");
            var end = DateTime.Parse("2017-12-27");
            string title = "Test Recurrence";


            var recurrenceDataXml = new XElement("recurrence",
                                    new XElement("rule",
                                        new XElement("firstDayOfWeek", "su"),
                                        new XElement("repeat",
                                            new XElement("weekly",
                                                new XAttribute("mo", "TRUE"),
                                                new XAttribute("tu", "TRUE"),
                                                new XAttribute("we", "TRUE"),
                                                new XAttribute("th", "TRUE"),
                                                new XAttribute("fr", "TRUE"),
                                                new XAttribute("weekFrequency", "1"))),
                                        new XElement("repeatInstances", GetWorkdays(start, end))));

            var recurrenceDataString = recurrenceDataXml.ToString();

            var newEventXml = new XDocument(
               new XElement("Batch",
                new XAttribute("OnError", "Continue"),
                new XAttribute("ListVersion", "1"),
                new XAttribute("ViewName", ""),
                new XElement("Method",
                  new XAttribute("ID", "1"),
                  new XAttribute("Cmd", "New"),
                  new XElement("Field", new XAttribute("Name", "Title"), title),
                  new XElement("Field", new XAttribute("Name", "EventDate"), String.Format("{0:yyyy'-'MM'-'dd 00':'00':'00}", start)),
                  new XElement("Field", new XAttribute("Name", "EndDate"), String.Format("{0:yyyy'-'MM'-'dd 23':'59':'00}", end)),
                  new XElement("Field", new XAttribute("Name", "fAllDayEvent"), "1"),
                  new XElement("Field", new XAttribute("Name", "fRecurrence"), "1"),
                  new XElement("Field", new XAttribute("Name", "Duration"), 86340),
                  new XElement("Field", new XAttribute("Name", "EventType"), "1"),
                  new XElement("Field", new XAttribute("Name", "UID"), "{" + Guid.NewGuid() + "}"),
                  new XElement("Field", new XAttribute("Name", "TimeZone"), "0"),
                  new XElement("Field", new XAttribute("Name", "RecurrenceData"),
                    new XCData(recurrenceDataString)))));

            var doc = new XmlDocument();
            using (var reader = newEventXml.CreateReader())
                doc.Load(reader);

            System.Xml.XmlNode result = lists.UpdateListItems("Calendar", doc);

            XmlTextReader xr = new XmlTextReader(result.OuterXml, XmlNodeType.Element, null);
            while (xr.Read())
            {
                if (xr.ReadToFollowing("z:row"))
                {
                    if (xr["ows_ID"] != null)
                    {
                        Console.WriteLine(xr["ows_ID"].ToString());
                    }
                }
            }

            Console.WriteLine("Done...!");
            Console.ReadLine();

        }

    }
}

 

Sample REST call in Script Editor Web Part:
Below code demonstrates creation of the recurring event using REST API

<div><button type="button" onclick="CreateDailyRecurringEvent()">Create Daily Recurring Event</button></div>
<br><br>
<div id="Status"></div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<script type="text/javascript">
	function createGuid()  
	{  
	   return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {  
		  var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);  
		  return v.toString(16);  
	   });  
	}  
	var guid = createGuid();
	function CreateDailyRecurringEvent() 
	{
		//create a string that has the events
		var stringStartDate = "2017-07-13T08:00:00Z";
		var stringEndDate = "2017-07-27T23:59:00Z";
		var reccurenceString = "<recurrence><rule><firstDayOfWeek>su</firstDayOfWeek><repeat><daily weekday='TRUE' /></repeat><windowEnd>2017-07-27T23:59:00Z</windowEnd></rule></recurrence>";
		var recReq =
        		{
			url: "http://sp/_api/web/lists/GetByTitle('Events')/items",
			type: "POST",
			data: JSON.stringify({
				'__metadata': {
					'type': 'SP.ListItem'
				},
				'Title': 'Daily 5',
				'EventDate': stringStartDate,
				'EndDate': stringEndDate,
				'Location': 'Seattle',
				'Description': 'Daily 5',
				'Category': 'Meeting',
				'fRecurrence': true,
				'fAllDayEvent': true,
				'RecurrenceData': reccurenceString,
				'TimeZone': 0,
				'UID': guid,
				'EventType': 1
			}),
			headers: {
				"accept": "application/json;odata=verbose",
				"content-type": "application/json;odata=verbose",
				"X-RequestDigest": $("#__REQUESTDIGEST").val()
			},
			success :function () {
				alert("Event data saved.");				
			},
			error:function (err) {
				alert("Error occurred while saving question data.");
				console.log("ERROR", err);
			}
		};

		jQuery.ajax(recReq);
	}
</script>
Comments (1)

Skip to main content