using framework_business;
using framework_library;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Reflection;
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_calendarEvent : System.Web.UI.UserControl
{
#region properties
public bool Reloaded
{
get
{
if (ViewState["reloaded"] == null)
return false;
else
return (bool)ViewState["reloaded"];
}
set
{
ViewState["reloaded"] = true;
}
}
public int CalendarId
{
get
{
if (ViewState["calendarId"] == null)
return 0;
else
return (int)ViewState["calendarId"];
}
set
{
ViewState["calendarId"] = value;
}
}
public oCalendarEvent Event
{
get
{
if (ViewState["event"] == null)
return new oCalendarEvent();
else
return (oCalendarEvent)ViewState["event"];
}
set
{
ViewState["event"] = value;
}
}
#endregion
#region methods
///
/// Persist Event object to session
///
private void PersistEvent()
{
oCalendarEvent _calEvent = new oCalendarEvent();
_calEvent.recId = this.Event.recId;
_calEvent.calendarId = this.CalendarId;
hfcalendarId.Value = this.CalendarId.ToString();
if (utils.verifySession("eventPersist"))
{
_calEvent = (oCalendarEvent)Session["eventPersist"];
}
SaveFormValues(ref _calEvent);
Session["eventPersist"] = _calEvent;
this.Event = _calEvent;
}
///
/// Reload Control
///
public void ReloadControl()
{
try
{
BindEventTypes();
BindRooms();
BindStatuses();
ArrayList users = new ArrayList();
if (utils.verifySession("tempUsers"))
{
users = (ArrayList)Session["tempUsers"];
}
if (this.Event.recId <= 0)
{
btnSaveInsert.Visible = true;
btnSaveUpdate.Visible = false;
}
else
{
btnSaveInsert.Visible = false;
btnSaveUpdate.Visible = true;
if (this.Event.users != String.Empty)
{
users = xCalendar.GetUsersForCalendar(this.CalendarId, this.Event.users);
}
BindAttachments(this.Event.recId, divfTaskAttachments);
BindNotes(this.Event.recId, divfTaskNotes, false);
string[] userArr = this.Event.users.Split(char.Parse(","));
if (userArr.Length > 0)
{
if (userArr[0] != "" && handler.ReturnSetup().code != "STUD-1")
{
divBilingNotes.Visible = true;
BindNotes(int.Parse(userArr[0]), divfBillingNotes, true);
}
}
}
if (utils.verifySession("eventPersist"))
{
oCalendarEvent evnt = (oCalendarEvent)Session["eventPersist"];
if (evnt.recId == this.Event.recId)
{
this.Event = evnt;
}
}
if (handler.ReturnSetup().code == "STUD-1")
{
divBillingNote.Visible = false;
pnlPatient.Visible = false;
pnlSBFProfiles.Visible = true;
if (Event.recId > 0)
{
foreach (oCalendarEventContact contact in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEventContact), "calendarEventId,isIncluded", Event.recId.ToString() + ",1"))
{
pnlSBFComms.Visible = true;
break;
}
}
}
PopulateFormValues(this.Event, users);
this.Reloaded = true;
}
catch (Exception ex)
{
exception.HandleException("CalendarEvent:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Handle Event Type display
///
private void HandleEventTypeDisplay()
{
try
{
//handle interval
int eventTypeId = 0;
if (ddEventType.SelectedItem != null)
int.TryParse(ddEventType.SelectedItem.Value, out eventTypeId);
foreach (oCalendarEventType evType in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEventType), "recId", eventTypeId.ToString()))
{
if (evType.interval > 0)
{
if (evType.interval > 60)//all day event
{
chkAllDay.Checked = true;
txtStartTime.Visible = false;
txtEndTime.Visible = false;
}
else
{
chkAllDay.Checked = false;
txtStartTime.Visible = true;
txtEndTime.Visible = true;
DateTime dt;
if (DateTime.TryParseExact(txtStartTime.Text, "HH:mm", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
txtEndTime.Text = dt.AddMinutes(evType.interval).ToString("HH:mm");
}
}
}
}
}
catch (Exception ex)
{
exception.HandleException("CalendarEvent:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Bind Users
///
///
private void BindTempUsers(ArrayList _list)
{
try
{
rptEventUsers.DataSource = _list;
rptEventUsers.DataBind();
if (_list.Count > 0)
pnlReminder.Visible = true;
else
pnlReminder.Visible = false;
}
catch (Exception ex)
{
exception.HandleException("CalendarEvent:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Bind Event Types
///
private void BindEventTypes()
{
try
{
ddEventType.Items.Clear();
DataTable dt = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oCalendarEventType), "isActive, calendarId", "1," + this.CalendarId, "sequence");
ddEventType.DataSource = dt;
ddEventType.DataTextField = "name";
ddEventType.DataValueField = "recId";
ddEventType.DataBind();
}
catch (Exception ex)
{
exception.HandleException("CalendarEvent:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Bind Statuses
///
private void BindStatuses()
{
try
{
ddStatuses.Items.Clear();
DataTable dt = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oCalendarStatus), "isActive, calendarId", "1," + this.CalendarId);
ddStatuses.DataSource = dt;
ddStatuses.DataTextField = "status";
ddStatuses.DataValueField = "recId";
ddStatuses.DataBind();
}
catch (Exception ex)
{
exception.HandleException("CalendarEvent:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Bind Locations
///
private void BindRooms()
{
try
{
DataTable roomData = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oCalendarRoom), "isActive, calendarId", "1," + this.CalendarId);
ddRoom.DataSource = roomData;
ddRoom.DataTextField = "name";
ddRoom.DataValueField = "recId";
ddRoom.DataBind();
}
catch (Exception ex)
{
exception.HandleException("CalendarEvent:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
private TimeSpan ConvertStringToTimeSpan(string time)
{
try
{
TimeSpan timespan = new TimeSpan(int.Parse(time.Substring(0, 2)), int.Parse(time.Substring(3, 2)), 0);
return timespan;
}
catch (Exception ex)
{
exception.HandleException("CalendarEvent:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
return new TimeSpan();
}
}
private void DeleteRecurrenceExceptions(oCalendarEvent masterEvent)
{
try
{
foreach (oCalendarEvent exception in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEvent), "recurrenceParentId", masterEvent.recId.ToString()))
{
xData.DeleteTyped("recId", exception.recId.ToString(), typeof(oCalendarEvent));
}
}
catch
{
//no action
}
}
///
/// Save Form Values
///
///
private void SaveFormValues(ref oCalendarEvent _event)
{
try
{
//get customer code from setup table
oSetup _setup = new oSetup();
foreach (oSetup setup in xData.GetTypedCollection("recId", typeof(oSetup), ""))
{
_setup = setup;
break;
}
DateTime dtStart = utils.formatStringToDate(txtStartDate.Value);
DateTime dtEnd = utils.formatStringToDate(txtEndDate.Value);
if (!chkAllDay.Checked)
{
dtStart = dtStart.Add(ConvertStringToTimeSpan(txtStartTime.Text));
dtEnd = dtEnd.Add(ConvertStringToTimeSpan(txtEndTime.Text));
}
else
{
//if start and end date is the same, fix end date to start date + 1, otherwise it doesn't save properly
if (dtStart == dtEnd)
dtEnd = dtEnd.AddDays(1);
}
int eventTypeId = 0;
if (ddEventType.SelectedItem == null || ddEventType.SelectedItem.Value == "Manage" || ddEventType.SelectedItem.Value == "Separator")
{
ddEventType.ClearSelection();
ddEventType.SelectedIndex = 0;
}
int.TryParse(ddEventType.SelectedItem.Value, out eventTypeId);
if (eventTypeId <= 0)
throw new Exception("Invalid Event Type " + ddEventType.SelectedItem.Value);
_event.calendarEventTypeId = eventTypeId;
int roomId = 0;
string roomOther = "";
if (ddRoom.SelectedItem != null)
{
if (ddRoom.SelectedItem.Value == "Other")
roomOther = txtRoomOther.Text.Trim();
else
int.TryParse(ddRoom.SelectedItem.Value, out roomId);
}
_event.calendarRoomId = roomId;
_event.calendarRoomOther = roomOther;
_event.calendarId = this.CalendarId;
_event.customerId = _setup.recId;
_event.end = dtEnd;
_event.statusId = int.Parse(ddStatuses.SelectedValue);
_event.isNewContact = chkNewPatient.Checked;
_event.newContactName = txtNewPatientName.Text;
_event.newContactSurname = txtNewPatientSurname.Text;
_event.newContactTel = txtNewPatientTel.Text;
_event.newContactEmail = txtNewPatientEmail.Text;
//when updating a recurring event, need to copy the exceptions from the original rule before overwriting it.
//if there is an existing recurrence rule, get it
if (_event.recurrenceRule != null && _event.recurrenceRule != "")
{
RecurrenceRule ruleOld;
RecurrenceRule.TryParse(_event.recurrenceRule, out ruleOld);
ruleOld.Range.Start = _event.start;
ruleOld.Range.EventDuration = _event.end - _event.start;
//if there is an existing recurrence rule, but recurrence has been removed, need to clear exceptions too
if (eventRecurrence == null || eventRecurrence.RecurrenceRule == null)
{
DeleteRecurrenceExceptions(_event);
}
else //there is existing recurrence and updated recurrence, copy exceptions
{
RecurrenceRule rule;
RecurrenceRule.TryParse(eventRecurrence.RecurrenceRule.ToString(), out rule);
rule.Range.Start = dtStart;
rule.Range.EventDuration = dtEnd - dtStart;
//add exceptions, with start time of current recurrence rule
foreach (DateTime exception in ruleOld.Exceptions)
{
DateTime exceptionDate = exception.Date;
exceptionDate += dtStart.TimeOfDay;
var exceptionStartDateUtc = DateTime.SpecifyKind(exceptionDate, DateTimeKind.Utc);
rule.Exceptions.Add(exceptionStartDateUtc);
}
_event.recurrenceRule = rule.ToString();
}
}
//no existing recurrence, but new recurrence
else if (eventRecurrence != null && eventRecurrence.RecurrenceRule != null)
{
RecurrenceRule rule;
RecurrenceRule.TryParse(eventRecurrence.RecurrenceRule.ToString(), out rule);
rule.Range.Start = dtStart;
rule.Range.EventDuration = dtEnd - dtStart;
_event.recurrenceRule = rule.ToString();
}
if (_event.recurrenceRule == null)
_event.recurrenceRule = "";
_event.start = dtStart;
_event.subject = txtSubject.Text;
string users = "";
if (utils.verifySession("tempUsers"))
{
ArrayList list = (ArrayList)Session["tempUsers"];
foreach (oUser usr in list)
{
if (users == "")
users = usr.recId.ToString();
else
users += "," + usr.recId;
}
}
_event.users = users;
_event.isEmailReminder = false;
_event.emailReminderMin = 0;
if (_event.users != "")
{
if (ddEmailReminder.SelectedItem != null && ddEmailReminder.SelectedItem.Value != "None")
{
_event.isEmailReminder = true;
_event.emailReminderMin = int.Parse(ddEmailReminder.SelectedItem.Value);
}
}
}
catch (Exception ex)
{
exception.HandleException("CalendarEvent:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
private void SaveRecurrenceException(oCalendarEvent _event)
{
try
{
//get recurrence master to update
ArrayList list = xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEvent), "recId", _event.recurrenceParentId.ToString());
if (list == null || list.Count <= 0)
return;
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;
//need to use the date of the occurrence but the time of the master event for the exception to be saved correctly
DateTime exceptionDate = _event.start.Date;
exceptionDate += master.start.TimeOfDay;
var exceptionStartDateUtc = DateTime.SpecifyKind(exceptionDate, DateTimeKind.Utc);
rule.Exceptions.Add(exceptionStartDateUtc);
master.recurrenceRule = rule.ToString();
xData.UpdateTyped("recId", master.recId.ToString(), typeof(oCalendarEvent), master);
}
catch (Exception ex)
{
exception.HandleException("CalendarEvent:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Populate the values to the event object
///
///
///
private void PopulateFormValues(oCalendarEvent _event, ArrayList _users)
{
try
{
txtSubject.Text = _event.subject;
txtStartDate.Value = _event.start.ToString("dd/MM/yyyy");
txtEndDate.Value = _event.end.ToString("dd/MM/yyyy");
txtStartTime.Text = _event.start.ToString("HH:mm");
txtEndTime.Text = _event.end.ToString("HH:mm");
if (txtStartTime.Text == "00:00" && txtEndTime.Text == "00:00")
{
chkAllDay.Checked = true;
txtStartTime.Visible = false;
txtEndTime.Visible = false;
}
else
{
chkAllDay.Checked = false;
txtStartTime.Visible = true;
txtEndTime.Visible = true;
}
if (_event.statusId > 0)
ddStatuses.SelectedValue = _event.statusId.ToString();
if (_event.recurrenceParentId != 0) //recurring appointment, editing single occurrence
{
eventRecurrence.Enabled = false;
}
else if (_event.recurrenceRule != "")
{
RecurrenceRule rule;
RecurrenceRule.TryParse(_event.recurrenceRule, out rule);
rule.Range.Start = _event.start;
rule.Range.EventDuration = _event.end - _event.start;
eventRecurrence.RecurrenceRule = rule;
}
if (ddEventType.Items.FindByValue(_event.calendarEventTypeId.ToString()) != null)
{ ddEventType.SelectedValue = _event.calendarEventTypeId.ToString(); }
if (_event.calendarRoomOther != "")
{
txtRoomOther.Text = _event.calendarRoomOther;
pnlRoomOther.Visible = true;
if (ddRoom.Items.FindByValue("Other") != null)
{
ddRoom.ClearSelection();
ddRoom.Items.FindByValue("Other").Selected = true;
}
}
else if (ddRoom.Items.FindByValue(_event.calendarRoomId.ToString()) != null)
{
pnlRoomOther.Visible = false;
ddRoom.SelectedValue = _event.calendarRoomId.ToString();
}
Session["tempUsers"] = _users;
BindTempUsers(_users);
if (_users != null && _users.Count > 0 && _event.isEmailReminder)
{
pnlReminder.Visible = true;
if (ddEmailReminder.Items.FindByValue(_event.emailReminderMin.ToString()) != null)
{
ddEmailReminder.SelectedValue = _event.emailReminderMin.ToString();
}
}
if (_event.recId > 0)
{
//HandleEventTypeDisplay();
}
chkNewPatient.Checked = _event.isNewContact;
txtNewPatientName.Text = _event.newContactName;
txtNewPatientSurname.Text = _event.newContactSurname;
txtNewPatientTel.Text = _event.newContactTel;
txtNewPatientEmail.Text = _event.newContactEmail;
hfcalendarId.Value = this.CalendarId.ToString();
ToggleNewPatient();
}
catch (Exception ex)
{
exception.HandleException("CalendarEvent:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Save Event
///
///
private bool SaveEvent()
{
bool result = false;
oCalendarEvent calEvent = new oCalendarEvent();
try
{
if (this.Event.recId > 0) //update mode
{
calEvent = this.Event;
SaveFormValues(ref calEvent);
//validate start and end
if (calEvent.end < calEvent.start)
{
lblEventResult.Text = "Event cannot end before it starts.";
lblEventResult.Visible = true;
return false;
}
//set audit details
calEvent.dateUpdated = System.DateTime.Now;
if (utils.verifySession("user"))
{
calEvent.userIdUpdated = ((oUser)Session["user"]).recId;
}
//update
if (xData.UpdateTyped("recId", calEvent.recId.ToString(), typeof(oCalendarEvent), calEvent))
{
this.Event = calEvent;
result = true;
}
}
else
{
//still copy session event, in case it's a new exception to recurring event with parentId set
calEvent = this.Event;
SaveFormValues(ref calEvent);
//validate start and end
if (calEvent.end < calEvent.start)
{
lblEventResult.Text = "Event cannot end before it starts.";
lblEventResult.Visible = true;
return false;
}
//set audit details
calEvent.dateSaved = System.DateTime.Now;
if (utils.verifySession("user"))
{
calEvent.userIdSaved = ((oUser)Session["user"]).recId;
}
//save
calEvent.recId = xData.SaveTyped("recId", typeof(oCalendarEvent), calEvent);
if (calEvent.recId > 0)
{
this.Event = calEvent;
result = true;
}
if (calEvent.recurrenceParentId > 0)
SaveRecurrenceException(calEvent);
}
if (result)
{
utils.disposeSession("tempUsers");
utils.disposeSession("eventPersist");
Session["eventUpdated"] = 1;
}
}
catch (Exception ex)
{
exception.HandleException("CalendarEvent:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
return result;
}
///
/// Toggle Patient view
///
private void ToggleNewPatient()
{
try
{
if (chkNewPatient.Checked)
{
pnlNewPatient.Visible = true;
pnlPatient.Visible = false;
pnlSBFProfiles.Visible = false;
}
else
{
pnlNewPatient.Visible = false;
if (handler.ReturnSetup().code == "STUD-1")
{
pnlPatient.Visible = false;
pnlSBFProfiles.Visible = true;
}
else
{
pnlPatient.Visible = true;
pnlSBFProfiles.Visible = false;
}
}
}
catch (Exception ex)
{
exception.HandleException("CalendarEvent:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
#endregion
#region events
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Load();
}
}
protected void chkAllDay_CheckedChanged(object sender, EventArgs e)
{
try
{
CheckBox chk = (CheckBox)sender;
if (chk != null)
{
if (chk.Checked)
{
txtStartTime.Visible = false;
txtEndTime.Visible = false;
}
else
{
if (txtStartTime.Text == "00:00")
{
txtStartTime.Text = "08:00";
txtEndTime.Text = "09:00";
}
txtEndDate.Value = txtStartDate.Value;
txtStartTime.Visible = true;
txtEndTime.Visible = true;
}
}
}
catch (Exception ex)
{
exception.HandleException("CalendarEvent:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Add Patient
///
///
///
protected void btnAddPatient_Click(object sender, EventArgs e)
{
try
{
string user = String.Empty;
if (Request.Form[hfcalauto.UniqueID] != null)
user = Request.Form[hfcalauto.UniqueID];
if (user != String.Empty)
{
int userId = 0;
int.TryParse(user, out userId);
if (userId > 0)
{
ArrayList list = new ArrayList();
if (utils.verifySession("tempUsers"))
{
list = (ArrayList)Session["tempUsers"];
}
bool exists = false;
foreach (oUser usr in list)
{
if (usr.recId == userId)
{
exists = true;
break;
}
}
oUser Evusr = new oUser();
foreach (oUser us in xCalendar.GetUsersForCalendar(this.CalendarId, userId.ToString()))
{
Evusr = us;
break;
}
if (Evusr.recId > 0)
{
if (!exists)
list.Add(Evusr);
Session["tempUsers"] = list;
BindTempUsers(list);
if (handler.ReturnSetup().code != "STUD-1")
divBilingNotes.Visible = true;
}
}
}
}
catch (Exception ex)
{
exception.HandleException("CalendarEvent:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
protected void lnkRemoveEventUser_Click(object sender, EventArgs e)
{
try
{
if (sender.GetType() == typeof(LinkButton))
{
int userId = int.Parse(((LinkButton)sender).CommandArgument);
if (utils.verifySession("tempUsers"))
{
ArrayList list = (ArrayList)Session["tempUsers"];
for (int i = list.Count - 1; i >= 0; i--)
{
oUser user = (oUser)list[i];
if (user.recId == userId)
list.RemoveAt(i);
}
Session["tempUsers"] = list;
BindTempUsers(list);
}
}
}
catch (Exception ex)
{
exception.HandleException("CalendarEvent:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
///
///
///
///
protected void ddEventType_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
//persist object to session for reload
PersistEvent();
HandleEventTypeDisplay();
}
catch (Exception ex)
{
exception.HandleException("CalendarEvent:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Locations Selection Changed event
///
///
///
protected void ddRoom_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
pnlRoomOther.Visible = false;
DropDownList dd = (DropDownList)sender;
if (dd.SelectedItem.Value == "Other")
pnlRoomOther.Visible = true;
PersistEvent();
}
catch (Exception ex)
{
exception.HandleException("CalendarEvent:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Save Event
///
///
///
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
PersistEvent();
SaveEvent();
}
catch (Exception ex)
{
exception.HandleException("CalendarEvent:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
protected void btnClose_Click(object sender, EventArgs e)
{
utils.disposeSession("eventPersist");
//utils.disposeSession("selectedEventType");
utils.disposeSession("tempUsers");
//no action, CommandName returns to Calendar view
}
///
/// checked changed event
///
///
///
protected void chkNewPatient_CheckedChanged(object sender, EventArgs e)
{
try
{
PersistEvent();
ToggleNewPatient();
}
catch (Exception ex)
{
exception.HandleException("CalendarEvent:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
#endregion
#region note handling
private string GetFileTypeImage(string fileLocation)
{
string imgSrc = "/images/doc.png";
try
{
//string uri = String.Empty;
//if (fileLocation.Contains("http"))
// uri = fileLocation;
//else
// uri = Server.MapPath("~" + fileLocation);
System.Drawing.Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(fileLocation);
if (icon != null)
{
System.Drawing.Image img = icon.ToBitmap();
byte[] byteArray = new byte[0];
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Close();
byteArray = stream.ToArray();
}
string base64 = Convert.ToBase64String(byteArray);
imgSrc = String.Format("data:image/png;base64,{0}", base64);
}
return imgSrc;
}
catch (Exception ex)
{
throw new Exception("Icon conversion to image failed. " + ex.Message);
}
}
///
/// Bind Attachments
///
///
///
private void BindAttachments(int eventId, HtmlGenericControl parentControl)
{
try
{
oSetup _setup = handler.ReturnSetup();
System.Text.StringBuilder formbuilder = new System.Text.StringBuilder();
//get all attachments linked to this event
//CVH 2017-05-24 Arraylist always blank, datatable works fine (entityId?)
//ArrayList files = xData.GetTypedByCriteriaSpecific("recId", typeof(oAttachment), "moduleId,entityId", (int)pNums.Module.Calendar + "," + eventId.ToString(), "dateSaved DESC");
DataTable dtFiles = xData.GetDynamicByCriteriaSpecific("recId", typeof(oAttachment), "moduleId,entityId", (int)pNums.Module.Calendar + "," + eventId.ToString(), "dateSaved DESC");
if (dtFiles != null && dtFiles.Rows.Count > 0)
{
formbuilder.AppendLine("
");
//get all attachments linked to this event
foreach (DataRow row in dtFiles.Rows)
{
string user = "";
foreach (ovUserShared usr in xData.GetTypedByCriteriaSpecific("recId", typeof(ovUserShared), "recId", row["userIdSaved"].ToString()))
{
user = usr.name;
break;
}
string details = "(" + user + " - " + utils.fixDate(row["dateSaved"].ToString()) + ")";
string fileLocation = "";
string pathLocation = "";
string hyperlink = "";
if (row["typeId"].ToString() == pNums.AttachmentType.Document.GetHashCode().ToString())
{
fileLocation = Server.MapPath("~/upload/" + row["folderName"].ToString() + " / file/" + row["fileName"].ToString());
pathLocation = row["sourcePath"].ToString() + " / upload/" + row["folderName"].ToString() + "/file/" + row["fileName"].ToString();
hyperlink = "
" + row["display"].ToString() + "";
}
else
{
fileLocation = Server.MapPath("~/upload/" + row["folderName"].ToString() + "/image/" + row["fileName"].ToString());
pathLocation = row["sourcePath"].ToString() + "/upload/" + row["folderName"].ToString() + "/image/" + row["fileName"].ToString();
hyperlink = "
" + row["display"].ToString() + "";
}
formbuilder.AppendLine(hyperlink);
}
formbuilder.AppendLine("
");
}
parentControl.InnerHtml = formbuilder.ToString();
}
catch (Exception ex)
{
exception.HandleException("Task:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Bind Notes
///
///
///
private void BindNotes(int entityId, HtmlGenericControl parentControl, bool isBilling)
{
try
{
parentControl.InnerHtml = "";
ArrayList taskNotes = new ArrayList();
//get list of all notes linked to this history item
foreach (oNote note in xData.GetTypedByCriteriaSpecific("recId", typeof(oNote), "moduleId,entityId", (int)pNums.Module.Calendar + "," + entityId.ToString(), ""))
{
if (isBilling)
{
if (note.typeId == (int)pNums.NoteType.Billing)
{
taskNotes.Add(note);
}
}
else
{
if (note.typeId != (int)pNums.NoteType.Billing)
{
taskNotes.Add(note);
}
}
}
//order notes by date
if (taskNotes == null || taskNotes.Count <= 0)
return;
var notes = taskNotes.OfType().OrderByDescending(n => n.dateSaved).ToArray();
System.Text.StringBuilder formBuilder = new System.Text.StringBuilder();
bool firstNote = true;
//loop through notes, get attachment linked to note, and add to form
foreach (oNote noteAdd in notes)
{
//start of group
formBuilder.Append(" ");
//heading
formBuilder.AppendLine("
");
//end of heading
//toggle panel
if (firstNote)
{
formBuilder.AppendLine("
");
firstNote = false;
}
else
{
formBuilder.AppendLine("
");
}
//build body of
formBuilder.AppendLine("
");
//build horizontal form
formBuilder.AppendLine("
");
formBuilder.AppendLine("
");
formBuilder.AppendLine("
");
formBuilder.AppendLine("
");
formBuilder.AppendLine("
");
formBuilder.AppendLine("
");
//end of body
formBuilder.AppendLine("
");
//end toggle panel
formBuilder.AppendLine("
");
//end of group
}
parentControl.InnerHtml = formBuilder.ToString();
}
catch (Exception ex)
{
exception.HandleException("Task:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]);
Response.Redirect("/error", false);
}
}
///
/// Add Attachments
///
///
///
protected void btnfAddFile_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myfFileModal", "$('#modAddFile').modal(); ", true);
}
///
/// Add notes
///
///
///
protected void btnfAddNotes_Click(object sender, EventArgs e)
{
lblNoteTypeCustom.Text = string.Empty;
divNoteCustom.Visible = false;
chkBillingNote.Checked = false;
radNewNote.Content = "";
pnlNoteAttachments.Visible = true;
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myfNoteModal", "$('#modAddNote').modal();", true);
upNotesAdd.Update();
}
protected void lnkAddBillingNote_Click(object sender, EventArgs e)
{
lblNoteTypeCustom.Text = string.Empty;
divNoteCustom.Visible = false;
chkBillingNote.Checked = true;
radNewNote.Content = "";
pnlNoteAttachments.Visible = false;
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myfNoteModal", "$('#modAddNote').modal();", true);
upNotesAdd.Update();
}
protected void lnkRemoveBillingNotes_Click(object sender, EventArgs e)
{
string[] userArr = this.Event.users.Split(char.Parse(","));
if (userArr.Length > 0)
{
xData.DeleteTyped("moduleId,entityId,typeId", (int)pNums.Module.Calendar + "," + userArr[0] + "," + (int)pNums.NoteType.Billing, typeof(oNote));
BindNotes(int.Parse(userArr[0]), divfBillingNotes, true);
}
}
///
/// File Uploaded
///
///
///
protected void radUpload_FileUploaded(object sender, FileUploadedEventArgs e)
{
oAttachment Attachment = new oAttachment();
try
{
oUser usr = new oUser();
if (utils.verifySession("user"))
usr = (oUser)Session["user"];
else
{
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "userAlert", "alert('No user login detected. Operation aborted.');", true);
return;
}
if (this.Event.recId == 0)
{
if (!SaveEvent())
return;
}
int itemId = this.Event.recId;
Attachment.entityId = itemId;
Attachment.moduleId = (int)pNums.Module.Calendar;
Attachment.isActive = true;
Attachment.typeId = e.File.ContentType.StartsWith("image") ? (int)pNums.AttachmentType.Image : (int)pNums.AttachmentType.Document;
string taskFolderName = "calendar/";
taskFolderName += this.Event.recId.ToString();
Attachment.folderName = taskFolderName;
/* CVH 2016-04-15 Add date and user */
int userId = usr.recId;
if (Attachment.recId > 0)
{
Attachment.userIdUpdated = userId;
Attachment.dateUpdated = System.DateTime.Now;
}
else
{
Attachment.userIdSaved = userId;
Attachment.dateSaved = System.DateTime.Now;
}
Attachment.display = e.File.FileName.Remove(e.File.FileName.LastIndexOf("."));
Attachment.fileName = Attachment.entityId + "_" + utils.RandomString(9, true) + e.File.FileName.Substring(e.File.FileName.LastIndexOf("."));
string imagePath = Server.MapPath("~/upload/" + Attachment.folderName + "/image/");
string thumbPath = Server.MapPath("~/upload/" + Attachment.folderName + "/thumb/");
string tempPath = Server.MapPath("~/upload/" + Attachment.folderName + "/temp/");
string filePath = Server.MapPath("~/upload/" + Attachment.folderName + "/file/");
utils.validateFolder(imagePath);
utils.validateFolder(thumbPath);
utils.validateFolder(tempPath);
utils.validateFolder(filePath);
Attachment.sourcePath = ConfigurationManager.AppSettings["WebAddy"];
if (Attachment.typeId == pNums.AttachmentType.Image.GetHashCode())
{
//upload file
e.File.SaveAs(tempPath + Attachment.fileName);
//resize and crop for thumbnail
utils.ResizeCropImagePrecise(tempPath + Attachment.fileName, thumbPath, Attachment.fileName, 383, 264, false);
//resize image for a larger size
utils.ResizeImage(tempPath + Attachment.fileName, imagePath, Attachment.fileName, 400, true, true);
}
else
{
//upload file
e.File.SaveAs(filePath + Attachment.fileName);
}
if (Attachment.recId > 0)
{
xData.UpdateTyped("recId", Attachment.recId.ToString(), typeof(oAttachment), Attachment);
utils.disposeSession("Attachment");
}
else
{
Attachment.recId = xData.SaveTyped("recId", typeof(oAttachment), Attachment);
if (Attachment.recId > 0)
{ }
}
}
catch (Exception ex)
{
exception.HandleException("Attachments:", MethodBase.GetCurrentMethod().Name, ex, Session["attachment"]);
Response.Redirect("/error", false);
}
}
///
/// Close File Modal
///
///
///
protected void btnCloseFileModal_Click(object sender, EventArgs e)
{
BindAttachments(this.Event.recId, divfTaskAttachments);
BindNotes(this.Event.recId, divfTaskNotes, false);
string[] userArr = this.Event.users.Split(char.Parse(","));
int user = 0;
if (userArr.Length > 0)
{
if (int.TryParse(userArr[0], out user))
{
BindNotes(user, divfBillingNotes, true);
}
}
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myfFileModalClose", "$('.modal-backdrop').remove(); $('body').removeClass('modal-open');", true);
}
///
/// File Notes uploaded
///
///
///
protected void radUploadNotes_FileUploaded(object sender, FileUploadedEventArgs e)
{
oAttachment Attachment = new oAttachment();
try
{
oUser user = new oUser();
if (utils.verifySession("user"))
user = (oUser)Session["user"];
else
{
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "userAlert", "alert('No user login detected. Operation aborted.');", true);
return;
}
oNote note = new oNote();
if (ViewState["newNote"] == null)
{
if (this.Event.recId == 0)
{
if (!SaveEvent())
return;
}
int itemId = this.Event.recId;
//save new note to link attachment to
note.caption = radNewNote.Content;
note.dateSaved = System.DateTime.Now;
note.entityId = itemId;
note.isActive = true;
note.moduleId = (int)pNums.Module.Calendar;
note.title = user.name + " (" + utils.fixDate(System.DateTime.Now) + ")";
note.typeId = (int)pNums.NoteType.General;
note.userIdSaved = user.recId;
if (ddNoteCustom.SelectedItem != null)
note.customValue = ddNoteCustom.SelectedItem.Text;
note.recId = xData.SaveTyped("recId", typeof(oNote), note);
ViewState["newNote"] = note;
}
else
{
note = (oNote)ViewState["newNote"];
}
Attachment.entityId = note.recId;
Attachment.moduleId = (int)pNums.Module.Notes;
Attachment.isActive = true;
Attachment.typeId = e.File.ContentType.StartsWith("image") ? (int)pNums.AttachmentType.Image : (int)pNums.AttachmentType.Document;
string taskFolderName = "calendar/";
taskFolderName += this.Event.recId.ToString();
Attachment.folderName = taskFolderName;
/* CVH 2016-04-15 Add date and user */
int userId = user.recId;
if (Attachment.recId > 0)
{
Attachment.userIdUpdated = userId;
Attachment.dateUpdated = System.DateTime.Now;
}
else
{
Attachment.userIdSaved = userId;
Attachment.dateSaved = System.DateTime.Now;
}
Attachment.display = e.File.FileName.Remove(e.File.FileName.LastIndexOf("."));
Attachment.fileName = Attachment.entityId + "_" + utils.RandomString(9, true) + e.File.FileName.Substring(e.File.FileName.LastIndexOf("."));
string imagePath = Server.MapPath("~/upload/" + Attachment.folderName + "/image/");
string thumbPath = Server.MapPath("~/upload/" + Attachment.folderName + "/thumb/");
string tempPath = Server.MapPath("~/upload/" + Attachment.folderName + "/temp/");
string filePath = Server.MapPath("~/upload/" + Attachment.folderName + "/file/");
utils.validateFolder(imagePath);
utils.validateFolder(thumbPath);
utils.validateFolder(tempPath);
utils.validateFolder(filePath);
Attachment.sourcePath = ConfigurationManager.AppSettings["WebAddy"];
if (Attachment.typeId == pNums.AttachmentType.Image.GetHashCode())
{
//upload file
e.File.SaveAs(tempPath + Attachment.fileName);
//resize and compress
utils.ResizeImage(tempPath + Attachment.fileName, imagePath, Attachment.fileName, 400, true);
//resize and crop
utils.ResizeCropImagePrecise(imagePath + Attachment.fileName, thumbPath, Attachment.fileName, 383, 264, false);
}
else
{
//upload file
e.File.SaveAs(filePath + Attachment.fileName);
}
if (Attachment.recId > 0)
{
xData.UpdateTyped("recId", Attachment.recId.ToString(), typeof(oAttachment), Attachment);
utils.disposeSession("Attachment");
}
else
{
Attachment.recId = xData.SaveTyped("recId", typeof(oAttachment), Attachment);
if (Attachment.recId > 0)
{ }
}
}
catch (Exception ex)
{
exception.HandleException("Attachments:", MethodBase.GetCurrentMethod().Name, ex, Session["attachment"]);
Response.Redirect("/error", false);
}
}
///
/// Cancel Click
///
///
///
protected void btnCancelNote_Click(object sender, EventArgs e)
{
BindAttachments(this.Event.recId, divfTaskAttachments);
//BindNotes(this.Event.recId, divfTaskNotes);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myfNoteModalClose", "$('.modal-backdrop').remove();$('body').removeClass('modal-open');", true);
}
protected void btnSaveNote_Click(object sender, EventArgs e)
{
try
{
oUser user = new oUser();
string[] userArr = this.Event.users.Split(char.Parse(","));
if (utils.verifySession("user"))
{
user = (oUser)Session["user"];
}
else
{
Response.Redirect("/home", false);
return;
//throw new Exception("Logged on user could not be determined.");
}
//if viewstate is null, no attachment has been linked to this note, and the note hasn't been saved yet, save it now
if (ViewState["newNote"] == null)
{
if (this.Event.recId == 0)
{
if (!SaveEvent())
return;
userArr = this.Event.users.Split(char.Parse(","));
}
int itemId = this.Event.recId;
oNote note = new oNote();
note.caption = radNewNote.Content;
note.dateSaved = System.DateTime.Now;
note.isActive = true;
note.title = user.name + " (" + utils.fixDate(System.DateTime.Now) + ")";
note.userIdSaved = user.recId;
if (chkBillingNote.Checked)
{
note.moduleId = (int)pNums.Module.Calendar;
if (userArr.Length > 0)
{
if (userArr[0] != "")
note.entityId = int.Parse(userArr[0]);
}
else
{
note.entityId = itemId;
}
note.typeId = (int)pNums.NoteType.Billing;
}
else
{
note.moduleId = (int)pNums.Module.Calendar;
note.entityId = itemId;
note.typeId = (int)pNums.NoteType.General;
}
note.recId = xData.SaveTyped("recId", typeof(oNote), note);
}
else
ViewState["newNote"] = null;
BindAttachments(this.Event.recId, divfTaskAttachments);
BindNotes(this.Event.recId, divfTaskNotes, false);
if (userArr.Length > 0)
{
if (userArr[0] != "")
BindNotes(int.Parse(userArr[0]), divfBillingNotes, true);
}
if (handler.GetRoutedData("canvas-title") != "overlay")
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myfNoteModalSave", "$('.modal-backdrop').remove(); $('body').removeClass('modal-open');", true);
}
catch (Exception ex)
{
exception.HandleException("Attachments:", MethodBase.GetCurrentMethod().Name, ex, Session["attachment"]);
Response.Redirect("/error", false);
}
}
#endregion
#region sbf contacts
///
/// SBF Profiles
///
///
///
protected void lnkSBFProfiles_Click(object sender, EventArgs e)
{
if (this.Event.recId == 0)
{
if (!SaveEvent())
return;
}
PersistEvent();
BindSurfaces();
upRecipient.Update();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "showRecipientModal", "$('#modRecipient').modal('show');", true);
}
///
/// bind surfaces
///
private void BindSurfaces()
{
try
{
DataTable apps = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oSurface), "isActive", "1", "surface");
if (handler.ReturnSetup().code == "STUD-1")
{
ArrayList allowedSurfaces = new ArrayList();
allowedSurfaces.Add("Profiles");
//allowedSurfaces.Add("DetailsofPrimaryCaregivers");
DataTable sourceSurface = apps.AsEnumerable()
.Where(r => allowedSurfaces.Contains(r.Field
("name")))
.CopyToDataTable();
ddRecipientSurface.DataSource = sourceSurface;
}
else
ddRecipientSurface.DataSource = apps;
ddRecipientSurface.DataTextField = "surface";
ddRecipientSurface.DataValueField = "recId";
ddRecipientSurface.DataBind();
ddRecipientSurface.Items.Insert(0, new ListItem("select...", "0"));
foreach (oCalendarEventModule evntModule in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEventModule), "calendarId", CalendarId.ToString()))
{
if (ddRecipientSurface.Items.FindByValue(evntModule.entityId.ToString()) != null)
{
ddRecipientSurface.Items.FindByValue(evntModule.entityId.ToString()).Selected = true;
ddRecipientSurface_SelectedIndexChanged(null, null);
}
}
}
catch (Exception ex)
{
exception.HandleException("events:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// surface change
///
///
///
protected void ddRecipientSurface_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
PersistEvent();
if (ddRecipientSurface.SelectedValue != null)
{
DataTable numberFields = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oSurfaceField), "isActive,validationType,surfaceId", "1," + ((int)pNums.ValidationType.ContactNumber).ToString() + "," + ddRecipientSurface.SelectedValue.ToString(), "surfaceFieldName");
foreach (oSurfaceField labelFields in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceField), "isActive,surfaceFieldTypeId,surfaceId", "1,29," + ddRecipientSurface.SelectedValue.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);
}
}
ddRecipientNumber.DataSource = numberFields;
ddRecipientNumber.DataTextField = "surfaceFieldDisplay";
ddRecipientNumber.DataValueField = "recId";
ddRecipientNumber.DataBind();
ddRecipientNumber.Items.Insert(0, new ListItem("select...", "0"));
DataTable nameFields = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oSurfaceField), "isActive,surfaceFieldTypeId,surfaceId,surfaceFieldName", "1,~()3|29," + ddRecipientSurface.SelectedValue.ToString() + ",~%name", "surfaceFieldName");
ddRecipientName.DataSource = nameFields;
ddRecipientName.DataTextField = "surfaceFieldDisplay";
ddRecipientName.DataValueField = "recId";
ddRecipientName.DataBind();
ddRecipientName.Items.Insert(0, new ListItem("select...", "0"));
int schoolLookupCatId = 0;
foreach (oSurfaceLookupCategory cat in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceLookupCategory), "lookupCategory,isActive", "Schools,1"))
{
schoolLookupCatId = cat.recId;
}
DataTable dtSchoolValues = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oSurfaceLookup), "categoryId,isActive", schoolLookupCatId.ToString() + ",1", "sequence");
lstRecipientFilterSchool.DataSource = dtSchoolValues;
lstRecipientFilterSchool.DataTextField = "display";
lstRecipientFilterSchool.DataValueField = "display";
lstRecipientFilterSchool.DataBind();
lstRecipientFilterIntakeYear.Items.Clear();
for (int i = 2010; i <= DateTime.Now.Year; i++)
{
string display = i.ToString();
if (i == DateTime.Now.Year - 4)
display = i.ToString() + " (Grade 8)";
if (i == DateTime.Now.Year - 3)
display = i.ToString() + " (Grade 9)";
if (i == DateTime.Now.Year - 2)
display = i.ToString() + " (Grade 10)";
if (i == DateTime.Now.Year - 1)
display = i.ToString() + " (Grade 11)";
if (i == DateTime.Now.Year)
display = i.ToString() + " (Grade 12)";
lstRecipientFilterIntakeYear.Items.Add(new ListItem(display, i.ToString()));
}
foreach (oCalendarEventModule evntModule in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEventModule), "calendarId", CalendarId.ToString()))
{
if (ddRecipientNumber.Items.FindByValue(evntModule.entityMobileField.ToString()) != null)
ddRecipientNumber.Items.FindByValue(evntModule.entityMobileField.ToString()).Selected = true;
if (ddRecipientName.Items.FindByValue(evntModule.entityNameField.ToString()) != null)
ddRecipientName.Items.FindByValue(evntModule.entityNameField.ToString()).Selected = true;
int filterIndex = 0;
foreach (string fieldType in this.Event.filterValue.Split('|'))
{
foreach (string fields in fieldType.Split(','))
{
switch (filterIndex)
{
case 0://school
if (lstRecipientFilterSchool.Items.FindByValue(fields.Replace("'", "")) != null)
{
lstRecipientFilterSchool.Items.FindByValue(fields.Replace("'", "")).Selected = true;
}
break;
case 1://intake year
if (lstRecipientFilterIntakeYear.Items.FindByValue(fields.Replace("'", "")) != null)
{
lstRecipientFilterIntakeYear.Items.FindByValue(fields.Replace("'", "")).Selected = true;
}
break;
default:
break;
}
}
filterIndex++;
}
GenerateRecipients(true);
}
}
}
catch (Exception ex)
{
exception.HandleException("events:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// Generate Recipient List
///
///
private void GenerateRecipients(bool clearExisting = true)
{
try
{
int surfaceId = Convert.ToInt32(ddRecipientSurface.SelectedValue.ToString());
string filterField = string.Empty;
string filterValues = string.Empty;
string filter = string.Empty;
filterField = "School|IntakeYear";
string schoolValues = string.Empty;
string intakeYearValues = string.Empty;
foreach (ListItem item in lstRecipientFilterSchool.Items.GetSelectedItems())
{
if (item.Selected)
{
if (schoolValues != string.Empty)
schoolValues += ",'" + item.Value.Replace("'","''").ToString() + "'";
else
schoolValues += "'" + item.Value.Replace("'", "''").ToString() + "'";
}
}
foreach (ListItem item in lstRecipientFilterIntakeYear.Items.GetSelectedItems())
{
if (item.Selected)
{
if (intakeYearValues != string.Empty)
intakeYearValues += ",'" + item.Value.ToString() + "'";
else
intakeYearValues += "'" + item.Value.ToString() + "'";
}
}
filterValues = schoolValues + "|" + intakeYearValues;
if (schoolValues != string.Empty)
{
if (filter != string.Empty)
filter += " AND ";
filter += "ProfileHeader_School IN (" + schoolValues + ")";
}
if (intakeYearValues != string.Empty)
{
if (filter != string.Empty)
filter += " AND ";
filter += "ProfileHeader_IntakeYear IN (" + intakeYearValues + ")";
}
if (surfaceId > 0 && ddRecipientName.SelectedValue.ToString() != "0" && ddRecipientNumber.SelectedValue.ToString() != "0")
{
int totalRows = xData.GetSurfaceQueryDataCount(surfaceId, 0, "", filter);
string recipName = string.Empty;
string recipNumber = string.Empty;
foreach (oSurfaceField field in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceField), "recId", ddRecipientName.SelectedValue.ToString()))
{
recipName = field.surfaceFieldName;
}
foreach (oSurfaceField field in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceField), "recId", ddRecipientNumber.SelectedValue.ToString()))
{
recipNumber = field.surfaceFieldName;
}
foreach (oCalendarEventModule evntModule in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEventModule), "calendarId", CalendarId.ToString()))
{
evntModule.entityId = surfaceId;
evntModule.entityMobileField = Convert.ToInt32(ddRecipientNumber.SelectedValue.ToString());
evntModule.entityNameField = Convert.ToInt32(ddRecipientName.SelectedValue.ToString());
this.Event.filterField = filterField;
this.Event.filterValue = filterValues;
xData.UpdateTyped("recId", evntModule.recId.ToString(), typeof(oCalendarEventModule), evntModule);
DataTable dtRecipients = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oCalendarEventContact), "calendarEventId,isIncluded", evntModule.recId.ToString() + ",1");
DataTable dtGenerated = xData.GetSurfaceQueryDataPaged(surfaceId, 0, totalRows, "", "", handler.ReturnUser().recId, 0, filter, true);
DataView view = new DataView(dtGenerated);
DataTable dtRec = view.ToTable("Recipients", false, recipName, recipNumber, "itemID");
foreach (DataRow row in dtRec.Rows)
{
DataRow newRecipientRow = dtRecipients.NewRow();
newRecipientRow["calendarEventId"] = evntModule.recId.ToString();
newRecipientRow["recipientName"] = row[recipName].ToString();
newRecipientRow["recipientNumber"] = row[recipNumber].ToString();
newRecipientRow["contactSurfaceItemId"] = Convert.ToInt32(row["itemID"].ToString());
newRecipientRow["isIncluded"] = false;
newRecipientRow["recId"] = 0;
var dr = from r in dtRecipients.AsEnumerable()
where r.Field("contactSurfaceItemId") == Convert.ToInt32(newRecipientRow["contactSurfaceItemId"].ToString())
select r;
if (dr.AsDataView().Count == 0)
dtRecipients.Rows.Add(newRecipientRow);
}
Session["dtRecipient"] = dtRecipients;
grdRecipients.DataSource = dtRecipients;
grdRecipients.DataBind();
lblRecipientIncludedCount.Text = "Recipient Count: " + RecipientCount.ToString();
btnRecipientSave.Visible = RecipientCount > 0;
upRecipient.Update();
}
}
}
catch (Exception ex)
{
exception.HandleException("events:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// btn generate click
///
///
///
protected void btnGenerate_Click(object sender, EventArgs e)
{
PersistEvent();
GenerateRecipients();
}
///
/// recipient save
///
///
///
protected void btnRecipientSave_Click(object sender, EventArgs e)
{
try
{
PersistEvent();
ArrayList currentList = new ArrayList();
ArrayList newList = new ArrayList();
currentList = xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEventContact), "calendarEventId,isIncluded", Event.recId.ToString() + ",1");
if (currentList.Count > 0)
{
foreach (oCalendarEventContact item in currentList)
{
item.isIncluded = false;
}
xData.UpdateTypedCollection("recId", typeof(oCalendarEventContact), currentList);
}
DataTable dtRecipients = (DataTable)Session["dtRecipient"];
foreach (DataRow row in dtRecipients.Rows)
{
if (row["isIncluded"].ToString() == "True")
{
oCalendarEventContact eventRecipient = new oCalendarEventContact();
eventRecipient.calendarEventId = Event.recId;
eventRecipient.recipientName = row["recipientName"].ToString();
eventRecipient.recipientNumber = row["recipientNumber"].ToString();
eventRecipient.isIncluded = true;
eventRecipient.contactSurfaceItemId = Convert.ToInt32(row["contactSurfaceItemId"].ToString());
newList.Add(eventRecipient);
}
}
xData.UpdateTypedCollection("recId", typeof(oCalendarEventContact), newList);
foreach (oCalendarEventContact contact in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendarEventContact), "calendarEventId,isIncluded", Event.recId.ToString() + ",1"))
{
pnlSBFComms.Visible = true;
break;
}
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "showRecipientModal", "$('#modRecipient').modal('hide');", true);
}
catch (Exception ex)
{
exception.HandleException("events:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// include all click
///
///
///
protected void lnkIncludeAll_Click(object sender, EventArgs e)
{
try
{
PersistEvent();
LinkButton lnkIncludeAll = (LinkButton)sender;
DataTable dtRecipients = (DataTable)Session["dtRecipient"];
if (IncludeAll)
{
IncludeAll = false;
foreach (DataRow row in dtRecipients.Rows)
{
row["isIncluded"] = false;
}
}
else
{
IncludeAll = true;
foreach (DataRow row in dtRecipients.Rows)
{
row["isIncluded"] = true;
}
}
Session["dtRecipient"] = dtRecipients;
grdRecipients.DataSource = dtRecipients;
grdRecipients.DataBind();
lnkIncludeAll.Text = IncludeAll ? "exclude all" : "include all";
lblRecipientIncludedCount.Text = "Recipient Count: " + RecipientCount.ToString();
btnRecipientSave.Visible = RecipientCount > 0;
upRecipient.Update();
}
catch (Exception ex)
{
exception.HandleException("events:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// recipient prerender
///
///
///
protected void rptRecipient_PreRender(object sender, EventArgs e)
{
Repeater rptRecipient = (Repeater)sender;
LinkButton lnkIncludeAll = (LinkButton)rptRecipient.Controls[0].Controls[0].FindControl("lnkIncludeAll");
lnkIncludeAll.Text = IncludeAll ? "exclude all" : "include all";
}
///
/// recipient item created
///
///
///
protected void rptRecipient_ItemCreated(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Header)
{
LinkButton lnkIncludeAll = (LinkButton)e.Item.FindControl("lnkIncludeAll");
lnkIncludeAll.Text = IncludeAll ? "exclude all" : "include all";
}
}
///
/// check included
///
///
///
protected void chkIncluded_CheckedChanged(object sender, EventArgs e)
{
try
{
PersistEvent();
int selRowIndex = ((GridViewRow)(((CheckBox)sender).Parent.Parent)).RowIndex;
CheckBox cb = (CheckBox)grdRecipients.Rows[selRowIndex].FindControl("chkIncluded");
Label lblId = (Label)grdRecipients.Rows[selRowIndex].FindControl("lblId");
Label lblName = (Label)grdRecipients.Rows[selRowIndex].FindControl("lblName");
Label lblNumber = (Label)grdRecipients.Rows[selRowIndex].FindControl("lblNumber");
DataTable dtRecipients = (DataTable)Session["dtRecipient"];
DataRow[] foundRows = dtRecipients.Select("recId = " + lblId.Text + "AND recipientName = '" + lblName.Text + "' AND recipientNumber = '" + lblNumber.Text + "'");
foundRows[0]["isIncluded"] = cb.Checked;
Session["dtRecipient"] = dtRecipients;
grdRecipients.DataSource = dtRecipients;
//grdRecipients.DataBind();
lblRecipientIncludedCount.Text = "Recipient Count: " + RecipientCount.ToString();
btnRecipientSave.Visible = RecipientCount > 0;
upRecipient.Update();
}
catch (Exception ex)
{
exception.HandleException("events:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
///
/// grid recipients prerender
///
///
///
protected void grdRecipients_PreRender(object sender, EventArgs e)
{
//PersistEvent();
if (grdRecipients.Rows.Count > 0)
{
LinkButton lnkIncludeAll = (LinkButton)grdRecipients.Controls[0].Controls[0].FindControl("lnkIncludeAll");
lnkIncludeAll.Text = IncludeAll ? "exclude all" : "include all";
}
}
///
/// grid recipients rowcreated
///
///
///
protected void grdRecipients_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.TableSection = TableRowSection.TableHeader;
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.TableSection = TableRowSection.TableBody;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.TableSection = TableRowSection.TableFooter;
}
}
#endregion
#region Properties
///
/// Include All Property
///
public bool IncludeAll
{
get
{
if (ViewState["includeAll"] == null)
return false;
else
return (bool)ViewState["includeAll"];
}
set
{
ViewState["includeAll"] = value;
}
}
///
/// Calc Recipient Count
///
public int RecipientCount
{
get
{
int counter = 0;
DataTable dtRecipients = (DataTable)Session["dtRecipient"];
foreach (DataRow row in dtRecipients.Rows)
{
if (row["isIncluded"].ToString() == "True")
{
counter++;
}
}
return counter;
}
}
#endregion
protected void lnkCommunication_Click(object sender, EventArgs e)
{
try
{
PersistEvent();
Session["eventToCampaigns"] = this.Event;
Response.Redirect("/pages/communication", false);
}
catch (Exception ex)
{
exception.HandleException("events:", MethodBase.GetCurrentMethod().Name, ex, 0);
Response.Redirect("/error", false);
}
}
}