public void IsMember(User CurrentUser)
 {
     string siteApproverGroupname = Config.TimeOffApprovers;
     ConfigListValues objConfigAppList = new ConfigListValues();
     objConfigAppList.GetConfigValues(null);
     if (objConfigAppList.items != null)
     {
         if (objConfigAppList.items.ContainsKey("TimeOffApprovers"))
             siteApproverGroupname = objConfigAppList.items["TimeOffApprovers"].ToString();
     }
     GroupsClass objTOR = new GroupsClass();
     IsGroupMember = objTOR.IsCurrentUserExistInGroup(siteApproverGroupname, CurrentUser.LoginName);
 }
        public static string CancelRequest(string requestid, string startdate, string enddate, string status)
        {
            if (HttpContext.Current.Session["CurrentSPContext"] != null)
            {
                TimeOffRequests obj = new TimeOffRequests();
                obj.RequestID = requestid;
                obj.StartDate = DateTime.Parse(startdate);
                obj.EndDate = DateTime.Parse(enddate);
                if (status == "Pending Approval")
                {
                    if (obj.CancelRequest(HttpContext.Current.Session["CurrentSPContext"] as SharePointContext, status))                   
                    {
                        //TO DO cancellation email to approver
                        return "Your request has been successfully cancelled.";
                    }
                    else
                        return "Could not able to cancel the request.";
                }
                else
                    if (status == "Approved")
                    {
                        string CancelLeaveDay = Config.CancelLeaveDay;
                        ConfigListValues objConfigAppList = new ConfigListValues();
                        objConfigAppList.GetConfigValues(HttpContext.Current.Session["CurrentSPContext"] as SharePointContext);

                        if (objConfigAppList.items != null)
                        {
                            if (objConfigAppList.items["CancelLeaveDay"] != null)
                            { CancelLeaveDay = objConfigAppList.items["CancelLeaveDay"].ToString(); }
                        }
                        DateTime dtNew = DateTime.Now.AddDays(Convert.ToInt32(CancelLeaveDay));
                        if (obj.StartDate > dtNew)
                        {

                            if (obj.CancelRequest(HttpContext.Current.Session["CurrentSPContext"] as SharePointContext, status))
                            //if (obj.CancelRequest(status))
                            {
                                return "Your request has been successfully submitted for Cancellation. Approver has to review.";
                            }
                        }
                        else
                            return "You can cancel the request only which are requested after " + dtNew.ToShortDateString();
                    }
                return "";
            }
            return "";
        }
 public void LoadNotesToolTip()
 {
     ConfigListValues objConfigAppList = new ConfigListValues();
     string NotesToolTip="";
     objConfigAppList.GetConfigValues(null);
     if (objConfigAppList.items != null)
     {
         
         if (objConfigAppList.items.ContainsKey("NotesToolTip"))
             NotesToolTip = objConfigAppList.items["NotesToolTip"].ToString();
     }
     if (NotesToolTip == null || NotesToolTip == "")
     {
         NotesToolTip = Config.NotesToolTip;
     }
   
     this.txtNotes.ToolTip = NotesToolTip;
     this.lblnotesHint.InnerText = NotesToolTip;
 }
        public void VerifyApprover()
        {
            GroupsClass objTOR = new GroupsClass();
            if (Request.QueryString[Config.ListURL] != null)
                sharepointUrl = new Uri(Request.QueryString[Config.ListURL]);

            string siteApproverGroupname = Config.TimeOffApprovers;//default from web.config

            //Get from App Config (custom)
            ConfigListValues objConfigAppList = new ConfigListValues();
            objConfigAppList.GetConfigValues(null);
            if (objConfigAppList.items != null)
            {
                if (objConfigAppList.items[Config.TimeOffApprovers] != null)
                    siteApproverGroupname = objConfigAppList.items[Config.TimeOffApprovers].ToString();
            }

            UserClass objUser = new UserClass();
            string strCurrentUserTitle = objUser.GetCurrentUserByApp().LoginName;
            if (!objTOR.IsCurrentUserExistInGroup( siteApproverGroupname, strCurrentUserTitle))
            {
                lblerrmsg.Text = " You do not have Access Permission";
            }
            else
            {
                string deptCalName = Config.DepartmentCalendar;//default from web.config
                //Get from App Config (custom)
                ConfigListValues objConfAppList = new ConfigListValues();
                objConfAppList.GetConfigValues(null);
                if (objConfAppList.items != null)
                {
                    if (objConfAppList.items[deptCalName] != null)
                    {
                        deptCalName = objConfAppList.items[deptCalName].ToString();
                    }
                }
                Response.Redirect(Request.QueryString["SPHostUrl"] + "/_layouts/15/start.aspx#/Lists/" + deptCalName, false);
            }
        }
 private void RetrieveApprovers()
 {
     GroupsClass objGrp = new GroupsClass();
      string siteApproverGroupname = Config.TimeOffApprovers;
      ConfigListValues objConfigAppList = new ConfigListValues();
     objConfigAppList.GetConfigValues(null);
     if (objConfigAppList.items != null)
     {
         if (objConfigAppList.items.ContainsKey("TimeOffApprovers"))
             siteApproverGroupname = objConfigAppList.items["TimeOffApprovers"].ToString();
     }
     UserCollection approvers= objGrp.GetUserList(siteApproverGroupname);
     ddApprover1.Items.Clear();
     ddApprover2.Items.Clear();
     ddApprover3.Items.Clear();
     ddApprover1.Items.Add("- Select -");
     ddApprover2.Items.Add("- Select -");
     ddApprover3.Items.Add("- Select -");
     foreach (User member in approvers)
     {
         ddApprover1.Items.Add(new System.Web.UI.WebControls.ListItem(member.Title, member.LoginName));
         ddApprover2.Items.Add(new System.Web.UI.WebControls.ListItem(member.Title, member.LoginName));
         ddApprover3.Items.Add(new System.Web.UI.WebControls.ListItem(member.Title, member.LoginName));
     }
 }
        private bool CreateNewTimeOffRequest(string accessToken)
        {
         
            lblerrmsg.Text = "";
            int offHrs = 0;
            string qs;
            string uipage;
            try
            {
                DateTime starttime = Convert.ToDateTime(ddlsrttime.SelectedItem.Text);
                DateTime endtime = Convert.ToDateTime(ddlendtime.SelectedItem.Text);
                TimeSpan diff = DateTime.Now.Subtract(starttime);
                UserClass objUser = new UserClass();         
                if (CurrentUser == null)
                    LoadUserProfile();
                if (diff.Days < 0)
                {
                    lblerrmsg.Text = "* Dates are referenced to past dates, please submit to current or future dates.";
                    return false;
                }
                if (this.rbPartial.Checked)
                {
                    if (this.txtEndDate.Text.Equals(this.txtStartDate.Text))
                    {
                        offHrs = totalhours(starttime, endtime);
                        if (offHrs <= 0)
                        {
                            lblerrmsg.Text = "* Partial day Off duration is 0 or Time difference is not proper. Please verify and Submit again.";
                            return false;
                        }
                        if (offHrs >= Convert.ToInt32(Config.WorkingHours))
                        {
                            lblerrmsg.Text = "* Partial day Off duration is more/equal to One day Working hours. Please verify";
                            return false;
                        }
                    }
                    else
                    {
                        lblerrmsg.Text = "* Start date and End date has to be same for Partial day TimeOff Request";
                        return false;
                    }
                }
              
                string redirecturl;
                var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext.Current);
                using (var clientContext = spContext.CreateUserClientContextForSPAppWeb())//CreateAppOnlyClientContextForSPAppWeb
                {                   
                    try
                    {
                        Web web = clientContext.Web;                       
                   
                        clientContext.Load(web);
                        clientContext.ExecuteQuery();
                        clientContext.Load(web.CurrentUser);    //Get the current user
                        clientContext.ExecuteQuery();
                        List timeOffRequestList = clientContext.Web.Lists.GetByTitle("TimeOffRequests");                       
                        clientContext.Load(timeOffRequestList.Fields);// resolving Notes and Notes1 problem
                        clientContext.ExecuteQuery();

                        ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                        Microsoft.SharePoint.Client.ListItem newTimeOff = timeOffRequestList.AddItem(itemCreateInfo);
                        newTimeOff["TimeOffType"] = ddTimeoffType.SelectedItem.Text;
                        newTimeOff["RequestedBy"] = web.CurrentUser;
                        newTimeOff["IsFullDay"] = (rbFullDay.Checked ? 1 : 0);
                        newTimeOff["StartDateTime"] = DateTime.Parse(txtStartDate.Text + " 12:00:00 AM");
                        newTimeOff["EndDateTime"] = DateTime.Parse(txtEndDate.Text + " 12:00:00 PM");
                        newTimeOff["ExcludeWeekends"] = (rbExcludeWeekendYes.Checked ? 1 : 0);
                        newTimeOff["ExcludeHolidays"] = (rbExcludeHolidayYes.Checked ? 1 : 0);
                        newTimeOff["ExcludeOtherDays"] = (rbExcludeOtherYes.Checked ? 1 : 0); ;
                        newTimeOff["HasAlternateContact"] = (chkAlternateContact.Checked ? 1 : 0); ;
                        newTimeOff["IsAccessible"] = (chkAccessible.Checked ? 1 : 0); ;
                        newTimeOff["IsPrivate"] = (chkPrivate.Checked ? 1 : 0); ;                      
                         newTimeOff["Notes"] = this.txtNotes.Text;   
                        Guid objguid = Guid.NewGuid();
                        newTimeOff["RequestID"] = objguid.ToString();                      
                        if (CurrentUser == null)
                            LoadUserProfile();
                        newTimeOff["RequestedByEmail"] = CurrentUser.Email;                          
                        if (this.rbPartial.Checked)
                        {
                            newTimeOff["StartDateTime"] = DateTime.Parse(GetDateTime(txtStartDate.Text, this.ddlsrttime.SelectedItem.Text));//.ToString("MM/dd/yyyy hh:mm:tt").ToString(); //DateTime.Parse(txtStartDate.Text).ToString("MM/dd/yyyy hh:mm:tt") + " " + GetTime(this.ddlsrttime.SelectedItem.Text);//TODO
                            newTimeOff["EndDateTime"] = DateTime.Parse(GetDateTime(this.txtEndDate.Text, this.ddlendtime.SelectedItem.Text)); //DateTime.Parse(txtEndDate.Text).ToString("MM/dd/yyyy") + " " + GetTime(this.ddlendtime.SelectedItem.Text);//TODO
                            int hrs = DaysIgnoreWeekendsHoliday(ParseDate(this.txtStartDate.Text), ParseDate(this.txtEndDate.Text), Convert.ToInt32(Config.WorkingHours), accessToken);
                            if (hrs == Convert.ToInt32(Config.WorkingHours))
                                newTimeOff["TotalHours"] = offHrs;
                            else
                                newTimeOff["TotalHours"] = 0;
                        }
                        else
                            newTimeOff["TotalHours"] = DaysIgnoreWeekendsHoliday(ParseDate(this.txtStartDate.Text), ParseDate(this.txtEndDate.Text), Convert.ToInt32(Config.WorkingHours), accessToken);

                        TimeOffRequests objTOR = new TimeOffRequests();
                        if (CurrentUser == null)
                            LoadUserProfile();
                        if (objTOR.IsDuplicateExists(CurrentUser.Id, DateTime.Parse(newTimeOff["StartDateTime"].ToString()), DateTime.Parse(newTimeOff["EndDateTime"].ToString())))
                        {
                            lblerrmsg.Text = "* Another request for same date(s) has been requested. We cant create a new request for same date(s).";
                            return false;
                        }    
                        
                        if ((bool)listTimeoffTypes[ddTimeoffType.SelectedItem.Text]) //Save the Status
                            newTimeOff["Status"] = "Pending Approval";
                        else
                            newTimeOff["Status"] = "Approved";
                        if (ddApprover1.SelectedItem.Value != "- Select -")   //Get approvers
                        {
                            Microsoft.SharePoint.Client.User user = clientContext.Web.SiteUsers.GetByLoginName(ddApprover1.SelectedItem.Value);
                            newTimeOff["Approver1"] = user;
                            newTimeOff["Approver1Status"] = "Pending Approval";
                        }
                        if (ddApprover2.SelectedItem.Value != "- Select -")
                        {
                            Microsoft.SharePoint.Client.User user2 = clientContext.Web.SiteUsers.GetByLoginName(ddApprover2.SelectedItem.Value);
                            newTimeOff["Approver2"] = user2;
                            newTimeOff["Approver2Status"] = "Pending Approval";
                        }
                        if (ddApprover3.SelectedItem.Value != "- Select -")
                        {
                            Microsoft.SharePoint.Client.User user3 = clientContext.Web.SiteUsers.GetByLoginName(ddApprover3.SelectedItem.Value);
                            newTimeOff["Approver3"] = user3;
                            newTimeOff["Approver3Status"] = "Pending Approval";
                        }
                        if (this.ddApprover1.SelectedIndex == 0 && this.ddApprover2.SelectedIndex == 0 && this.ddApprover3.SelectedIndex == 0)
                        {
                            newTimeOff["Status"] = "Approved";
                            string msg = "TimeOff Request of " + this.ddTimeoffType.SelectedItem.Text + ": on " + this.txtStartDate.Text + " to " + this.txtEndDate.Text + " has been Approved";
                            if (this.rbFullDay.Checked)
                            {
                                this.txtStartDate.Text += " 12:00 AM";
                                this.txtEndDate.Text += " 12:00 PM";
                            }
                            else
                            {
                                this.txtStartDate.Text += " " + ParseDDLTime(this.ddlsrttime.SelectedItem.Text);
                                this.txtEndDate.Text += " " + ParseDDLTime(this.ddlendtime.SelectedItem.Text);
                            }                           
                        
                            string reqEmail = "";
                            if (CurrentUser == null)
                                LoadUserProfile();
                            reqEmail = CurrentUser.Email;
                        
                            string[] reqdAtten = { reqEmail };
                            string[] optAtten = { };
                            //TODO DeptCalendarList
                            // newTimeOff["ApproverUrl"] = redirecturl;
                            newTimeOff["RequestedByEmail"] = reqEmail;
                            qs = "&redirect_uri=https://" + Request.Url.Authority;
                            redirecturl = Request.QueryString["SPHostUrl"] + "/_layouts/15/appredirect.aspx?client_id=" + Config.ClientId
                                                 + qs + "/Pages/ApprovalForm.aspx" + Server.UrlEncode(Request.Url.Query.ToString() + "&RequestID=" + objguid.ToString());

                            newTimeOff["ApproverUrl"] = redirecturl;
                            newTimeOff.Update();
                            clientContext.ExecuteQuery();

                            string UserID = Config.SenderEmail;//default from web.config
                            string UserPassword = Config.SenderPassword;
                            string WorkingHours = Config.WorkingHours;
                            //Get UserID, UserPassword App Config (custom)
                            ConfigListValues objConfigAppList = new ConfigListValues();
                            objConfigAppList.GetConfigValues(null);
                            if (objConfigAppList.items != null)
                            {
                                if (objConfigAppList.items.ContainsKey("SenderEmail"))
                                    UserID = objConfigAppList.items["SenderEmail"].ToString();
                                if (objConfigAppList.items.ContainsKey("SenderPassword"))
                                    UserPassword = objConfigAppList.items["SenderPassword"].ToString();
                                if (objConfigAppList.items.ContainsKey("WorkingHours"))
                                    UserPassword = objConfigAppList.items["WorkingHours"].ToString();
                            }
                            EWSClass objEWS = new EWSClass();
                            objEWS.SetupCalendarEvent(msg, this.txtStartDate.Text, this.txtEndDate.Text, reqdAtten, optAtten, UserID, UserPassword, WorkingHours);
                            try
                            {       
                            DeptCalListClass objDept = new DeptCalListClass();                                  
                            objDept.AddDeptCal(null, this.lblCurrentUser.Text + "-" + this.ddTimeoffType.SelectedItem.Text, newTimeOff["StartDateTime"].ToString(), newTimeOff["EndDateTime"].ToString());                                                     
                            } catch {}
                            qs = "&redirect_uri=https://" + Request.Url.Authority;//+ "/Pages/ApprovalForm.aspx" + Server.UrlEncode(Request.Url.Query.ToString() + "&success=1&RequestID="+objguid.ToString());
                             redirecturl = Request.QueryString["SPHostUrl"] + "/_layouts/15/appredirect.aspx?client_id=" + Config.ClientId
                                                 + qs + "/Pages/ApprovalForm.aspx" + Server.UrlEncode(Request.Url.Query.ToString() + "&RequestID=" + objguid.ToString());

                            uipage = Request.QueryString["SPHostUrl"] + "/_layouts/15/appredirect.aspx?client_id=" + Config.ClientId
                                                + qs + "/Pages/Ui.aspx" + Server.UrlEncode(Request.Url.Query.ToString() + "&success=1");
                            Response.Redirect(uipage,false);
                            return true;
                        }
                      
                        qs = "&redirect_uri=https://" + Request.Url.Authority;//+ "/Pages/ApprovalForm.aspx" + Server.UrlEncode(Request.Url.Query.ToString() + "&success=1&RequestID="+objguid.ToString());
                         redirecturl = Request.QueryString["SPHostUrl"] + "/_layouts/15/appredirect.aspx?client_id=" + Config.ClientId
                                             + qs + "/Pages/ApprovalForm.aspx" + Server.UrlEncode(Request.Url.Query.ToString() + "&RequestID=" + objguid.ToString());

                        uipage = Request.QueryString["SPHostUrl"] + "/_layouts/15/appredirect.aspx?client_id=" + Config.ClientId
                                            + qs + "/Pages/Ui.aspx" + Server.UrlEncode(Request.Url.Query.ToString() + "&success=1");

                        newTimeOff["ApproverUrl"] = redirecturl;                        
                        newTimeOff.Update();
                      //  this.HyperLink1.NavigateUrl = redirecturl;
                        clientContext.ExecuteQuery();
                        Response.Redirect(uipage, false);
                    }
                    catch (Exception ex)
                    {
                        Utility.LogCustomRemoteAppError(clientContext, Global.ProductId, ex.Message);
                        clientContext.ExecuteQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            return true;
        }
        public List<string> GetNoteReqdList()
        {
            List<string> lstTimeOffTypeNotesReqd = new List<string>();
            //TO DO get from ConfigList/ webconfig as default.
            //lstTimeOffTypeNotesReqd.Add("Funeral");
            //lstTimeOffTypeNotesReqd.Add("I will accessible");
            string exceptionTypes =Config.TimeOffTypeExceptionList;
             ConfigListValues objConfigAppList = new ConfigListValues();
            objConfigAppList.GetConfigValues(null);

            if (objConfigAppList.items != null)
            {
                if (objConfigAppList.items.ContainsKey("TimeOffTypeExceptionList"))
                {
                    exceptionTypes = objConfigAppList.items["TimeOffTypeExceptionList"].ToString();
                }
            }
            if (exceptionTypes != null || exceptionTypes != "")
                lstTimeOffTypeNotesReqd = new List<string>(exceptionTypes.Split(','));
            return lstTimeOffTypeNotesReqd;
        }
        public static string DeleteRequest(string requestid, string startdate, string enddate, string requestorname, string type, string status)
        {

            if (HttpContext.Current.Session["CurrentSPContext"] != null)
            {
                TimeOffRequests obj = new TimeOffRequests();
                obj.RequestID = requestid;
                obj.StartDate = DateTime.Parse(startdate);
                obj.EndDate = DateTime.Parse(enddate);
                if (status == "Approved")
                {
                    string CancelLeaveDay = Config.CancelLeaveDay;
                    ConfigListValues objConfigAppList = new ConfigListValues();
                    objConfigAppList.GetConfigValues( HttpContext.Current.Session["CurrentSPContext"] as SharePointContext);
                    if (objConfigAppList.items != null)
                    {
                        if (objConfigAppList.items["CancelLeaveDay"] != null)
                        { CancelLeaveDay = objConfigAppList.items["CancelLeaveDay"].ToString(); }
                    }
                    DateTime dtNew = DateTime.Now.AddDays(Convert.ToInt32(CancelLeaveDay));
                    if (obj.StartDate > dtNew)
                    {
                        if (obj.DeleteRequest(HttpContext.Current.Session["CurrentSPContext"] as SharePointContext,"1"))
                        {
                            string deptCalName = Config.DepartmentCalendar;//default from web.config                        
                            try
                            {
                                ConfigListValues objConfAppList = new ConfigListValues();
                                objConfAppList.GetConfigValues( HttpContext.Current.Session["CurrentSPContext"] as SharePointContext);
                                if (objConfAppList.items != null)
                                {
                                    if (objConfAppList.items["DepartmentCalendar"] != null)
                                    {
                                        deptCalName = objConfAppList.items["DepartmentCalendar"].ToString();
                                    }
                                }
                                DeptCalendar objDept = new DeptCalendar();
                                objDept.Title = requestorname + "-" + type;
                                DateTime startDate = DateTime.Parse(startdate);
                                objDept.EventTime = startDate;
                                objDept.DeleteEvent(deptCalName,HttpContext.Current.Session["CurrentSPContext"] as SharePointContext);
                                return "Request has been cancelled and deleted.";
                            }
                            catch (Exception ex)
                            {
                            }
                            return "Your request has been successfully submitted for Cancellation. Approver has to review.";
                        }
                        else
                            return "Unable to cancel the Approved Request. Please try again.";
                    }
                    else
                        return "You can cancel the request only which are requested after " + dtNew.ToShortDateString();
                }
                else
                    return "Only Approved Requests will be processed.";
            }
            return "";
        }