This is a migrated thread and some comments may be shown as answers.

Impletementing a provider issue

7 Answers 248 Views
Scheduler
This is a migrated thread and some comments may be shown as answers.
mulligann
Top achievements
Rank 1
mulligann asked on 21 Mar 2009, 06:15 PM
I am trying to use the scheduler to add events on the admin side and then show a read only version of the same scheduler on the public site.  I am trying to setup the scheduler on the admin side first.  I went and looked at the demo site, then went to the documention / help area and read about using a data provider and then Implementing a provider.  I put the code into the web.config, but not sure if I put the following code in the right spot of the web.config.
<telerik.web.ui>
  
<radScheduler defaultAppointmentProvider="Integrated">
      
<appointmentProviders>
          
<add name="XmlSchedulerProvider1"
               
type="Telerik.Web.UI.XmlSchedulerProvider"
               
fileName="~/App_Data/Appointments.xml"
               
persistChanges="true"/>
      
</appointmentProviders>
  
</radScheduler>
</
telerik.web.ui>

Is there a specific section to put the code in.  It doesn't really say in the help section.  also I copied the code from "Implementing a DataProvider" section as well.  I am getting an error in Public Overloads Overrides Sub Initialize sub "config = Nothing".  Error says Operator '=' is not defined for types System.Collections.Specialized.NameValueCollection.   I get another error in the Private Sub EnsureFilePath sub owner.Page = Nothing Operator '=' is not defined for types System.Web.UI.Page.  The last error is in Public Overloads Overrides Function GetAppointments LoadAppointmentResources in not declared.

Not sure where to go from here.  I don't know enough about these errors to try and troubleshoot.  I have copied the code exactly from the VB sections.

I changed 
Public Class MyXmlSchedulerProvider
  Inherits SchedulerProviderBase
 End Class
to XmlScheduleProvider1 as that is what is in the web.config file.

Any help?

7 Answers, 1 is accepted

Sort by
0
Accepted
Peter
Telerik team
answered on 24 Mar 2009, 12:20 PM

Hi mulligann,

I have prepared a demo with XmlSchedulerProvider and MyDbSchedulerProvider. Please, find it attached and use it for reference.


Kind regards,
Peter
the Telerik team

Check out Telerik Trainer , the state of the art learning tool for Telerik products.
0
mulligann
Top achievements
Rank 1
answered on 24 Mar 2009, 06:47 PM
Thanks for the reply.  I'll check out the demo today.
0
mulligann
Top achievements
Rank 1
answered on 25 Mar 2009, 10:38 PM
Thanks for the demo.  It was alot easier to configure and get working.  I was able to use your xml example and got the scheduler up and running in minutes.  Then attached the tooltip manager to the read only version of the scheduler on the public site and it works great.  Thank you.
0
peter brandt
Top achievements
Rank 1
answered on 07 Oct 2009, 07:20 AM


