using framework_business; using framework_library; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using Telerik.Web.UI; public partial class controls_module_calendar : System.Web.UI.UserControl, ISurfaceControlBase { private const string ProviderSessionKey = "SchedulerContextMenuCSharp"; XmlSchedulerProvider Provider { get { XmlSchedulerProvider provider = (XmlSchedulerProvider)Session[ProviderSessionKey]; if (Session[ProviderSessionKey] == null || !IsPostBack) { provider = new XmlSchedulerProvider(); Session[ProviderSessionKey] = provider; } return provider; } } #region methods private bool BindCalendarList() { try { int userId = 0; if (utils.verifySession("user")) userId = ((oUser)Session["user"]).recId; List list = new List(); oDynamicParam param1 = new oDynamicParam(); param1.paramDisplayName = "userId"; param1.paramObject = userId; list.Add(param1); ArrayList calList = xData.GetTypedCollectionByProc("recId", typeof(oCalendar), "sp_CalendarAccess", list); ddCalendar.DataSource = calList; ddCalendar.DataTextField = "name"; ddCalendar.DataValueField = "recId"; ddCalendar.DataBind(); if (calList != null && calList.Count > 0) { radCalendar.ReadOnly = false; return true; } else return false; } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); return false; } } /// /// Bind Calendar Schedule /// /// private void BindCalendar(int calendarId, bool isPatientSearch = false, SchedulerViewType schedulerViewType = SchedulerViewType.AgendaView) { try { radCalendar.AgendaView.NumberOfDays = 30; string eventTypes = String.Empty; //filter event types //var types = lstEventTypes.Items.GetSelectedItems(); //eventTypes = String.Join(",", types.Select(x => x.Value).ToArray()); //filter locations string eventLocations = String.Empty; if (utils.verifySession("eventLocations")) { eventLocations = Session["eventLocations"].ToString(); String[] locations = eventLocations.Split(char.Parse(",")); foreach (string loc in locations) { foreach (ListItem item in lstRooms.Items) { if (item.Value == loc) { item.Selected = true; break; } } } } else { var locations = lstRooms.Items.GetSelectedItems(); eventLocations = String.Join(",", locations.Select(x => x.Value).ToArray()); } //filter statuses string statuses = String.Empty; if (utils.verifySession("eventStatuses")) { statuses = Session["eventStatuses"].ToString(); String[] stats = statuses.Split(char.Parse(",")); foreach (string stat in stats) { foreach (ListItem item in lstEventStatuses.Items) { if (item.Value == stat) { item.Selected = true; break; } } } } else { var stats = lstEventStatuses.Items.GetSelectedItems(); statuses = String.Join(",", stats.Select(x => x.Value).ToArray()); } //filter users - pass through as param //string user = String.Empty; //if (Request.Form[hfcalauto.UniqueID] != null) // user = Request.Form[hfcalauto.UniqueID]; //Determine the selcted date range on the schedule DateTime startRange = radCalendar.VisibleRangeStart; startRange = new DateTime(startRange.Year, startRange.Month, 1); DateTime endRange = radCalendar.VisibleRangeEnd; endRange = endRange.AddMonths(1).AddDays(-1); //custom query based on filters StringBuilder customQuery = new StringBuilder(); customQuery.Append("SELECT * FROM [dbo].[pal_CalendarEvent] "); customQuery.Append("WHERE calendarID = " + calendarId + " "); if (!isPatientSearch)//exclude date range for patient search customQuery.Append("AND ([start] > '" + utils.fixDate(startRange.AddDays(-1).Date) + "' AND [end] < '" + utils.fixDate(endRange.AddDays(1).Date) + "') "); if (statuses != String.Empty) customQuery.Append("AND statusID IN (" + statuses + ") "); if (eventTypes != String.Empty) customQuery.Append("AND calendarEventTypeId IN (" + eventTypes + ") "); if (eventLocations != String.Empty) customQuery.Append("AND calendarRoomId IN (" + eventLocations + ") "); if (User != String.Empty) { customQuery.Append("AND (Users LIKE '%" + User + "%') "); } //fetch the data DataTable dt = xData.GetCustomTypedTable(customQuery.ToString()); //need to set recurrence settings to null, otherwise it binds to calendar incorrectly dt = utils.ChangeDataTableColumnZerosToNull(dt, "recurrenceParentId"); if (eventLocations != String.Empty) { DataTable locationSource = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oCalendarRoom), "recId", eventLocations, ""); radCalendar.ResourceTypes[0].DataSource = locationSource; radCalendar.GroupBy = "Date,Location"; } else { radCalendar.GroupBy = ""; } //bind to the schedule radCalendar.DataSource = dt; radCalendar.DataBind(); //set to agenda view for a patient if (isPatientSearch) { radCalendar.SelectedView = schedulerViewType; radCalendar.SelectedDate = DateTime.Now.AddDays(-15); radCalendar.AgendaView.NumberOfDays = 30; hfcalauto.Value = null; txbSearchPatient.Value = ""; } else if (handler.ReturnSetup().code == "STUD-1") { radCalendar.AgendaView.NumberOfDays = 31; } else { radCalendar.AgendaView.NumberOfDays = 7; } hfcalendarId.Value = ddCalendar.SelectedValue; upFilters.Update(); } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Method to configure the schedule defaults /// /// private void configureScheduleDefaults(int calendarId) { try { //setup context menu foreach (oCalendarEventModule mod in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEventModule), "calendarId", calendarId.ToString())) { if (mod.moduleId == pNums.Module.Surface.GetHashCode()) { //show menu items for billing and profiles SchedulerAppointmentContextMenu.Items[3].Visible = true; SchedulerAppointmentContextMenu.Items[4].Visible = true; SchedulerAppointmentContextMenu.Items[5].Visible = true; SchedulerAppointmentContextMenu.Items[6].Visible = true; } else { //hide menu items for billing and profiles SchedulerAppointmentContextMenu.Items[3].Visible = false; SchedulerAppointmentContextMenu.Items[4].Visible = false; SchedulerAppointmentContextMenu.Items[5].Visible = false; SchedulerAppointmentContextMenu.Items[6].Visible = false; } } if (handler.ReturnSetup().code == "STUD-1") { divBillingModule.Visible = false; if (SchedulerAppointmentContextMenu.Items.FindItemByValue("enquiryview") != null) { SchedulerAppointmentContextMenu.Items.Remove(SchedulerAppointmentContextMenu.Items.FindItemByValue("enquiryview")); if (SchedulerAppointmentContextMenu.Items.FindItemByValue("enquiryviewSeparator") != null) SchedulerAppointmentContextMenu.Items.Remove(SchedulerAppointmentContextMenu.Items.FindItemByValue("enquiryviewSeparator")); } if (SchedulerAppointmentContextMenu.Items.FindItemByValue("contactview") != null) { SchedulerAppointmentContextMenu.Items.Remove(SchedulerAppointmentContextMenu.Items.FindItemByValue("contactview")); if (SchedulerAppointmentContextMenu.Items.FindItemByValue("contactViewSeparator") != null) SchedulerAppointmentContextMenu.Items.Remove(SchedulerAppointmentContextMenu.Items.FindItemByValue("contactViewSeparator")); } } //setup the calendar foreach (oCalendar cal in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendar), "recId", calendarId.ToString())) { //minutes per row radCalendar.MinutesPerRow = cal.interval; //radCalendar.TimeLabelRowSpan = 1; radCalendar.TimeSlotContextMenuSettings.EnableDefault = true; //radCalendar.OverflowBehavior = OverflowBehavior.Expand; radCalendar.NumberOfHoveredRows = 1; //default view switch (cal.defaultView.ToLower()) { case "day": radCalendar.SelectedView = SchedulerViewType.DayView; break; case "multi-day": radCalendar.SelectedView = SchedulerViewType.MultiDayView; break; case "week": radCalendar.SelectedView = SchedulerViewType.WeekView; break; case "month": radCalendar.SelectedView = SchedulerViewType.MonthView; break; case "timeline": radCalendar.SelectedView = SchedulerViewType.TimelineView; break; case "agenda": radCalendar.SelectedView = SchedulerViewType.AgendaView; break; } //first day of the week switch (cal.firstDayOfWeek.ToLower()) { case "sunday": radCalendar.FirstDayOfWeek = radCalendar.FirstDayOfWeek = DayOfWeek.Sunday; break; case "monday": radCalendar.FirstDayOfWeek = radCalendar.FirstDayOfWeek = DayOfWeek.Monday; break; case "tuesday": radCalendar.FirstDayOfWeek = radCalendar.FirstDayOfWeek = DayOfWeek.Tuesday; break; case "wednesday": radCalendar.FirstDayOfWeek = radCalendar.FirstDayOfWeek = DayOfWeek.Wednesday; break; case "thursday": radCalendar.FirstDayOfWeek = radCalendar.FirstDayOfWeek = DayOfWeek.Thursday; break; case "friday": radCalendar.FirstDayOfWeek = radCalendar.FirstDayOfWeek = DayOfWeek.Friday; break; case "saturday": radCalendar.FirstDayOfWeek = radCalendar.FirstDayOfWeek = DayOfWeek.Saturday; break; } break; } //build statuses menu ArrayList statuses = xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarStatus), "isActive,calendarId", "1," + ddCalendar.SelectedValue, "status"); SchedulerAppointmentContextMenu.Items[2].Items.Clear(); RadContextMenu menu = new RadContextMenu(); foreach (oCalendarStatus stat in statuses) { RadMenuItem statItem = new RadMenuItem(); statItem.Text = stat.status; statItem.Value = "status:" + stat.recId; menu.Items.Add(statItem); } SchedulerAppointmentContextMenu.Items[2].Items.AddRange(menu.Items.ToArray()); } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Bind sequence /// private void BindSequence() { try { for (int i = 0; i < 20; i++) { //append sequence item ddSequence.Items.Add(new ListItem(i.ToString(), i.ToString())); } } catch (Exception ex) { exception.HandleException("calendar:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Bind users /// /// private void BindUsers(RadComboBox combo) { try { //get customer code from setup table oSetup _setup = new oSetup(); foreach (oSetup setup in xData.GetTypedCollection("recId", typeof(oSetup), "")) { _setup = setup; break; } DataTable dt = new DataTable(); dt.Columns.Add("recId"); dt.Columns.Add("TextField"); foreach (ovUserShared user in xData.GetTypedByCriteriaSpecific("recId", typeof(ovUserShared), "isActive,customerCode", "1," + _setup.code, "name")) { DataRow row = dt.NewRow(); row["recId"] = user.recId; row["TextField"] = user.name + " " + user.surname + " (" + user.email + ")"; dt.Rows.Add(row); } combo.DataSource = dt; combo.DataTextField = "TextField"; combo.DataValueField = "recId"; combo.DataBind(); } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Bind restgricted Access users /// /// private void BindTempRestrictedAccessUsers(ArrayList _calendarUsers) { try { //get customer code from setup table oSetup _setup = new oSetup(); foreach (oSetup setup in xData.GetTypedCollection("recId", typeof(oSetup), "")) { _setup = setup; break; } //ArrayList users = xData.GetTypedCollection("recId", typeof(oUser)); ArrayList users = xData.GetTypedByCriteriaSpecific("recId", typeof(oUser), "isActive,customerCode", "1," + _setup.code, "name", "pal_", true); DataTable dt = new DataTable(); dt.Columns.Add("userId"); dt.Columns.Add("UserEmail"); foreach (oCalendarUser calUser in _calendarUsers) { foreach (oUser user in users) { if (calUser.userId == user.recId) { DataRow row = dt.NewRow(); row["userId"] = calUser.userId; row["UserEmail"] = user.email; dt.Rows.Add(row); break; } } } rptCalendarUsers.DataSource = dt; rptCalendarUsers.DataBind(); } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Bind Event Statuses /// private void BindEventStatuses() { try { DataTable statuses = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oCalendarStatus), "isActive, calendarId", "1," + ddCalendar.SelectedValue, "status"); lstEventStatuses.DataSource = statuses; lstEventStatuses.DataTextField = "status"; lstEventStatuses.DataValueField = "recId"; lstEventStatuses.DataBind(); } catch (Exception ex) { exception.HandleException("calendar:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Bind Rooms /// private void BindRooms() { try { DataTable rooms = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oCalendarRoom), "isActive, calendarId", "1," + ddCalendar.SelectedValue, "name"); lstRooms.DataSource = rooms; lstRooms.DataTextField = "name"; lstRooms.DataValueField = "recId"; lstRooms.DataBind(); } catch (Exception ex) { exception.HandleException("calendar:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Toggle Panels /// /// private void TogglePanels(string panel) { switch (panel) { case "pnlCalendar": //divFilter.Visible = true; pnlFilters.Visible = true; upFilters.Update(); divLabel.Visible = false; divNew.Visible = true; //pnlCalendar.Visible = true; //pnlCalendarForm.Visible = false; //upCalendarSchedule.Update(); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "hideCalForm", "$('#modCalendar').modal('hide');", true); break; case "pnlCalendarForm": //divFilter.Visible = false; pnlFilters.Visible = false; upFilters.Update(); divLabel.Visible = true; divNew.Visible = false; //pnlCalendar.Visible = false; //pnlCalendarForm.Visible = true; upCalendarForm.Update(); //show modal ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "showCalForm", "$('#modCalendar').modal();", true); break; } } /// /// Populate Calendar values /// /// /// private void PopulateCalendarFormValues(oCalendar _calendar, ArrayList _calendarUsers) { try { divButtons.Visible = (_calendar.recId > 0); txtCalendarName.Text = _calendar.name; txtCalendarDescription.Text = _calendar.description; txtInterval.Text = _calendar.interval.ToString(); if (_calendar.firstDayOfWeek != String.Empty) ddfirstDayOfWeek.SelectedValue = _calendar.firstDayOfWeek; if (_calendar.defaultView != String.Empty) ddDefaultView.SelectedValue = _calendar.defaultView; chkIsActive.Checked = _calendar.isActive; chkIsDoubleBook.Checked = _calendar.isDoubleBook; chkIsAccessRestricted.Checked = _calendar.isAccessRestricted; ddBillingModule.SelectedValue = _calendar.billingModule.ToString(); if (_calendar.sequence > 0) ddSequence.SelectedValue = _calendar.sequence.ToString(); if (_calendar.isAccessRestricted) { BindUsers(rcbCalendarUsers); BindTempRestrictedAccessUsers(_calendarUsers); pnlCalendarUsers.Visible = true; } } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Save Calendar values /// /// private void SaveCalendarFormValues(ref oCalendar calendar) { try { calendar.name = txtCalendarName.Text.Trim(); calendar.description = txtCalendarDescription.Text.Trim(); calendar.interval = int.Parse(txtInterval.Text); calendar.firstDayOfWeek = ddfirstDayOfWeek.SelectedItem.Value; calendar.defaultView = ddDefaultView.SelectedItem.Value; calendar.isDoubleBook = chkIsDoubleBook.Checked; calendar.isAccessRestricted = chkIsAccessRestricted.Checked; int userId = 0; if (utils.verifySession("user")) userId = ((oUser)Session["user"]).recId; if (calendar.recId > 0) { calendar.dateUpdated = System.DateTime.Now; calendar.userIdUpdated = userId; } else { calendar.dateSaved = System.DateTime.Now; calendar.userIdSaved = userId; } if (ddBillingModule.SelectedValue != null && ddBillingModule.SelectedValue != String.Empty) calendar.billingModule = int.Parse(ddBillingModule.SelectedValue); calendar.sequence = int.Parse(ddSequence.SelectedItem.Value); calendar.isActive = chkIsActive.Checked; } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Bind Rooms /// private void BindCalendarModules() { try { DataTable mods = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oModule), "isCalendar", "1", "module"); ddCalendarModules.DataSource = mods; ddCalendarModules.DataTextField = "module"; ddCalendarModules.DataValueField = "recId"; ddCalendarModules.DataBind(); ddCalendarModules.Items.Insert(0, new ListItem("select...", "0")); } catch (Exception ex) { exception.HandleException("calendar:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Bind Rooms /// private void BindCalendarSurfaces() { try { DataTable apps = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oSurface), "isActive", "1", "surface"); if (handler.ReturnSetup().code == "STUD-1") { ArrayList allowedSurfaces = new ArrayList(); allowedSurfaces.Add("Profiles"); DataTable sourceSurface = apps.AsEnumerable() .Where(r => allowedSurfaces.Contains(r.Field("name"))) .CopyToDataTable(); ddCalendarSurface.DataSource = sourceSurface; } else ddCalendarSurface.DataSource = apps; ddCalendarSurface.DataTextField = "surface"; ddCalendarSurface.DataValueField = "recId"; ddCalendarSurface.DataBind(); ddCalendarSurface.Items.Insert(0, new ListItem("select...", "0")); } catch (Exception ex) { exception.HandleException("calendar:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Bind Rooms /// private void BindCalendarSurfaceFieldOptions(int surfaceId) { try { DataTable fields = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oSurfaceField), "surfaceId,surfaceFieldTypeId", surfaceId.ToString() + "," + pNums.FieldType.Text.GetHashCode(), "surfaceFieldName"); DataTable fieldNames = new DataTable(); DataTable fieldSurnames = new DataTable(); DataTable fieldEmails = new DataTable(); DataTable fieldMobile = new DataTable(); if (handler.ReturnSetup().code == "STUD-1") { fieldNames = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oSurfaceField), "isActive,surfaceFieldTypeId,surfaceId,surfaceFieldName", "1,~()3|29," + surfaceId.ToString() + ",~%name", "surfaceFieldName"); fieldSurnames = fieldNames.Copy(); DataTable emailFields = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oSurfaceField), "isActive,validationType,surfaceId", "1," + ((int)pNums.ValidationType.Email).ToString() + "," + surfaceId.ToString(), "surfaceFieldName"); foreach (oSurfaceField labelFields in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceField), "isActive,surfaceFieldTypeId,surfaceId", "1,29," + surfaceId.ToString(), "surfaceFieldName")) { foreach (oSurfaceField labelEmailFields in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceField), "recId,validationType", labelFields.relationalFields + "," + ((int)pNums.ValidationType.Email).ToString())) { DataTable emailLabelFields = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oSurfaceField), "recId", labelFields.recId.ToString()); emailFields.Merge(emailLabelFields); } } fieldEmails = emailFields.Copy(); DataTable numberFields = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oSurfaceField), "isActive,validationType,surfaceId", "1," + ((int)pNums.ValidationType.ContactNumber).ToString() + "," + surfaceId.ToString(), "surfaceFieldName"); foreach (oSurfaceField labelFields in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceField), "isActive,surfaceFieldTypeId,surfaceId", "1,29," + surfaceId.ToString(), "surfaceFieldName")) { foreach (oSurfaceField labelNumberFields in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceField), "recId,validationType", labelFields.relationalFields + "," + ((int)pNums.ValidationType.ContactNumber).ToString())) { DataTable numberLabelFields = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oSurfaceField), "recId", labelFields.recId.ToString()); numberFields.Merge(numberLabelFields); } } fieldMobile = numberFields.Copy(); } else { fieldNames = fields.Copy(); fieldSurnames = fields.Copy(); fieldEmails = fields.Copy(); fieldMobile = fields.Copy(); } ddCalenderNameField.DataSource = fieldNames; ddCalenderNameField.DataTextField = "surfaceFieldName"; ddCalenderNameField.DataValueField = "recId"; ddCalenderNameField.DataBind(); ddCalenderNameField.Items.Insert(0, new ListItem("select...", "0")); ddCalenderSurnameField.DataSource = fieldSurnames; ddCalenderSurnameField.DataTextField = "surfaceFieldName"; ddCalenderSurnameField.DataValueField = "recId"; ddCalenderSurnameField.DataBind(); ddCalenderSurnameField.Items.Insert(0, new ListItem("select...", "0")); ddCalendarEmailField.DataSource = fieldEmails; ddCalendarEmailField.DataTextField = "surfaceFieldName"; ddCalendarEmailField.DataValueField = "recId"; ddCalendarEmailField.DataBind(); ddCalendarEmailField.Items.Insert(0, new ListItem("select...", "0")); ddCalendarMobileField.DataSource = fieldMobile; ddCalendarMobileField.DataTextField = "surfaceFieldName"; ddCalendarMobileField.DataValueField = "recId"; ddCalendarMobileField.DataBind(); ddCalendarMobileField.Items.Insert(0, new ListItem("select...", "0")); } catch (Exception ex) { exception.HandleException("calendar:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Save Calendar Configuration /// /// /// private bool SaveCalenderConfig(oCalendar _calendar) { bool result = false; try { oCalendarEventModule calMod = new oCalendarEventModule(); foreach (oCalendarEventModule mod in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEventModule), "calendarId", _calendar.recId.ToString())) { calMod = mod; break; } calMod.calendarId = _calendar.recId; calMod.moduleId = int.Parse(ddCalendarModules.SelectedValue); if (calMod.moduleId == pNums.Module.Surface.GetHashCode()) { calMod.entityId = int.Parse(ddCalendarSurface.SelectedValue); calMod.entityNameField = int.Parse(ddCalenderNameField.SelectedValue); calMod.entitySurnameField = int.Parse(ddCalenderSurnameField.SelectedValue); calMod.entityEmailField = int.Parse(ddCalendarEmailField.SelectedValue); calMod.entityMobileField = int.Parse(ddCalendarMobileField.SelectedValue); } if (calMod.recId > 0)//update { result = xData.UpdateTyped("recId", calMod.recId.ToString(), typeof(oCalendarEventModule), calMod); } else//save { calMod.recId = xData.SaveTyped("recId", typeof(oCalendarEventModule), calMod); if (calMod.recId > 0) result = true; } } catch (Exception ex) { exception.HandleException("calendar:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } return result; } /// /// Populate Calendar Configuration /// /// private void PopulateCalendarConfig(oCalendar _calendar) { try { oCalendarEventModule calMod = new oCalendarEventModule(); foreach (oCalendarEventModule mod in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEventModule), "calendarId", _calendar.recId.ToString())) { calMod = mod; break; } if (calMod.recId > 0) { if (ddCalendarModules.Items.FindByValue(calMod.moduleId.ToString()) != null) ddCalendarModules.SelectedValue = calMod.moduleId.ToString(); if (calMod.moduleId == pNums.Module.Surface.GetHashCode()) { BindCalendarSurfaces(); pnlSurfaceModule.Visible = true; if (ddCalendarSurface.Items.FindByValue(calMod.entityId.ToString()) != null) ddCalendarSurface.SelectedValue = calMod.entityId.ToString(); if (ddCalendarSurface.SelectedValue != null) { BindCalendarSurfaceFieldOptions(int.Parse(ddCalendarSurface.SelectedValue)); if (ddCalenderNameField.Items.FindByValue(calMod.entityNameField.ToString()) != null) ddCalenderNameField.SelectedValue = calMod.entityNameField.ToString(); if (ddCalenderSurnameField.Items.FindByValue(calMod.entitySurnameField.ToString()) != null) ddCalenderSurnameField.SelectedValue = calMod.entitySurnameField.ToString(); if (ddCalendarEmailField.Items.FindByValue(calMod.entityEmailField.ToString()) != null) ddCalendarEmailField.SelectedValue = calMod.entityEmailField.ToString(); if (ddCalendarMobileField.Items.FindByValue(calMod.entityMobileField.ToString()) != null) ddCalendarMobileField.SelectedValue = calMod.entityMobileField.ToString(); } if (ddBillingModule.Items.FindByValue(_calendar.billingModule.ToString()) != null) ddBillingModule.SelectedValue = _calendar.billingModule.ToString(); } else { pnlSurfaceModule.Visible = false; } } } catch (Exception ex) { exception.HandleException("calendar:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Reload Control /// /// /// /// public void ReloadControl(oSurfaceFieldData controlFieldData, bool alternateView = false, bool readOnly = false) { try { SetupCalendar(); User = controlFieldData.surfaceItemId.ToString(); int calendarId = int.Parse(ddCalendar.SelectedItem.Value); if (alternateView) { //divFilter.Visible = false; pnlFilters.Visible = false; radCalendar.ShowHeader = false; radCalendar.EnableDatePicker = false; radCalendar.AllowDelete = false; radCalendar.AllowEdit = false; radCalendar.AllowInsert = false; radCalendar.AgendaView.DateColumnWidth = 150; radCalendar.AgendaView.TimeColumnWidth = 150; BindCalendar(calendarId, true); } else { //divFilter.Visible = false; BindCalendar(calendarId, true, SchedulerViewType.MonthView); } } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Save Control Data /// /// public void SaveControlData(ref oSurfaceFieldData _surfaceFieldData) { try { } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } #endregion #region events /// /// Init /// /// /// private void Page_Init(object sender, EventArgs e) { //radCalendar.Provider = Provider; } protected override void OnPreRender(EventArgs e) { // "Group By Calendar" context menu item //RadMenuItem menuItem = radCalendar.TimeSlotContextMenus[0].Items[3]; //if (String.IsNullOrEmpty(radCalendar.GroupBy)) //{ // menuItem.Text = "Group by Calendar"; // menuItem.Value = "EnableGrouping"; //} //else //{ // menuItem.Text = "Disable Grouping"; // menuItem.Value = "DisableGrouping"; //} base.OnPreRender(e); } /// /// Page Load Event /// /// /// protected void Page_Load(object sender, EventArgs e) { try { if (!IsPostBack) { LoadCalendar(); } } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } private void LoadCalendar() { string canvasName = handler.GetRoutedData("canvas-title"); foreach (oCanvas canvas in xData.GetTypedByCriteriaSpecific("recId", typeof(oCanvas), "name", canvasName)) { foreach (oCanvasMetaData met in xData.GetTypedByCriteriaSpecific("recId", typeof(oCanvasMetaData), "canvasId", canvas.recId.ToString())) { if (met.moduleId != pNums.Module.Surface.GetHashCode()) { SetupCalendar(); } } } } /// /// Setup the Calendar /// private void SetupCalendar() { try { BindUsers(rcbCalendarUsers); BindSequence(); //if no calendars defined, create default calendar if (!BindCalendarList()) { oCalendar calendar = new oCalendar(); calendar.name = "Calendar"; calendar.description = "Calendar"; calendar.interval = 30; calendar.firstDayOfWeek = "Sunday"; calendar.defaultView = "Month"; calendar.isDoubleBook = true; calendar.isAccessRestricted = false; calendar.dateSaved = System.DateTime.Now; int userId = 0; if (utils.verifySession("user")) userId = ((oUser)Session["user"]).recId; calendar.userIdSaved = userId; calendar.sequence = 1; calendar.isActive = true; calendar.recId = xData.SaveTyped("recId", typeof(oCalendar), calendar); ddCalendar.Items.Insert(0, new ListItem(calendar.name, calendar.recId.ToString())); } if (Request.Form[hfcalauto.UniqueID] != null) User = Request.Form[hfcalauto.UniqueID]; BindEventStatuses(); BindRooms(); if (utils.verifySession("surfaceToEventId")) { int eventId = Convert.ToInt32(Session["surfaceToEventId"].ToString()); utils.disposeSession("surfaceToEventId"); int calId = 0; foreach (oCalendarEvent eventItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEvent), "recId", eventId.ToString())) { calId = eventItem.calendarId; } if (ddCalendar.Items.FindByValue(calId.ToString()) != null) ddCalendar.Items.FindByValue(calId.ToString()).Selected = true; BindCalendar(calId); BindCalendarModules(); configureScheduleDefaults(calId); radCalendar.ShowAdvancedEditForm(radCalendar.Appointments.FindByID(eventId)); } else { BindCalendar(int.Parse(ddCalendar.SelectedItem.Value)); BindCalendarModules(); configureScheduleDefaults(int.Parse(ddCalendar.SelectedItem.Value)); } } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// New Calendar /// /// /// protected void btnNew_Click(object sender, EventArgs e) { try { lblCalendarResult.Text = ""; lblCalendarResult.Visible = false; utils.disposeSession("calendar"); utils.disposeSession("tempRestrictedAccessUsers"); oCalendar calendar = new oCalendar(); calendar.recId = 0; calendar.interval = 30; calendar.isActive = true; calendar.isDoubleBook = true; ArrayList calendarUsers = new ArrayList(); PopulateCalendarFormValues(calendar, calendarUsers); PopulateCalendarConfig(calendar); TogglePanels("pnlCalendarForm"); } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Save Calendar /// /// /// protected void btnSaveCalendar_Click(object sender, EventArgs e) { try { oCalendar calendar = new oCalendar(); if (utils.verifySession("calendar")) //update mode { calendar = (oCalendar)Session["calendar"]; SaveCalendarFormValues(ref calendar); if (xData.UpdateTyped("recId", calendar.recId.ToString(), typeof(oCalendar), calendar)) { Session["calendar"] = calendar; SaveCalenderConfig(calendar); BindCalendarList(); if (Request.Form[hfcalauto.UniqueID] != null) User = Request.Form[hfcalauto.UniqueID]; BindCalendar(int.Parse(ddCalendar.SelectedItem.Value)); lblCalendarResult.Visible = true; lblCalendarResult.Text = "your changes were updated successfully."; } } else { if (!xData.VerifyExists("recId", typeof(oCalendar), "name", txtCalendarName.Text)) { //save form values SaveCalendarFormValues(ref calendar); calendar.recId = xData.SaveTyped("recId", typeof(oCalendar), calendar); if (calendar.recId > 0) { Session["calendar"] = calendar; SaveCalenderConfig(calendar); BindCalendarList(); if (Request.Form[hfcalauto.UniqueID] != null) User = Request.Form[hfcalauto.UniqueID]; BindCalendar(int.Parse(ddCalendar.SelectedItem.Value)); divButtons.Visible = true; lblCalendarResult.Visible = true; lblCalendarResult.Text = "your calendar was created successfully."; } } else { lblCalendarResult.Visible = true; lblCalendarResult.Text = "a calendar with this name already exists in the system."; } } } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Cancel Calendar click event /// /// /// protected void btnCancelCalendar_Click(object sender, EventArgs e) { BindRooms(); BindEventStatuses(); TogglePanels("pnlCalendar"); } /// /// Checked changed for restricted /// /// /// protected void chkIsAccessRestricted_CheckedChanged(object sender, EventArgs e) { try { if (!utils.verifySession("user")) { ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myAlert", "alert('Access restrictions can only be changed by a logged on user. Please log in and try again.');", true); chkIsAccessRestricted.Checked = !chkIsAccessRestricted.Checked; return; } if (chkIsAccessRestricted.Checked) { int calId = 0; if (utils.verifySession("calendar")) calId = ((oCalendar)Session["calendar"]).recId; //use current list of calendar users if exists. ensure that logged on user is granted access oUser userLog = (oUser)Session["user"]; ArrayList list = new ArrayList(); if (utils.verifySession("tempRestrictedAccessUsers")) { list = (ArrayList)Session["tempRestrictedAccessUsers"]; } bool exists = false; foreach (oCalendarUser usr in list) { if (usr.userId == userLog.recId) { exists = true; break; } } if (!exists) { oCalendarUser calUser = new oCalendarUser(); calUser.calendarId = calId; calUser.userId = userLog.recId; calUser.isViewOnly = false; list.Add(calUser); Session["tempRestrictedAccessUsers"] = list; } BindTempRestrictedAccessUsers(list); BindUsers(rcbCalendarUsers); pnlCalendarUsers.Visible = true; } else { pnlCalendarUsers.Visible = false; } } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Selected Index Changed for users /// /// /// protected void rcbCalendarUsers_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e) { try { int calId = 0; if (utils.verifySession("calendar")) calId = ((oCalendar)Session["calendar"]).recId; ArrayList list = new ArrayList(); if (utils.verifySession("tempRestrictedAccessUsers")) { list = (ArrayList)Session["tempRestrictedAccessUsers"]; } oCalendarUser calUser = new oCalendarUser(); calUser.calendarId = calId; calUser.userId = int.Parse(e.Value); //calUser.userEmail = e.Text.Substring(e.Text.LastIndexOf("(") + 1, e.Text.Length - e.Text.LastIndexOf("(") - 2); calUser.isViewOnly = false; bool exists = false; foreach (oCalendarUser usr in list) { if (usr.userId == calUser.userId) { exists = true; break; } } rcbCalendarUsers.ClearSelection(); rcbCalendarUsers.Text = ""; if (!exists) { list.Add(calUser); Session["tempRestrictedAccessUsers"] = list; BindTempRestrictedAccessUsers(list); } else ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myAlert1", "alert('The selected user has already been granted access to this calendar.');", true); } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Remove Calendar user /// /// /// protected void lnkRemoveCalendarUser_Click(object sender, EventArgs e) { try { if (sender.GetType() == typeof(LinkButton)) { if (!utils.verifySession("user")) { ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myAlert2", "alert('User access can only be changed by a logged on user. Please log in and try again.');", true); return; } int userId = int.Parse(((LinkButton)sender).CommandArgument); oUser userLog = (oUser)Session["user"]; if (userId == userLog.recId) { ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myAlert2", "alert('The current user cannot be removed from the access list.');", true); return; } if (utils.verifySession("tempRestrictedAccessUsers")) { ArrayList list = (ArrayList)Session["tempRestrictedAccessUsers"]; for (int i = list.Count - 1; i >= 0; i--) { oCalendarUser user = (oCalendarUser)list[i]; if (user.userId == userId) list.RemoveAt(i); } Session["tempRestrictedAccessUsers"] = list; BindTempRestrictedAccessUsers(list); } } } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Edit Calendar Click event /// /// /// protected void btnEditCalendar_Click(object sender, EventArgs e) { try { lblCalendarResult.Text = ""; lblCalendarResult.Visible = false; int calendarId = int.Parse(ddCalendar.SelectedItem.Value); ArrayList calList = xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendar), "recId", calendarId.ToString()); if (calList == null || calList.Count <= 0) throw new Exception("Calendar " + calendarId + " not found."); oCalendar calendar = (oCalendar)calList[0]; ArrayList calendarUsers = xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarUser), "calendarId", calendar.recId.ToString()); Session["tempRestrictedAccessUsers"] = calendarUsers; Session["calendar"] = calendar; PopulateCalendarFormValues(calendar, calendarUsers); PopulateCalendarConfig(calendar); TogglePanels("pnlCalendarForm"); } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Remove Calendar event /// /// /// protected void btnRemoveCalendar_Click(object sender, EventArgs e) { try { int calendarId = int.Parse(ddCalendar.SelectedItem.Value); ArrayList calendars = xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendar), "recId", calendarId.ToString()); if (calendars == null || calendars.Count <= 0) throw new Exception("Calendar " + calendarId + " not found."); oCalendar calendar = (oCalendar)calendars[0]; //only delete if there aren't any events linked to calendar ArrayList events = xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEvent), "calendarId", calendar.recId.ToString()); if (events != null && events.Count > 0) { ScriptManager.RegisterStartupScript(Page, Page.GetType(), "removeAlert", "alert('The selected calendar has events linked to it and cannot be deleted.');", true); return; } //delete calendar if (xData.DeleteTyped("recId", calendar.recId.ToString(), typeof(oCalendar))) { //also delete calendar user records foreach (oCalendarUser calUser in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarUser), "calendarId", calendar.recId.ToString())) { xData.DeleteTyped("recId", calUser.recId.ToString(), typeof(oCalendarUser)); } if (!BindCalendarList()) { ddCalendar.Items.Add(new ListItem("None", "0")); radCalendar.ReadOnly = true; } if (Request.Form[hfcalauto.UniqueID] != null) User = Request.Form[hfcalauto.UniqueID]; BindCalendar(int.Parse(ddCalendar.SelectedItem.Value)); } } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Selected Index Changed for Calender Picklist /// /// /// protected void ddCalendar_SelectedIndexChanged(object sender, EventArgs e) { try { if (Request.Form[hfcalauto.UniqueID] != null) User = Request.Form[hfcalauto.UniqueID]; //dispose previous selected sessions utils.disposeSession("eventLocations"); utils.disposeSession("eventStatuses"); BindRooms(); BindEventStatuses(); BindCalendar(int.Parse(ddCalendar.SelectedItem.Value)); configureScheduleDefaults(int.Parse(ddCalendar.SelectedItem.Value)); } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Selected index changed for location /// /// /// protected void lstRooms_SelectedIndexChanged(object sender, EventArgs e) { try { int calendarId = int.Parse(ddCalendar.SelectedItem.Value); if (Request.Form[hfcalauto.UniqueID] != null) User = Request.Form[hfcalauto.UniqueID]; if (lstRooms.Items.GetSelectedItems().Any()) { var locations = lstRooms.Items.GetSelectedItems(); Session["eventLocations"] = String.Join(",", locations.Select(x => x.Value).ToArray()); } else { utils.disposeSession("eventLocations"); } BindCalendar(calendarId); } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Event Types selection changed event /// /// /// protected void lstEventTypes_SelectedIndexChanged(object sender, EventArgs e) { try { int calendarId = int.Parse(ddCalendar.SelectedItem.Value); if (Request.Form[hfcalauto.UniqueID] != null) User = Request.Form[hfcalauto.UniqueID]; BindCalendar(calendarId); } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Event Statuses Selected Index Change /// /// /// protected void lstEventStatuses_SelectedIndexChanged(object sender, EventArgs e) { try { int calendarId = int.Parse(ddCalendar.SelectedItem.Value); if (Request.Form[hfcalauto.UniqueID] != null) User = Request.Form[hfcalauto.UniqueID]; Session["eventStatuses"] = ""; if (lstEventStatuses.Items.GetSelectedItems().Any()) { var stats = lstEventStatuses.Items.GetSelectedItems(); Session["eventStatuses"] = String.Join(",", stats.Select(x => x.Value).ToArray()); } BindCalendar(calendarId); } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Search for patient /// /// /// protected void btnPatientSearch_Click(object sender, EventArgs e) { try { int calendarId = int.Parse(ddCalendar.SelectedItem.Value); if (Request.Form[hfcalauto.UniqueID] != null) User = Request.Form[hfcalauto.UniqueID]; BindCalendar(calendarId, true); } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Selected Index changd event for Calendar Moduels /// /// /// protected void ddCalendarModules_SelectedIndexChanged(object sender, EventArgs e) { try { if (ddCalendarModules.SelectedValue != null) { if (int.Parse(ddCalendarModules.SelectedValue) == pNums.Module.Surface.GetHashCode()) { BindCalendarSurfaces(); pnlSurfaceModule.Visible = true; } else { pnlSurfaceModule.Visible = false; } } } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Selected index Changed event /// /// /// protected void ddCalendarSurface_SelectedIndexChanged(object sender, EventArgs e) { try { if (ddCalendarSurface.SelectedValue != null) { BindCalendarSurfaceFieldOptions(int.Parse(ddCalendarSurface.SelectedValue)); } } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } protected void btnEventTypes_Click(object sender, EventArgs e) { try { oCalendar calendar = new oCalendar(); if (utils.verifySession("calendar")) //update mode { calendar = (oCalendar)Session["calendar"]; dynamic uc = this.FindControl("ucEventType"); uc.ReloadControl(calendar.recId); ScriptManager.RegisterStartupScript(Page, Page.GetType(), "modalEventTypes", "$('#modCalendarEventType').modal('show');", true); } } catch (Exception ex) { exception.HandleException("calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } protected void btnLocations_Click(object sender, EventArgs e) { try { oCalendar calendar = new oCalendar(); if (utils.verifySession("calendar")) //update mode { calendar = (oCalendar)Session["calendar"]; dynamic uc = this.FindControl("ucRoom"); uc.ReloadControl(calendar.recId); ScriptManager.RegisterStartupScript(Page, Page.GetType(), "modalRooms", "$('#modCalendarRoom').modal('show');", true); } } catch (Exception ex) { exception.HandleException("calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } protected void btnStatuses_Click(object sender, EventArgs e) { try { oCalendar calendar = new oCalendar(); if (utils.verifySession("calendar")) //update mode { calendar = (oCalendar)Session["calendar"]; dynamic uc = this.FindControl("ucEventStatus"); uc.ReloadControl(calendar.recId); ScriptManager.RegisterStartupScript(Page, Page.GetType(), "modalStatuses", "$('#modCalendarEventStatuses').modal('show');", true); } } catch (Exception ex) { exception.HandleException("calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } protected void btnUpdate_Click(object sender, EventArgs e) { //if (ViewState["btnRefreshed"] == null) //{ // ViewState["btnRefreshed"] = 1; //} //else //{ // btnUpdate.Visible = false; // upCalendarSchedule.Update(); //} upCalendarSchedule.Update(); } #endregion #region calendar events /// /// Form Created Event /// /// /// protected void radCalendar_FormCreated(object sender, Telerik.Web.UI.SchedulerFormCreatedEventArgs e) { try { if (e.Container.Mode == SchedulerFormMode.AdvancedEdit) { //reverse visible state (this method also invoked when cancelling add / edit //divFilter.Visible = !divFilter.Visible; pnlFilters.Visible = false; upFilters.Update(); oCalendarEvent calEvent = new oCalendarEvent(); if (e.Appointment.ID == null) { if (e.Appointment.RecurrenceParentID == null) { throw new Exception("Parent ID of recurring event is null."); } string parentRecId = e.Appointment.RecurrenceParentID.ToString(); ArrayList list = xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEvent), "recId", parentRecId); if (list == null || list.Count <= 0) throw new Exception("Event with parent ID " + parentRecId + " could not be found."); oCalendarEvent calParent = (oCalendarEvent)list[0]; //copy details of recurring parent event, except recId, parentRecId, recurrence. when save on form, new event will created as a copy. calEvent.calendarEventTypeId = calParent.calendarEventTypeId; calEvent.calendarId = calParent.calendarId; calEvent.calendarRoomId = calParent.calendarRoomId; calEvent.calendarRoomOther = calParent.calendarRoomOther; calEvent.customerId = calParent.customerId; calEvent.dateSaved = calParent.dateSaved; calEvent.dateUpdated = calParent.dateUpdated; calEvent.emailReminderMin = calParent.emailReminderMin; calEvent.end = e.Appointment.End; calEvent.isEmailReminder = calParent.isEmailReminder; calEvent.recurrenceParentId = calParent.recId; calEvent.start = e.Appointment.Start; calEvent.subject = calParent.subject; calEvent.userIdSaved = calParent.userIdSaved; calEvent.userIdUpdated = calParent.userIdUpdated; calEvent.users = calParent.users; } else { string recId = e.Appointment.ID.ToString(); ArrayList list = xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEvent), "recId", recId); if (list == null || list.Count <= 0) throw new Exception("Event with ID " + recId + " could not be found."); calEvent = (oCalendarEvent)list[0]; } dynamic uc = e.Container.FindControl("ucUpdateEvent"); uc.CalendarId = int.Parse(ddCalendar.SelectedItem.Value); uc.Event = calEvent; Session["eventPersist"] = calEvent; if (!uc.Reloaded) uc.ReloadControl(); } else if (e.Container.Mode == SchedulerFormMode.AdvancedInsert) { //reverse visible state (this method also invoked when cancelling add / edit //divFilter.Visible = !divFilter.Visible; pnlFilters.Visible = false; upFilters.Update(); dynamic uc = e.Container.FindControl("ucInsertEvent"); uc.CalendarId = int.Parse(ddCalendar.SelectedItem.Value); oCalendarEvent calEvent = new oCalendarEvent(); calEvent.start = e.Appointment.Start; calEvent.end = e.Appointment.End; if (e.Appointment.Resources.Count > 0 && e.Appointment.Resources[0].Key != null) calEvent.calendarRoomId = int.Parse(e.Appointment.Resources[0].Key.ToString()); uc.Event = calEvent; if (!uc.Reloaded) { uc.ReloadControl(); } } } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Form Creating event /// /// /// protected void radCalendar_FormCreating(object sender, Telerik.Web.UI.SchedulerFormCreatingEventArgs e) { if (e.Mode == SchedulerFormMode.AdvancedInsert) { utils.disposeSession("tempInsertUsers"); } } /// /// Insert Appt event /// /// /// protected void radCalendar_AppointmentInsert(object sender, AppointmentInsertEventArgs e) { try { int calendarId = int.Parse(ddCalendar.SelectedItem.Value); if (Request.Form[hfcalauto.UniqueID] != null) User = Request.Form[hfcalauto.UniqueID]; BindCalendar(calendarId); e.Cancel = true; //divFilter.Visible = true; pnlFilters.Visible = true; upFilters.Update(); radCalendar.Rebind(); } catch (Exception ex) { e.Cancel = true; exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Update Appointment event /// /// /// protected void radCalendar_AppointmentUpdate(object sender, AppointmentUpdateEventArgs e) { try { int calendarId = int.Parse(ddCalendar.SelectedItem.Value); int apptId = int.Parse(e.Appointment.ID.ToString()); if (!utils.verifySession("eventUpdated")) { foreach (oCalendarEvent calEv in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEvent), "recId", apptId.ToString())) { calEv.start = e.ModifiedAppointment.Start; calEv.end = e.ModifiedAppointment.End; if (e.ModifiedAppointment.Resources.Count > 0) calEv.calendarRoomId = int.Parse(e.ModifiedAppointment.Resources[0].Key.ToString()); xData.UpdateTyped("recId", calEv.recId.ToString(), typeof(oCalendarEvent), calEv); break; } } else { utils.disposeSession("eventUpdated"); } if (Request.Form[hfcalauto.UniqueID] != null) User = Request.Form[hfcalauto.UniqueID]; BindCalendar(calendarId); e.Cancel = true; //divFilter.Visible = true; pnlFilters.Visible = true; upFilters.Update(); radCalendar.Rebind(); } catch (Exception ex) { e.Cancel = true; exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Delete Appointment Event /// /// /// protected void radCalendar_AppointmentDelete(object sender, AppointmentDeleteEventArgs e) { try { int calendarId = int.Parse(ddCalendar.SelectedItem.Value); int recId = int.Parse(e.Appointment.ID.ToString()); foreach (oCalendarEventContact contact in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEventContact), "calendarEventId", recId.ToString())) { xData.DeleteTyped("recId", contact.recId.ToString(), typeof(oCalendarEventContact)); } xData.DeleteTyped("recId", recId.ToString(), typeof(oCalendarEvent)); if (Request.Form[hfcalauto.UniqueID] != null) User = Request.Form[hfcalauto.UniqueID]; BindCalendar(calendarId); e.Cancel = true; radCalendar.Rebind(); upCalendarSchedule.Update(); } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Delete occurance event /// /// /// protected void radCalendar_OccurrenceDelete(object sender, OccurrenceDeleteEventArgs e) { try { //when deleting a single occurrence, update master event with exception int calendarId = int.Parse(ddCalendar.SelectedItem.Value); int masterRecId = int.Parse(e.Appointment.ID.ToString()); ArrayList list = xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEvent), "recId", masterRecId.ToString()); if (list == null || list.Count <= 0) throw new Exception("Master event with ID " + masterRecId + " could not be found."); oCalendarEvent master = (oCalendarEvent)list[0]; RecurrenceRule rule; RecurrenceRule.TryParse(master.recurrenceRule, out rule); rule.Range.Start = master.start; rule.Range.EventDuration = master.end - master.start; var exceptionStartDateUtc = DateTime.SpecifyKind(e.OccurrenceAppointment.Start, DateTimeKind.Utc); rule.Exceptions.Add(exceptionStartDateUtc); master.recurrenceRule = rule.ToString(); xData.UpdateTyped("recId", master.recId.ToString(), typeof(oCalendarEvent), master); if (Request.Form[hfcalauto.UniqueID] != null) User = Request.Form[hfcalauto.UniqueID]; BindCalendar(calendarId); e.Cancel = true; radCalendar.Rebind(); } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Calendar Databound event /// /// /// protected void radCalendar_AppointmentDataBound(object sender, SchedulerEventArgs e) { try { string recId = e.Appointment.ID.ToString(); if (recId.IndexOf("_") > 0) recId = recId.Substring(0, recId.IndexOf("_")); //get event to get event type to get colour foreach (oCalendarEvent calEvent in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEvent), "recId", recId)) { string eventTypeName = ""; foreach (oCalendarEventType eventType in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEventType), "recId", calEvent.calendarEventTypeId.ToString())) { //CVH 2017-06-27 Re-enable setting of backcolor e.Appointment.BackColor = System.Drawing.ColorTranslator.FromHtml(eventType.colour); e.Appointment.BorderColor = System.Drawing.ColorTranslator.FromHtml(eventType.colour); eventTypeName = eventType.name; break; } //get users and show in subject line on calendar string users = ""; if (calEvent.users != String.Empty) { foreach (oUser usr in xCalendar.GetUsersForCalendar(calEvent.calendarId, calEvent.users)) { if (users == "") users += usr.name + " " + usr.surname; else users += ", " + usr.name + " " + usr.surname; } } else if (calEvent.isNewContact) { users = calEvent.newContactName + " " + calEvent.newContactSurname; } //e.Appointment.Subject = "" + e.Appointment.Subject; //if subject is blank, set event type as the subject if (e.Appointment.Subject == "") e.Appointment.Subject = eventTypeName; //add users to subject line if any if (users != "") e.Appointment.Subject += ": " + users; } } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Time slot created Event /// /// /// protected void radCalendar_TimeSlotCreated(object sender, TimeSlotCreatedEventArgs e) { try { if (radCalendar.SelectedView == SchedulerViewType.WeekView || radCalendar.SelectedView == SchedulerViewType.MonthView) { if (e.TimeSlot.Start.Date.ToString("yyyy-MM-dd") == System.DateTime.Now.ToString("yyyy-MM-dd")) { e.TimeSlot.CssClass = "today"; } } } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Appointment Created Event /// /// /// protected void radCalendar_AppointmentCreated(object sender, AppointmentCreatedEventArgs e) { HtmlGenericControl apptIcon = (HtmlGenericControl)e.Container.FindControl("apptIcon"); HtmlGenericControl apptBilledIcon = (HtmlGenericControl)e.Container.FindControl("apptBilledIcon"); if (apptIcon != null) { int apptId = 0; int.TryParse(e.Appointment.ID.ToString(), out apptId); if (apptId > 0) { foreach (oCalendarEvent evnt in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEvent), "recId", apptId.ToString())) { if (evnt.statusId > 0) { foreach (oCalendarStatus stat in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarStatus), "recId", evnt.statusId.ToString())) { apptIcon.Attributes.Remove("class"); apptIcon.Attributes.Add("class", stat.icon + " big-icon"); break; } } if (evnt.isBilled) { apptBilledIcon.Visible = true; } else { apptBilledIcon.Visible = false; } } } } if (e.Appointment.Visible && !IsAppointmentRegisteredForTooltip(e.Appointment) && radCalendar.SelectedView != SchedulerViewType.AgendaView) { string id = e.Appointment.ID.ToString(); foreach (string domElementID in e.Appointment.DomElements) { toolTipManager.TargetControls.Add(domElementID, id, true); } } } /// /// Appointment Command event /// /// /// protected void radCalendar_AppointmentCommand(object sender, AppointmentCommandEventArgs e) { try { } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Time /// /// /// protected void radCalendar_TimeSlotContextMenuItemClicking(object sender, TimeSlotContextMenuItemClickingEventArgs e) { if (e.MenuItem.Value == "EnableGrouping") { radCalendar.GroupBy = "Calendar"; } else if (e.MenuItem.Value == "DisableGrouping") { radCalendar.GroupBy = ""; } } /// /// On Navigation complete event /// /// /// protected void radCalendar_NavigationComplete(object sender, SchedulerNavigationCompleteEventArgs e) { try { int calendarId = int.Parse(ddCalendar.SelectedItem.Value); if (Request.Form[hfcalauto.UniqueID] != null) User = Request.Form[hfcalauto.UniqueID]; BindCalendar(calendarId); } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Resource Header Created event /// /// /// protected void radCalendar_ResourceHeaderCreated(object sender, ResourceHeaderCreatedEventArgs e) { try { Label lblLocation = (Label)e.Container.FindControl("lblLocation"); if (lblLocation.Text != null) { if (e.Container.Resource.Key != null) { int locationId = 0; int.TryParse(e.Container.Resource.Key.ToString(), out locationId); if (locationId > 0) { foreach (oCalendarRoom room in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarRoom), "recId", locationId.ToString())) { //set the location heading lblLocation.Text = room.name; break; } } } } } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Context Menut Item Clicked /// /// /// protected void radCalendar_AppointmentContextMenuItemClicked(object sender, AppointmentContextMenuItemClickedEventArgs e) { try { oSetup _setup = handler.ReturnSetup(); if (e.MenuItem.Value != null && e.MenuItem.Value.Contains("status:")) { foreach (oCalendarEvent appt in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEvent), "recId", e.Appointment.ID.ToString())) { appt.statusId = int.Parse(e.MenuItem.Value.Replace("status:", "")); xData.UpdateTyped("recId", appt.recId.ToString(), typeof(oCalendarEvent), appt); int calendarId = int.Parse(ddCalendar.SelectedItem.Value); if (Request.Form[hfcalauto.UniqueID] != null) User = Request.Form[hfcalauto.UniqueID]; BindCalendar(calendarId); if (e.MenuItem.Text.ToLower() == "rescheduled") { //create a new appointment //TO Do } } } else if (e.MenuItem.Value != null && e.MenuItem.Value.ToLower().Equals("contactview")) { foreach (oCalendarEvent appt in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEvent), "recId", e.Appointment.ID.ToString())) { //TO DO //LOOK at pal_CalendarEventModule to get the linked module it and entity id to determine the surfaceItemId foreach (oCalendarEventModule mod in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEventModule), "calendarId", appt.calendarId.ToString())) { foreach (oUser usr in xCalendar.GetUsersForCalendar(appt.calendarId, appt.users)) { //set the sessions of the referrer so it goes into edit mode Session["referItem"] = usr.recId; foreach (oCanvasMetaData meta in xData.GetTypedByCriteriaSpecific("recId", typeof(oCanvasMetaData), "isActive,moduleId,entityId", "1," + pNums.Module.Surface.GetHashCode() + "," + mod.entityId.ToString())) { string redirectpath = String.Empty; //find canvas page to redirect to foreach (oCanvas page in xData.GetTypedByCriteriaSpecific("recId", typeof(oCanvas), "recId", meta.canvasId.ToString(), "sequence")) { redirectpath = page.name.ToLower(); break; } if (redirectpath != String.Empty) { Response.Redirect(_setup.securePath + "/pages/" + redirectpath, false); } } break; } } } } else if (e.MenuItem.Value != null && e.MenuItem.Value.Equals("enquiryview")) { foreach (oCalendarEvent appt in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEvent), "recId", e.Appointment.ID.ToString())) { foreach (oCalendar cal in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendar), "recId", appt.calendarId.ToString())) { foreach (oUser usr in xCalendar.GetUsersForCalendar(appt.calendarId, appt.users)) { //set the sessions of the referrer so it goes into edit mode Session["referItem"] = usr.recId; int modId = 0; if (cal.billingModule == 1)//medical { modId = pNums.Module.Enquiry.GetHashCode(); foreach (oCalendarEventModule mod in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEventModule), "calendarId", appt.calendarId.ToString())) { if (utils.verifySession("user")) { oUser currentusr = (oUser)Session["user"]; Session["account"] = xDebtors.SetAccountItem(usr.recId, mod.entityId, currentusr); Session["loadType"] = "Redirected"; } break; } } else//sales { modId = pNums.Module.Sales.GetHashCode(); } foreach (oCanvasMetaData meta in xData.GetTypedByCriteriaSpecific("recId", typeof(oCanvasMetaData), "isActive,moduleId", "1," + modId.ToString())) { string redirectpath = String.Empty; //find canvas page to redirect to foreach (oCanvas page in xData.GetTypedByCriteriaSpecific("recId", typeof(oCanvas), "recId", meta.canvasId.ToString(), "sequence")) { redirectpath = page.name.ToLower(); break; } if (redirectpath != String.Empty) { Response.Redirect(_setup.securePath + "/pages/" + redirectpath, false); } } } } } } } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Cencel Edit /// /// /// protected void radCalendar_AppointmentCancelingEdit(object sender, AppointmentCancelingEditEventArgs e) { try { int calendarId = int.Parse(ddCalendar.SelectedItem.Value); BindCalendar(calendarId); upCalendarSchedule.Update(); pnlFilters.Visible = true; upFilters.Update(); } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// DataBound event /// /// /// protected void radCalendar_DataBound(object sender, EventArgs e) { try { toolTipManager.TargetControls.Clear(); ScriptManager.RegisterStartupScript(this, typeof(Page), "HideToolTip", "hideActiveToolTip();", true); } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } private bool IsAppointmentRegisteredForTooltip(Appointment apt) { foreach (ToolTipTargetControl targetControl in toolTipManager.TargetControls) { if (apt.DomElements.Contains(targetControl.TargetControlID)) { return true; } } return false; } /// /// Ajax Update Event /// /// /// protected void toolTipManager_AjaxUpdate(object sender, ToolTipUpdateEventArgs e) { try { int aptId; Appointment apt; if (!int.TryParse(e.Value, out aptId))//The appointment is occurrence and FindByID expects a string apt = radCalendar.Appointments.FindByID(e.Value); else //The appointment is not occurrence and FindByID expects an int apt = radCalendar.Appointments.FindByID(aptId); controls_module_calendarEventToolTip toolTip = (controls_module_calendarEventToolTip)LoadControl("~/controls/module/calendarEventToolTip.ascx"); toolTip.ID = "ucEventToolTip"; toolTip.TargetAppointment = apt; e.UpdatePanel.ContentTemplateContainer.Controls.Add(toolTip); } catch (Exception ex) { exception.HandleException("Calendar:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } #endregion #region properties public string User { get { if (ViewState["user"] == null) return string.Empty; else return ViewState["user"].ToString(); } set { ViewState["user"] = value; } } #endregion }