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 static bool ApproveRequest(string requestid)
        {
            if (HttpContext.Current.Session["CurrentSPContext"] != null)
            {
                TimeOffRequests obj = new TimeOffRequests();
                obj.RequestID = requestid;
                obj= obj.GetRequestDetailByRequestID(HttpContext.Current.Session["CurrentSPContext"] as SharePointContext);

                 UserClass objUser = new UserClass();
                 User CurrentUser = objUser.GetCurrentUserByApp(HttpContext.Current.Session["CurrentSPContext"] as SharePointContext);


                 int NumberofApprovers = 0, noOfApprovals = 0;
                 if (obj.Approver1 != "")
                     NumberofApprovers = 1;
                 if (obj.Approver2 != "")
                     NumberofApprovers = 2;
                 if (obj.Approver3 != "")
                     NumberofApprovers = 3;

                 if (obj.Approver1Status == "Approved")
                     noOfApprovals = 1;
                 if (obj.Approver2 != "Approved")
                     noOfApprovals = 2;
                 if (obj.Approver3 != "Approved")
                     noOfApprovals = 3;

                 bool sendCal = false;
                
                if(NumberofApprovers==1 && obj.Approver1Status == "Pending Approval" && obj.Approver1 == CurrentUser.LoginName)
                  {
                      obj.Approver1Status = "Approved";
                      obj.Status = "Approved";
                      sendCal = true;
                  }
               

                if (NumberofApprovers == 2 && obj.Approver1Status == "Approved" && obj.Approver2Status == "Pending Approval" && obj.Approver2 == CurrentUser.LoginName)
                {
                    obj.Approver2Status = "Approved";
                    obj.Status = "Approved";
                    sendCal = true;
                }

                if (NumberofApprovers == 3 && obj.Approver2Status == "Approved" && obj.Approver3Status == "Pending Approval" && obj.Approver3 == CurrentUser.LoginName)
                {
                    obj.Approver3Status = "Approved";
                    obj.Status = "Approved";
                    sendCal = true;
                }

                switch (noOfApprovals)
                {
                    case 0:
                        {
                            obj.Approver1Status = "Approved";
                            break;
                        }
                    case 1:
                        {
                            obj.Approver2Status = "Approved";
                            break;
                        }
                    case 3:
                        {
                            obj.Approver3Status = "Approved";
                            obj.Status = "Approved";
                            break;
                        }
                }
                bool updateResult=obj.UpdateRequest();



                if(sendCal)
                {
                    try
                    {
                        DeptCalListClass objDept = new DeptCalListClass();
                        objDept.AddDeptCal(null, obj.RequestedBy+ "-" + obj.TimeOffType, obj.StartDate.ToString(), obj.EndDate.ToString());
                    }
                    catch
                    { }
                }
              

            }
            return false;//TODO
        }