but the errors still exists
http://www.telerik.com/help/aspnet-ajax/schedule_databindingimplementingaprovider.html
Point 7
[C#] GetAppointments
...
         break;
       
case "Resources":
         LoadAppointmentResources(owner, appointment, appointmentData);
         
break;
       
case "Attribute":
...

LoadAppointmentResources does not exists.
Your schedulerprovider.zip doesnt handle MyXMLSchedulerProvider.cs --> only MyDbSchedulerProvider.cs
I was looking for syntax errors, but could find no function with 3 parameters, which fits LoadAppointmentsResource(owner, appointment, appointmentData).
Can you post this function please?

Thanks for your efforts
Peter

0
Peter
Telerik team
answered on 12 Oct 2009, 09:22 AM
Hello peter,

I am not sure how to replicate this problem locally. Do you have a simple demo which you can send via a support ticket so we can test it?


Best wishes,
Peter
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Watch a video on how to optimize your support resource searches and check out more tips on the blogs.
0
Shaan
Top achievements
Rank 1
answered on 28 Oct 2010, 10:47 AM
Hi Peter,

I am using the sample Application with XML as DataSource and followed the example at the link :-
http://www.telerik.com/help/aspnet-ajax/schedule_databindingimplementingaprovider.html

There is MethodName GetAppointments(RadScheduler owner) which has a method in a "Resources" Case known as
LoadAppointmentResources(owner, appointment, appointmentData).

The defintion for LoadAppointmentResources method is not provided anywhere in the example.

Can you please provide it,

peter brandt  also Posted the same issue on on Oct 7, 2009

Thanks
Shaan
0
Peter
Telerik team
answered on 02 Nov 2010, 04:23 PM
Hi Shaan,

XmlSchedulerProvider is part of the Telerik.Web.UI assembly. Here is the source code for your perusal:

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration.Provider;
using System.IO;
using System.Runtime.CompilerServices;
using System.Web;
using System.Web.UI;
using System.Xml;
using System.Globalization;
  
namespace Telerik.Web.UI
{
    /// <summary>
    /// A RadScheduler provider that uses XML document as a data store.
    /// </summary>
    public class XmlSchedulerProvider : SchedulerProviderBase
    {
        /// <summary>
        /// Format string for the dates. The "Z" appendix signifies UTC time.
        /// </summary>
        private const string DateFormatString = "yyyy-MM-ddTHH:mmZ";
  
        private readonly XmlDocument _doc;
        private string _dataFileName;
        private int _nextID;
        private List<Resource> _resources;
        private bool _documentLoaded;
  
        private bool _persistChanges;
  
        /// <summary>
        /// Initializes a new instance of the <see cref="XmlSchedulerProvider"/> class.
        /// </summary>
        /// <param name="dataFileName">Name of the data file.</param>
        /// <param name="persistChanges">if set to <c>true</c> the changes will be persisted.</param>
        public XmlSchedulerProvider(string dataFileName, bool persistChanges)
        {
            _dataFileName = dataFileName;
            _doc = new XmlDocument();
            _doc.Load(_dataFileName);
            _documentLoaded = true;
  
            _nextID = ReadNextID();
            LoadResources();
  
            _persistChanges = persistChanges;
        }
  
        /// <summary>
        /// Initializes a new instance of the <see cref="XmlSchedulerProvider"/> class.
        /// </summary>
        /// <param name="doc">The document instance to use as a data store.</param>
        public XmlSchedulerProvider(XmlDocument doc)
        {
            _doc = doc;
  
            _nextID = ReadNextID();
            LoadResources();
  
            _persistChanges = false;
        }
  
        /// <summary>
        /// Initializes a new instance of the <see cref="XmlSchedulerProvider"/> class.
        /// </summary>
        public XmlSchedulerProvider()
        {
            _doc = new XmlDocument();
            _nextID = 1;
  
            _resources = new List<Resource>();
            _doc.AppendChild(_doc.CreateNode(XmlNodeType.Element, "Appointments", ""));
  
            _persistChanges = false;
        }
  
  
        /// <summary>
        /// Initializes the provider.
        /// </summary>
        /// <param name="name">The friendly name of the provider.</param>
        /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>
        /// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception>
        /// <exception cref="T:System.InvalidOperationException">An attempt is made to call <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"></see> on a provider after the provider has already been initialized.</exception>
        /// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception>
        public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }
  
            if (string.IsNullOrEmpty(name))
            {
                name = "XmlSchedulerProvider";
            }
  
            base.Initialize(name, config);
  
            _dataFileName = config["fileName"];
            if (string.IsNullOrEmpty(_dataFileName))
            {
                throw new ProviderException("Missing XML data file name. Please specify it with the fileName property.");
            }
  
            string persistChanges = config["persistChanges"];
            if (!string.IsNullOrEmpty(persistChanges))
            {
                if (!bool.TryParse(persistChanges, out _persistChanges))
                {
                    throw new ProviderException("Invalid value for PersistChanges attribute. Use 'True' or 'False'.");
                }
            }
            else
            {
                _persistChanges = true;
            }
        }
  
        /// <summary>
        /// Fetches appointments.
        /// </summary>
        /// <param name="owner">The owner RadScheduler instance.</param>
        /// <returns></returns>
        public override IEnumerable<Appointment> GetAppointments(RadScheduler owner)
        {
            EnsureFilePath(owner);
            LoadDataFile();
  
            List<Appointment> appointmentsList = new List<Appointment>();
            foreach (XmlNode appointmentNode in _doc.SelectNodes("//Appointments/Appointment"))
            {
                Appointment appointment = owner.CreateAppointment();
                appointmentsList.Add(appointment);
  
                foreach (XmlNode appointmentData in appointmentNode.ChildNodes)
                {
                    if (owner.EnableDescriptionField && appointmentData.Name == "Description")
                    {
                        appointment.Description = appointmentData.InnerText;
                        continue;
                    }
  
                    switch (appointmentData.Name)
                    {
                        case "ID":
                            appointment.ID = int.Parse(appointmentData.InnerText);
                            break;
  
                        case "Subject":
                            appointment.Subject = appointmentData.InnerText;
                            break;
  
                        case "Start":
                            appointment.Start = DateTime.Parse(appointmentData.InnerText).ToUniversalTime();
                            break;
  
                        case "End":
                            appointment.End = DateTime.Parse(appointmentData.InnerText).ToUniversalTime();
                            break;
  
                        case "RecurrenceRule":
                            appointment.RecurrenceRule = appointmentData.InnerText;
                            appointment.RecurrenceState = RecurrenceState.Master;
                            break;
  
                        case "RecurrenceParentID":
                            appointment.RecurrenceParentID = int.Parse(appointmentData.InnerText);
                            appointment.RecurrenceState = RecurrenceState.Exception;
                            break;
  
                        case "Reminder":
                            var parsedReminders = Reminder.TryParse(appointmentData.InnerText);
                            if (parsedReminders != null)
                            {
                                appointment.Reminders.AddRange(parsedReminders);
                            }
                            break;
  
                        case "Resources":
                            LoadAppointmentResources(owner, appointment, appointmentData);
                            break;
  
                        case "Attribute":
                            appointment.Attributes.Add(appointmentData.Attributes["Key"].Value, appointmentData.Attributes["Value"].Value);
                            break;
                    }
                }
            }
  
            return appointmentsList;
        }
  
        /// <summary>
        /// Inserts the specified appointment.
        /// </summary>
        /// <param name="owner">The owner RadScheduler instance.</param>
        /// <param name="appointmentToInsert">The appointment to insert.</param>
        public override void Insert(RadScheduler owner, Appointment appointmentToInsert)
        {
            EnsureFilePath(owner);
            LoadDataFile();
  
            appointmentToInsert.ID = _nextID;
  
            XmlNode appointmentsNode = _doc.SelectSingleNode("//Appointments");
            appointmentsNode.AppendChild(CreateAppointmentNode(owner, appointmentToInsert));
  
            _nextID++;
            XmlNode nextIDNode = _doc.SelectSingleNode("//Appointments/NextID");
            if (nextIDNode == null)
            {
                nextIDNode = _doc.CreateElement("NextID");
                appointmentsNode.AppendChild(nextIDNode);
            }
            nextIDNode.InnerText = _nextID.ToString();
  
            SaveDataFile();
        }
  
        /// <summary>
        /// Updates the specified appointment.
        /// </summary>
        /// <param name="owner">The owner RadScheduler instance.</param>
        /// <param name="appointmentToUpdate">The appointment to update.</param>
        public override void Update(RadScheduler owner, Appointment appointmentToUpdate)
        {
            EnsureFilePath(owner);
            LoadDataFile();
  
            if (appointmentToUpdate.ID == null)
            {
                Insert(owner, appointmentToUpdate);
            }
  
            XmlNode appointmentNode = _doc.SelectSingleNode("//Appointments/Appointment[ID=" + appointmentToUpdate.ID + "]");
            appointmentNode.ParentNode.ReplaceChild(CreateAppointmentNode(owner, appointmentToUpdate), appointmentNode);
  
            SaveDataFile();
        }
  
        /// <summary>
        /// Deletes the specified appointment.
        /// </summary>
        /// <param name="owner">The owner RadScheduler instance.</param>
        /// <param name="appointmentToDelete">The appointment to delete.</param>
        public override void Delete(RadScheduler owner, Appointment appointmentToDelete)
        {
            EnsureFilePath(owner);
            LoadDataFile();
  
            XmlNode appointmentNode = _doc.SelectSingleNode("//Appointments/Appointment[ID=" + appointmentToDelete.ID + "]");
  
            if (appointmentNode != null)
            {
                appointmentNode.ParentNode.RemoveChild(appointmentNode);
  
                SaveDataFile();
            }
        }
  
        /// <summary>
        /// Gets the resource types.
        /// </summary>
        /// <param name="owner">The owner RadScheduler instance.</param>
        /// <returns></returns>
        public override IEnumerable<ResourceType> GetResourceTypes(RadScheduler owner)
        {
            EnsureFilePath(owner);
            LoadDataFile();
  
            List<string> resourceTypeNames = new List<string>();
            foreach (Resource res in _resources)
            {
                if (!resourceTypeNames.Contains(res.Type))
                {
                    resourceTypeNames.Add(res.Type);
                }
            }
  
            List<ResourceType> resourceTypes = new List<ResourceType>();
            foreach (string resourceTypeName in resourceTypeNames)
            {
                resourceTypes.Add(new ResourceType(resourceTypeName));
            }
  
            return resourceTypes;
        }
  
        /// <summary>
        /// Gets the type of the resources by.
        /// </summary>
        /// <param name="owner">The owner RadScheduler instance.</param>
        /// <param name="resourceType">Type of the resource.</param>
        /// <returns></returns>
        public override IEnumerable<Resource> GetResourcesByType(RadScheduler owner, string resourceType)
        {
            EnsureFilePath(owner);
            LoadDataFile();
  
            return _resources.FindAll(delegate(Resource res) { return res.Type == resourceType; });
        }
  
  
        private void LoadResources()
        {
            _resources = new List<Resource>();
  
            foreach (XmlNode resourcesNode in _doc.SelectNodes("//Appointments/Resources"))
            {
                foreach (XmlNode resourceNode in resourcesNode.ChildNodes)
                {
                    Resource resource = new Resource();
                    _resources.Add(resource);
  
                    resource.Type = resourceNode.Name;
  
                    foreach (XmlNode resourceData in resourceNode.ChildNodes)
                    {
                        switch (resourceData.Name)
                        {
                            case "Key":
                                resource.Key = resourceData.InnerText;
                                break;
  
                            case "Text":
                                resource.Text = resourceData.InnerText;
                                break;
  
                            default:
                                resource.Attributes[resourceData.Name] = resourceData.InnerText;
                                break;
                        }
                    }
                }
            }
        }
  
        private void LoadAppointmentResources(RadScheduler owner, Appointment appointment, XmlNode appointmentResourcesNode)
        {
            foreach (XmlNode resourceNode in appointmentResourcesNode.ChildNodes)
            {
                string type = resourceNode.Name;
                string key = resourceNode.Attributes["Key"].Value;
                Resource res = GetResource(owner, type, key);
  
                if (res != null)
                {
                    appointment.Resources.Add(res);
                }
                else
                {
                    throw new Exception(
                        string.Format("Cannot find resource of type '{0}' with Key={1} for appointment with ID={2}.",
                        type, key, appointment.ID));
                }
            }
        }
  
        private Resource GetResource(RadScheduler owner, string type, object key)
        {
            List<Resource> resourcesFilteredByType = (List<Resource>) GetResourcesByType(owner, type);
            return resourcesFilteredByType.Find(delegate(Resource res) { return (key != null) && res.Key.Equals(key); });
        }
  
        private XmlNode CreateAppointmentNode(RadScheduler owner, Appointment appointment)
        {
            XmlNode appointmentNode = _doc.CreateNode(XmlNodeType.Element, "Appointment", string.Empty);
  
            XmlNode appointmentID = _doc.CreateNode(XmlNodeType.Element, "ID", string.Empty);
            appointmentID.InnerText = appointment.ID.ToString();
            appointmentNode.AppendChild(appointmentID);
  
            XmlNode appointmentSubject = _doc.CreateNode(XmlNodeType.Element, "Subject", string.Empty);
            appointmentSubject.InnerText = appointment.Subject;
            appointmentNode.AppendChild(appointmentSubject);
  
            if (owner.EnableDescriptionField)
            {
                XmlNode appointmentDescription = _doc.CreateNode(XmlNodeType.Element, "Description", string.Empty);
                appointmentDescription.InnerText = appointment.Description;
                appointmentNode.AppendChild(appointmentDescription);
            }
  
            XmlNode appointmentStart = _doc.CreateNode(XmlNodeType.Element, "Start", string.Empty);
            appointmentStart.InnerText = appointment.Start.ToUniversalTime().ToString(DateFormatString, CultureInfo.InvariantCulture);
            appointmentNode.AppendChild(appointmentStart);
  
            XmlNode appointmentEnd = _doc.CreateNode(XmlNodeType.Element, "End", string.Empty);
            appointmentEnd.InnerText = appointment.End.ToUniversalTime().ToString(DateFormatString, CultureInfo.InvariantCulture);
            appointmentNode.AppendChild(appointmentEnd);
  
            if (!string.IsNullOrEmpty(appointment.RecurrenceRule))
            {
                XmlNode appointmentRecurrenceRule = _doc.CreateNode(XmlNodeType.Element, "RecurrenceRule", string.Empty);
                appointmentNode.AppendChild(appointmentRecurrenceRule);
  
                XmlNode recurrenceRuleCdata = _doc.CreateNode(XmlNodeType.CDATA, string.Empty, string.Empty);
                appointmentRecurrenceRule.AppendChild(recurrenceRuleCdata);
  
                recurrenceRuleCdata.InnerText = appointment.RecurrenceRule;
            }
  
            if (appointment.RecurrenceState == RecurrenceState.Exception)
            {
                XmlNode appointmentRecurrenceParentID = _doc.CreateNode(XmlNodeType.Element, "RecurrenceParentID", string.Empty);
                appointmentRecurrenceParentID.InnerText = appointment.RecurrenceParentID.ToString();
                appointmentNode.AppendChild(appointmentRecurrenceParentID);
            }
  
            if (appointment.Reminders.Count > 0)
            {
                var reminderNode = _doc.CreateNode(XmlNodeType.Element, "Reminder", string.Empty);
                appointmentNode.AppendChild(reminderNode);
  
                var reminderCdata = _doc.CreateNode(XmlNodeType.CDATA, string.Empty, string.Empty);
                reminderNode.AppendChild(reminderCdata);
  
                reminderCdata.InnerText = appointment.Reminders.ToString().Trim();
            }
  
            SaveAppointmentResources(appointment, appointmentNode);
            SaveAppointmentAttributes(appointment, appointmentNode);
  
            return appointmentNode;
        }
  
        [MethodImpl(MethodImplOptions.Synchronized)]
        private void LoadDataFile()
        {
            if (string.IsNullOrEmpty(_dataFileName))
            {
                return;
            }
  
            if (_documentLoaded && !_persistChanges)
            {
                // Work in-memory
                return;
            }
  
            _doc.Load(_dataFileName);
            _documentLoaded = true;
  
            _nextID = ReadNextID();
            LoadResources();
        }
  
        [MethodImpl(MethodImplOptions.Synchronized)]
        private void SaveDataFile()
        {
            if (_persistChanges && !string.IsNullOrEmpty(_dataFileName))
            {
                _doc.Save(_dataFileName);
            }
        }
  
        private void EnsureFilePath(Control owner)
        {
            if (string.IsNullOrEmpty(_dataFileName))
                return;
  
            if (!_dataFileName.StartsWith("~") && File.Exists(_dataFileName))
            {
                return;
            }
  
            if (owner.Page != null)
            {
                _dataFileName = owner.Page.MapPath(_dataFileName);
            }
            else if (HttpContext.Current != null)
            {
                _dataFileName = HttpContext.Current.Request.MapPath(_dataFileName);
            }
        }
  
        private void SaveAppointmentResources(Appointment appointment, XmlNode appointmentNode)
        {
            if (appointment.Resources.Count == 0)
            {
                return;
            }
  
            XmlNode resourcesGroupNode = _doc.CreateNode(XmlNodeType.Element, "Resources", string.Empty);
            appointmentNode.AppendChild(resourcesGroupNode);
            foreach (Resource res in appointment.Resources)
            {
                XmlNode resourceNode = _doc.CreateNode(XmlNodeType.Element, res.Type, string.Empty);
                resourcesGroupNode.AppendChild(resourceNode);
  
                XmlAttribute keyAttribute = _doc.CreateAttribute("Key");
                resourceNode.Attributes.Append(keyAttribute);
                keyAttribute.InnerText = res.Key.ToString();
            }
        }
  
        private void SaveAppointmentAttributes(Appointment appointment, XmlNode appointmentNode)
        {
            foreach (string attribute in appointment.Attributes.Keys)
            {
                if (!String.IsNullOrEmpty(appointment.Attributes[attribute]))
                {
                    XmlNode attributeNode = _doc.CreateNode(XmlNodeType.Element, "Attribute", string.Empty);
                    appointmentNode.AppendChild(attributeNode);
  
                    XmlAttribute keyAttribute = _doc.CreateAttribute("Key");
                    attributeNode.Attributes.Append(keyAttribute);
                    keyAttribute.InnerText = attribute;
  
                    XmlAttribute valueAttribute = _doc.CreateAttribute("Value");
                    attributeNode.Attributes.Append(valueAttribute);
                    valueAttribute.InnerText = appointment.Attributes[attribute];
                }
            }
        }
  
        private int ReadNextID()
        {
            XmlNode nextIDNode = _doc.SelectSingleNode("//Appointments/NextID");
            return nextIDNode != null ? int.Parse(nextIDNode.InnerText) : 1;
        }
    }
}


Greetings,
Peter
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
Tags
Scheduler
Asked by
mulligann
Top achievements
Rank 1
Answers by
Peter
Telerik team
mulligann
Top achievements
Rank 1
peter brandt
Top achievements
Rank 1
Shaan
Top achievements
Rank 1
Share this question
or