Creating a VB Scheduler in ASP.net

Embed Size (px)

Citation preview

  • 7/31/2019 Creating a VB Scheduler in ASP.net

    1/11

    Creating a VB Scheduler in ASP.NET MVC3 RazorIntroductionIn this article you will learn how to quickly create an Outlook-like event calendar in

    Visual Basic for your ASP.NET MVC app. To implement the task we have chosenDHMTLX Scheduler .NETweb control characterized by simplicity and ease in use. Its C#samples have been recently converted to VB.NET, so you can be among the first VBdevelopers to try it.

    By following this step-by-step tutorial, youll get a rich and nice-looking VB eventcalendar like the one on the picture below. The whole process of creation will take about 10minutes.

    The event calendar that we are going to create in this tutorial will have the followingfeatures:

    1. Multiple calendar views, including day, week and month views:

    http://scheduler-net.com/http://scheduler-net.com/http://scheduler-net.com/
  • 7/31/2019 Creating a VB Scheduler in ASP.net

    2/11

    2. Lightboxwith a field for event description and convenient date and time drop-down lists:

    3. Events cascade viewto display events overlapping in time:

  • 7/31/2019 Creating a VB Scheduler in ASP.net

    3/11

    The tutorial consists of 7 main steps. Lets start from the very beginning.

    1. Creating a new ProjectFirst of all, downloadDHTMLX Scheduler .NETarchive and unzip it to a new folder.

    In the root directory youll f ind Scheduler ready samples in VB.NET, including those forASP.NET and MVC3. You can check any of those right now to view the ready VB eventcalendar in action.

    In our tutorial well create an event calendar in MVC3 (VB). Lets start from scratch.Create a new VB project using MVC3 Web Application and name it

    MyCalendar. The default template settings should be as on the picture below:

    http://scheduler-net.com/license.aspx?gettrial=truehttp://scheduler-net.com/license.aspx?gettrial=truehttp://scheduler-net.com/license.aspx?gettrial=truehttp://scheduler-net.com/license.aspx?gettrial=true
  • 7/31/2019 Creating a VB Scheduler in ASP.net

    4/11

    2. Attaching Library to the Project

    Now you need to attach the Scheduler library to your project. First, add DHTML.dll toyour project folder from the Scheduler bin folder. Right-click on your project name to add areference. Then copy the dhtmlxScheduler folder found in the Scripts folder to the Scripts

    folder of your project.3. Setting up a Data Base

    Create a new data base to store your calendar events:a) Go to the Solution Explorer and add a new ASP.NET folder App_Datab) Create a new SQL Server Database and name it MyCalendar.mdfA new database has been created.

    Open MyCalendar.mdf in the Server Explorer. Find the folder Table and add a newtable Events to it. The table should have the following columns:

    Note that a primary key should be set to id and the identity column should beenabled in the table properties.

    4. Modeling the SchedulerAt this step we have to generate a data base model. To implement this, any ORM

    can be used, or you can even do without it. In our project well use LINQ to SQL.Go to Models to add a new item. Select LINQ to SQL Classes and name your model

    Calendar.dbml. Drag the Events table to the model designer surface.

  • 7/31/2019 Creating a VB Scheduler in ASP.net

    5/11

    5. Building up the Event Calendar

    After the data base and the data model are ready, proceed with building up thecalendar itself.

    Add a controller and name it CalendarController.vb. Then create a new Schedulerinstance and pass it to the view.

    Imports DHTMLX.SchedulerImports DHTMLX.Scheduler.DataImports DHTMLX.Common

    Namespace MyCalendarPublic Class CalendarController

    Inherits System.Web.Mvc.ControllerFunction Index() As ActionResult

    Dim scheduler = New DHXScheduler()scheduler.Config.first_hour = 8scheduler.Config.last_hour = 19Return View(scheduler)

    End FunctionEnd Class

    End NamespaceThen create a View to display the event calendar on the web page. Go to Views,create a new folder Calendar and add Index.vbhtml:

  • 7/31/2019 Creating a VB Scheduler in ASP.net

    6/11

    In Index.vbhtml coding we define the calendar height:@Code

    ViewData("Title") = "DHXScheduler"[email protected](Model.Render()) Now customize the scheduler look and feel. Go to Content/Site.css to set up the

    background color and the calendar width:body{

    font-size: 75%;font-family: Verdana, Tahoma, Arial, "Helvetica Neue", Helvetica,

    Sans-Serif;color: #232323;background-color: #5C87B2;width:960px;margin:0 auto;

    }To render the calendar, change the default route in Global.asax from Home to

    Calendar as it is shown below:

    NewWith{.controller = "Calendar", .action = "Index", .id =UrlParameter.Optional} _

    Thats it! A simple event calendar has been created.

  • 7/31/2019 Creating a VB Scheduler in ASP.net

    7/11

    Now you can add events but they are not saved after page reload. Lets update the

    controller config.6. Data Loading and Saving

    Open CalendarController.vb and make the following updates.

    Use a helper class SchedulerAjaxData to render the user collection of objects to jsonstring that the Scheduler can parse:Public Function Data() As ContentResult

    Return New SchedulerAjaxData((New CalendarDataContext()).Events)End Function

    Declare Save function. Every time when a user makes changes, Scheduler sendsinformation on the action type (adding a new entry, deleting or editing an entry) and thechanged event itself:

    Public Function Save(ByVal id As System.Nullable(Of Integer), ByValactionValues As FormCollection) As ContentResult

    To determine the type of action, lets use a special helper class DataAction:

    Dim action = New DataAction(actionValues)Dim data As New CalendarDataContext()Try

    Now we have to build up a data model object from the request variables. We canuse either MVC Model Binder or DHXEventsHelper.Bind available from the library:

    Dim changedEvent =DirectCast(DHXEventsHelper.Bind(GetType([Event]), actionValues), [Event])

  • 7/31/2019 Creating a VB Scheduler in ASP.net

    8/11

    Perform the related operation, depending on the type of DataAction:

    Select Case action.TypeCase DataActionTypes.Insert

    data.Events.InsertOnSubmit(changedEvent) Exit Select

    Case DataActionTypes.DeletechangedEvent =

    data.Events.SingleOrDefault(Function(ev) ev.id = action.SourceId)data.Events.DeleteOnSubmit(changedEvent) Exit Select

    Case Else' "update"Dim eventToUpdate =

    data.Events.SingleOrDefault(Function(ev) ev.id = action.SourceId)DHXEventsHelper.Update(eventToUpdate, changedEvent, New

    List(Of String)() From {"id"})Exit Select

    End Select

    data.SubmitChanges()action.TargetId = changedEvent.idCatch a As Exceptionaction.Type = DataActionTypes.[Error]End Try

    To render response, lets use one more helper AjaxSaveResponse that can beinitialized with the DataAction helper class. AjaxSaveResponse can be implicitly convertedto the ContentResult type.

    Return (New AjaxSaveResponse(action))End Function

    Lets enable saving and loading function and indicate urls for data and save actions.To prevent caching of data requests in browsers, use the PreventCache function.scheduler.LoadData = Truescheduler.EnableDataprocessor = Truescheduler.PreventCache() scheduler.SaveAction = Url.Action("Save", "Calendar")scheduler.DataAction = Url.Action("Data", "Calendar")

    For your convenience, we have added the full coding:Imports DHTMLX.SchedulerImports DHTMLX.Scheduler.DataImports DHTMLX.CommonNamespace MyCalendar

    Public Class CalendarControllerInherits System.Web.Mvc.ControllerFunction Index() As ActionResult

    Dim scheduler = New DHXScheduler()scheduler.Config.first_hour = 8

  • 7/31/2019 Creating a VB Scheduler in ASP.net

    9/11

    scheduler.Config.last_hour = 19scheduler.LoadData = Truescheduler.EnableDataprocessor = Truescheduler.PreventCache()scheduler.SaveAction = Url.Action("Save", "Calendar")scheduler.DataAction = Url.Action("Data", "Calendar")Return View(scheduler)

    End FunctionPublic Function Data() As ContentResult

    Return New SchedulerAjaxData((New CalendarDataContext()).Events)End FunctionPublic Function Save(ByVal id As System.Nullable(Of Integer), ByVal

    actionValues As FormCollection) As ContentResultDim action = New DataAction(actionValues)Dim data As New CalendarDataContext()

    TryDim changedEvent = DirectCast(DHXEventsHelper.Bind(GetType([Event]),

    actionValues), [Event])Select Case action.Type

    Case DataActionTypes.Insertdata.Events.InsertOnSubmit(changedEvent)Exit SelectCase DataActionTypes.DeletechangedEvent = data.Events.SingleOrDefault(Function(ev) ev.id =

    action.SourceId)data.Events.DeleteOnSubmit(changedEvent)Exit SelectCase Else' "update"Dim eventToUpdate = data.Events.SingleOrDefault(Function(ev) ev.id

    = action.SourceId)DHXEventsHelper.Update(eventToUpdate, changedEvent, New List(Of

    String)() From {"id"})Exit Select

    End Selectdata.SubmitChanges()action.TargetId = changedEvent.idCatch a As Exceptionaction.Type = DataActionTypes.[Error]End TryReturn (New AjaxSaveResponse(action))

    End FunctionEnd Class

    End Namespace

    Data saving is enabled. Create new events and refresh the page. Your events arenow saved.

  • 7/31/2019 Creating a VB Scheduler in ASP.net

    10/11

    7. Customizing Settings

    Now well show you how to set the minimum time period for an event. Lets make it

    30 minutes. To implement this, customize the controller config as follows:FunctionIndex() AsActionResult

    Dimscheduler = NewDHXScheduler()....

    scheduler.Config.time_step = 30ReturnView(scheduler)

    EndFunctionIf your events occur at one and the same time, you can simply arrange them as a

    cascade by adding the following code line:scheduler.Config.cascade_event_display = True

    Finally, enable scheduler dynamic loading so that to load only the events of thecalendar viewable area:scheduler.Data.EnableDynamicLoading(SchedulerDataLoader.DynamicalLoadingMode.Month)

    scheduler.Config.cascade_event_display = TrueReturn View(scheduler)

    End Function

  • 7/31/2019 Creating a VB Scheduler in ASP.net

    11/11

    Scheduler will transfer to the server the calendar viewable timeframe borders to loadonly the data of the viewable area:

    Public Function Data() As ContentResultDim dateFrom = DateTime.ParseExact(Me.Request.QueryString("from"),

    "yyyy-MM-dd", CultureInfo.InvariantCulture)Dim dateTo = DateTime.ParseExact(Me.Request.QueryString("to"),

    "yyyy-MM-dd", CultureInfo.InvariantCulture)Return New SchedulerAjaxData(New CalendarDataContext().Events _

    .Where(Function(ev) ev.start_date dateFrom) _

    )End FunctionThe VB Scheduler is ready to use and can be easily integrated into your app.

    ConclusionAfter implementing the steps described in this detailed tutorial, youll get a simple

    event calendar in Visual Basic for ASP.NET that allows you to easily add and manage your

    events. The calendar control can be always customized according to your application

    needs. You can extend its capabilities and add new features or change your calendar color

    scheme, when required.