Implementing a Provider That Supports Multi-Valued Resources
Although they are more difficult to implement, custom providers are more powerful than using data sources because you have more control over every detail of data access operations. Only custom providers can provide the support to allow multi-valued resources (resources that can have multiple values assigned to a single appointment).
The provider is instantiated once per application domain and is shared across threads. RadScheduler ensures basic thread safety by encapsulating each provider in a wrapper that provides locks around each of its public methods. However, you should take care of synchronizing access to instance field members where appropriate.
This example walks through the steps required to build a custom database-driven provider that supports multi-valued resources. The complete source code of the sample provider can be found in the Implementing a Custom Scheduler Provider That Supports Multi-Valued Resources Code Library project.
Database Schema
This example uses a database containing student classes, teachers and students. Each class has one teacher and multiple students. Any student can attend any class. The complete schema for the database is shown below:
Each class is treated by the scheduler as an appointment. Teachers and students are treated as resource types. Note that we keep a cross-link table, ClassStudents, to store the many-to-many relationships between classes and students.
The base class
To make the implementation of database-driven RadScheduler providers easier, Telerik.Web.UI includes an abstract base class - DbSchedulerProviderBase. This base class takes care of common configuration and initialization tasks. When initialization is complete, you can use the DbFactory object or the shortcut methods to create connections, parameters, etc. An outline of DbSchedulerProviderBase is shown below:
public abstract class DbSchedulerProviderBase : SchedulerProviderBase
{
protected DbProviderFactory DbFactory { get { ... }; set { ... }; }
protected bool PersistChanges { get { ... }; set { ... }; }
protected string ConnectionString { get { ... }; set { ... }; }
public override void Initialize(string name, NameValueCollection config) { ... }
protected virtual DbConnection OpenConnection() { ... }
protected virtual DbParameter CreateParameter(string name, object value) { ... }
}
Implementing the provider
- Declare the provider class, inheriting from DbSchedulerProviderBase:
public class MyDbSchedulerProvider : DbSchedulerProviderBase
{
// ...
}
Both SchedulerProviderBase and DbSchedulerProviderBase are abstract classes. The new provider class must provide an implementation for the abstract methods GetAppointments, Insert, Update, Delete, GetResourceTypes, and GetResourcesByType.
- Before implementing the methods that deal with appointments, lay the groundwork by implementing the support for custom resources. The first step is to implement GetResourceTypes to supply the scheduler with a list of available resource types. GetResourceTypes returns only basic information: the name of the resource and a boolean value indicating whether the provider supports multiple resource values for that type. Because this provider supports multiple values of the Student resource, we indicate that now:
public override IEnumerable<ResourceType> GetResourceTypes(RadScheduler owner)
{
ResourceType[] resourceTypes = new ResourceType[2];
resourceTypes[0] = new ResourceType("Teacher", false);
resourceTypes[1] = new ResourceType("Student", true);
return resourceTypes;
}
- Implement the GetResourcesByType method to supply the scheduler with a list of possible values given a resource type. This requires a query to the database to obtain the list of values. Once retrieved, the resources are cached. The base class, DbSchedulerProviderBase, provides the infrastructure for querying the database: The connection is established by calling OpenConnection() and database commands are created using the DbFactory object:
public override IEnumerable<Resource> GetResourcesByType(RadScheduler owner, string resourceType)
{
switch (resourceType)
{
case "Teacher" :
return Teachers.Values;
case "Student" :
return Students.Values;
default:
throw new InvalidOperationException( "Unknown resource type: " + resourceType);
}
}
private IDictionary<int, Resource> Teachers
{
get
{
if (_teachers == null)
{
_teachers = new Dictionary<int, Resource>();
foreach (Resource teacher in LoadTeachers())
{
_teachers.Add((int)teacher.Key, teacher);
}
}
return _teachers;
}
}
private IDictionary<int, Resource> Students
{
get
{
_students = new Dictionary<int, Resource>();
foreach (Resource student in LoadStudents())
{
_students.Add((int)student.Key, student);
}
return _students;
}
}
private IEnumerable<Resource> LoadTeachers()
{
List<Resource> resources = new List<Resource>();
using (DbConnection conn = OpenConnection())
{
DbCommand cmd = DbFactory.CreateCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT [TeacherID], [Name], [Phone] FROM [DbProvider_Teachers]";
using (DbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Resource res = new Resource();
res.Type = "Teacher";
res.Key = reader["TeacherID"];
res.Text = Convert.ToString(reader[ "Name" ]);
res.Attributes["Phone"] = Convert.ToString(reader["Phone"]);
resources.Add(res);
}
}
}
return resources;
}
private IEnumerable<Resource> LoadStudents()
{
List<Resource> resources = new List<Resource>();
using (DbConnection conn = OpenConnection())
{
DbCommand cmd = DbFactory.CreateCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT [StudentID], [Name] FROM [DbProvider_Students]";
using (DbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Resource res = new Resource();
res.Type = "Student";
res.Key = reader["StudentID"];
res.Text = Convert.ToString(reader[ "Name" ]);
resources.Add(res);
}
}
}
return resources;
}
- While we are working with resources, create a private helper method to read the resources for an appointment and assign them to the appointment object. This method will be useful when the provider reads appointments from the database. Note that the resource objects are read from cache.
private void LoadResources(Appointment apt)
{
using (DbConnection conn = OpenConnection())
{
DbCommand cmd = DbFactory.CreateCommand();
cmd.Connection = conn;
cmd.Parameters.Add(CreateParameter("@ClassID", apt.ID));
cmd.CommandText = "SELECT [TeacherID] FROM [DbProvider_Classes] WHERE [ClassID] = @ClassID AND [TeacherID] IS NOT NULL";
using (DbDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
Resource teacher = Teachers[Convert.ToInt32(reader["TeacherID"])];
apt.Resources.Add(teacher);
}
}
cmd.Parameters.Clear();
cmd.Parameters.Add(CreateParameter("@ClassID", apt.ID));
cmd.CommandText = "SELECT [StudentID] FROM [DbProvider_ClassStudents] WHERE [ClassID] = @ClassID";
using (DbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Resource student = Students[Convert.ToInt32(reader["StudentID"])];
apt.Resources.Add(student);
}
}
}
}
- Provide the implementation for GetAppointments to supply the scheduler with a list of all the appointments in the database. Note that this assigns an owner and a class ID before calling LoadResources to load the resources for the appointment:
public override IEnumerable<Appointment> GetAppointments(RadScheduler owner)
{
List<Appointment> appointments = new List<Appointment>();
using (DbConnection conn = OpenConnection())
{
DbCommand cmd = DbFactory.CreateCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT [ClassID], [Subject], [Start], [End], [RecurrenceRule], [RecurrenceParentId] FROM [DbProvider_Classes]";
using (DbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Appointment apt = new Appointment();
apt.Owner = owner;
apt.ID = reader["ClassID"];
apt.Subject = Convert.ToString(reader["Subject"]);
apt.Start = DateTime.SpecifyKind(Convert.ToDateTime(reader["Start"]), DateTimeKind.Utc);
apt.End = DateTime.SpecifyKind(Convert.ToDateTime(reader["End"]), DateTimeKind.Utc);
apt.RecurrenceRule = Convert.ToString(reader["RecurrenceRule"]);
apt.RecurrenceParentID = reader["RecurrenceParentId"] == DBNull.Value ? null : reader["RecurrenceParentId" ];
if (apt.RecurrenceParentID != null)
{
apt.RecurrenceState = RecurrenceState.Exception;
}
else if (apt.RecurrenceRule != string.Empty)
{
apt.RecurrenceState = RecurrenceState.Master;
}
LoadResources(apt);
appointments.Add(apt);
}
}
}
return appointments;
}
Note that this method reads UTC dates from the database. To make this clear to RadScheduler it calls DateTime.SpecifyKind() . You should store dates in UTC format to ensure proper handling of time zones.
This method gets a reference to the scheduler as a parameter (owner). You can use the RadScheduler properties to optimize your query. For example, the VisibleRangeStart and VisibleRangeEnd properties can be used to limit the number of records that the query retrieves. Recurring appointments are evaluated in-memory, however, so they should be always retrieved regardless of VisibleRangeStart and VisibleRangeEnd.
- Before proceeding to the Insert, Update, and Delete commands, the provider needs a few more helper functions. Because the provider is supporting multiple students for each class, it needs helper functions to add and delete these many-to-many relationships in the cross-link table (ClassStudents):
private void FillClassStudents(Appointment appointment, DbCommand cmd, object classId)
{
foreach (Resource student in appointment.Resources.GetResourcesByType("Student"))
{
cmd.Parameters.Clear();
cmd.Parameters.Add(CreateParameter("@ClassID", classId));
cmd.Parameters.Add(CreateParameter("@StudentID", student.Key));
cmd.CommandText = "INSERT INTO [DbProvider_ClassStudents] ([ClassID], [StudentID]) VALUES (@ClassID, @StudentID)";
cmd.ExecuteNonQuery();
}
}
private void ClearClassStudents(object classId, DbCommand cmd)
{
cmd.Parameters.Clear();
cmd.Parameters.Add(CreateParameter("@ClassID", classId));
cmd.CommandText = "DELETE FROM [DbProvider_ClassStudents] WHERE [ClassID] = @ClassID";
cmd.ExecuteNonQuery();
}
- To simplify creating parameters in the Insert and Update methods, add another helper function:
private void PopulateAppointmentParameters(DbCommand cmd, Appointment apt)
{
cmd.Parameters.Add(CreateParameter("@Subject", apt.Subject));
cmd.Parameters.Add(CreateParameter("@Start", apt.Start));
cmd.Parameters.Add(CreateParameter("@End", apt.End));
Resource teacher = apt.Resources.GetResourceByType("Teacher");
object teacherId = null;
if (teacher != null)
{
teacherId = teacher.Key;
}
cmd.Parameters.Add(CreateParameter("@TeacherID", teacherId));
string rrule = null;
if (apt.RecurrenceRule != string.Empty)
{
rrule = apt.RecurrenceRule;
}
cmd.Parameters.Add(CreateParameter("@RecurrenceRule" , rrule));
object parentId = null;
if (apt.RecurrenceParentID != null)
{
parentId = apt.RecurrenceParentID;
}
cmd.Parameters.Add(CreateParameter("@RecurrenceParentId" , parentId));
}
- Inserting appointments is a bit complicated as you need to retrieve the identity value. A stored procedure might be of help here. However, in order to target both MS SQL Server and MS Access, the provider uses normal queries. The Insert method breaks abstraction for the sake of data integrity: MS SQL Server provides the SCOPE_IDENTITY() function to retrieve the identity value of the current transaction, unlike @@IDENTITY that is a global identity value. After inserting the new class and obtaining its identity value, the identity value is passed to the FillClassStudents method, to create the many-to-many relationship between classes and students. The Insert method works in a transaction to ensure data integrity.
public override void Insert(RadScheduler owner, Appointment appointmentToInsert)
{
if (!PersistChanges)
{
return;
}
using (DbConnection conn = OpenConnection())
{
using (DbTransaction tran = conn.BeginTransaction())
{
DbCommand cmd = DbFactory.CreateCommand();
cmd.Connection = conn;
cmd.Transaction = tran;
PopulateAppointmentParameters(cmd, appointmentToInsert);
cmd.CommandText =
@" INSERT INTO [DbProvider_Classes]
([Subject], [Start], [End], [TeacherID],
[RecurrenceRule], [RecurrenceParentID])
VALUES (@Subject, @Start, @End, @TeacherID,
@RecurrenceRule, @RecurrenceParentID)";
if (DbFactory is SqlClientFactory)
{
cmd.CommandText += Environment.NewLine + "SELECT SCOPE_IDENTITY()";
}
else
{
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT @@IDENTITY";
}
int identity = Convert.ToInt32(cmd.ExecuteScalar());
FillClassStudents(appointmentToInsert, cmd, identity);
tran.Commit();
}
}
}
- The most challenging part of the update operation is to manage the many-to-many relationship. The provider needs to clear the cross-link table entries for the appointment and recreate them from scratch:
public override void Update(RadScheduler owner, Appointment appointmentToUpdate)
{
if (!PersistChanges)
{
return;
}
using (DbConnection conn = OpenConnection())
{
using (DbTransaction tran = conn.BeginTransaction())
{
DbCommand cmd = DbFactory.CreateCommand();
cmd.Connection = conn;
cmd.Transaction = tran;
PopulateAppointmentParameters(cmd, appointmentToUpdate);
cmd.Parameters.Add(CreateParameter( "@ClassID", appointmentToUpdate.ID));
cmd.CommandText = "UPDATE [DbProvider_Classes] SET [Subject] = @Subject, [Start] = @Start, [End] = @End, [TeacherID] = @TeacherID, [RecurrenceRule] = @RecurrenceRule, ecurrenceParentID] = @RecurrenceParentID WHERE [ClassID] = @ClassID";
cmd.ExecuteNonQuery();
ClearClassStudents(appointmentToUpdate.ID, cmd);
FillClassStudents(appointmentToUpdate, cmd, appointmentToUpdate.ID);
tran.Commit();
}
}
}
- The Delete method executes two queries: one to delete the entries for the appointment in the cross-link table and another to delete the appointment itself.
public override void Delete(RadScheduler owner, Appointment appointmentToDelete)
{
if (!PersistChanges)
{
return;
}
using (DbConnection conn = OpenConnection())
{
DbCommand cmd = DbFactory.CreateCommand();
cmd.Connection = conn;
using (DbTransaction tran = conn.BeginTransaction())
{
cmd.Transaction = tran;
ClearClassStudents(appointmentToDelete.ID, cmd);
cmd.Parameters.Clear();
cmd.Parameters.Add(CreateParameter( "@ClassID", appointmentToDelete.ID));
cmd.CommandText = "DELETE FROM [DbProvider_Classes] WHERE [ClassID] = @ClassID";
cmd.ExecuteNonQuery();
tran.Commit();
}
}
}