protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {              
                Session["CurrentSPContext"] = SharePointContextProvider.Current.GetSharePointContext(HttpContext.Current);             
                TimeOffRequests objTOR = new TimeOffRequests();
                List<TimeOffRequests> objTORList = objTOR.GetMyTimeOfRequests("TimeOffRequests");
                foreach (TimeOffRequests temp in objTORList)
                {
                    if (temp.CancelStatus == "Cancel")                 
                        temp.Status = temp.Status + " [Cancellation pending.]";                 
                }               
                if (objTORList.Count > 0)
                {
                    LVreqDetails.DataSource = objTORList;
                    LVreqDetails.DataBind();
                    LVreqDetails.Visible=true;
                    this.dummytable.Visible = false;
                }
                else
                {
                    LVreqDetails.Visible = false;
                    this.dummytable.Visible = true;
                }                
            }
        }      
        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 LoadGridNormal()
 {
     UserClass objUser = new UserClass();
     int intCurrentUserId = objUser.GetCurrentUserByApp().Id;
     string CurrentUserLoginName = objUser.GetCurrentUserByApp().LoginName;
     TimeOffRequests objTOR = new TimeOffRequests();
     List<TimeOffRequests> objTORList = objTOR.GetMyProcessingRequests( intCurrentUserId, CurrentUserLoginName);
     //ProcessDateOnFulldays(ref objTOR);
     if (objTORList.Count > 0)
     {
         lvNormal.DataSource = objTORList;
         lvNormal.DataBind();
         lvNormal.Visible = true;
         this.dummyTable2.Visible = false;
     }
     else
     {
         this.lvNormal.Visible = false;
         this.dummyTable2.Visible = true;
     }                
 }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
           // UpdateStatus(((Button)sender).CommandArgument, "Denied");
           // Response.Redirect("ui.aspx?SPHostUrl=" + Request.QueryString["SPHostUrl"].ToString() + "&approval=1&" + Config.ListURL + "=" + sharepointUrl.ToString());
            //TODO
            //Delete request
            //

             if (sharepointUrl == null)
                sharepointUrl = new Uri(Config.ListURL);
            TimeOffRequests objTimeOffReq = new TimeOffRequests();
            objTimeOffReq.RequestID= Request.QueryString["RequestID"].ToString();
            objTimeOffReq.DeleteRequest(null);
        }
        public void LoadUI(TimeOffRequests objTOR)
        {
            this.lblRequestedBy.Text = objTOR.RequestedBy;
            this.lblRequestedOn.Text = objTOR.RequestedOn;
            this.lblTimeoffType.Text = objTOR.TimeOffType;
            this.lblFullday.Text     = objTOR.isFullDay;
            if (objTOR.isFullDay == "Full Day(s)")
            {
                this.txtStartDate.Text = objTOR.StartDate.Value.ToString("MM/dd/yyyy");
                this.txtEndDate.Text = objTOR.EndDate.Value.ToString("MM/dd/yyyy");
            }
            else
            {              
                this.txtStartDate.Text = objTOR.StartDate.Value.ToString("MM/dd/yyyy hh:mm:ss tt");
                this.txtEndDate.Text = objTOR.EndDate.Value.ToString("MM/dd/yyyy hh:mm:ss tt");
            }
            this.rbExcludeWeekendYes.Checked = objTOR.ExcludeWeekend; 
            this.rbExcludeHolidayYes.Checked = objTOR.ExcludeHoliday;
            this.rbExcludeOtherYes.Checked = objTOR.ExcludeOtherDay;
            this.rbExcludeWeekendNo.Checked = !objTOR.ExcludeWeekend;
            this.rbExcludeHolidayNo.Checked = !objTOR.ExcludeHoliday;
            this.rbExcludeOtherNo.Checked = !objTOR.ExcludeOtherDay;

            this.lblApp1.InnerText = objTOR.Approver1;
            this.lblApp2.InnerText = objTOR.Approver2;
            this.lblApp3.InnerText = objTOR.Approver3;
            this.txtNotes.Text = objTOR.Notes;

            this.chkAccessible.Checked = objTOR.IsAccessible;
            this.chkAlternateContact.Checked = objTOR.Alternate;
            this.chkPrivate.Checked = objTOR.IsPrivate;
        }
        public bool IsConcernedApprover(TimeOffRequests objTOR)
        {
            //GetCurrentuser and check is he among 3 approver
            // validate is he concern approver
            string concernedApprover="";
            UserClass objUser = new UserClass();         
            User CurrentUser= objUser.GetCurrentUserByApp();
            if (objTOR.Approver3 != null || objTOR.Approver3 != "")
                concernedApprover = objTOR.Approver3;
            else if (objTOR.Approver2 != null || objTOR.Approver2 != "")
                 concernedApprover = objTOR.Approver2;
                 else if (objTOR.Approver1 != null || objTOR.Approver1 != "")
                       concernedApprover = objTOR.Approver1;

            if (concernedApprover == "")
                return false;
            else
            {
                if (CurrentUser.Title == objTOR.Approver1)
                    return true;
                else
                    return false;
            }
        }
 public bool IsStatusApproved(TimeOffRequests objTOR)
 {
     return objTOR.CancelStatus == "Approved" ? true : false;
 }
        public List<TimeOffRequests> GetRequestDetailsStatus(SharePointContext spContext,string year, Dictionary<string, CamlPara> FilterParameters = null, DateTime? startdate = null, DateTime? enddate = null)
        {
            Microsoft.SharePoint.Client.ListItemCollection listItems;
            List<TimeOffRequests> listTimeoffReq = new List<TimeOffRequests>();
            List<string> listyear = new List<string>();
          //  using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl, accessToken))
            if (spContext == null)
                spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext.Current);
            using (var clientContext = spContext.CreateAppOnlyClientContextForSPAppWeb())
            {
                try{
                Web web = clientContext.Web;
                ListCollection lists = web.Lists;
                List selectedList = lists.GetByTitle("TimeOffRequests");
                clientContext.Load<ListCollection>(lists); // this lists object is loaded successfully
                clientContext.Load<List>(selectedList);  // this list object is loaded successfully
                clientContext.ExecuteQuery();
                CamlQuery camlQuery = new CamlQuery();
                StringBuilder camlwhere = new StringBuilder();
                //camlwhere.Append("<Where><And>");
                //camlwhere.Append("<And><Geq>");
                //camlwhere.Append("<FieldRef Name='StartDateTime' /><Value Type='DateTime'>" + year + "-01-01 00:00:00</Value>");
                //camlwhere.Append("</Geq>");
                //camlwhere.Append("<Leq>");
                //camlwhere.Append("<FieldRef Name='StartDateTime' /><Value Type='DateTime'>" + year + "-12-31 00:00:00</Value>");
                //camlwhere.Append("</Leq></And>");

                //camlwhere.Append("<Eq>");
                //camlwhere.Append("<FieldRef Name='Status' />");
                //camlwhere.Append("<Value Type='Text'>");
                //camlwhere.Append(FilterParameters["Status"].value);
                //camlwhere.Append("</Value>");
                //camlwhere.Append("</Eq></And>");

                //camlwhere.Append("</Where>");

                camlwhere.Append("<Where>");
                camlwhere.Append("<And>");
                camlwhere.Append("     <And>");
                camlwhere.Append("          <And>");
                if (startdate != null && enddate != null)
                {
                    camlwhere.Append("               <Geq><FieldRef Name='StartDateTime' /><Value Type='DateTime'>" + startdate.Value.Year.ToString() + "-" + startdate.Value.Month.ToString() + "-" + startdate.Value.Day.ToString() + " " + startdate.Value.Hour.ToString() + ":" + startdate.Value.Minute + ":00</Value></Geq>");
                    camlwhere.Append("               <Leq><FieldRef Name='StartDateTime' /><Value Type='DateTime'>" + enddate.Value.Year.ToString() + "-" + enddate.Value.Month.ToString() + "-" + enddate.Value.Day.ToString() + " " + enddate.Value.Hour.ToString() + ":" + enddate.Value.Minute + ":00</Value></Leq>");
                }
                else
                {
                    camlwhere.Append("               <Geq><FieldRef Name='StartDateTime' /><Value Type='DateTime'>" + year + "-01-01 00:00:00</Value></Geq>");
                    camlwhere.Append("               <Leq><FieldRef Name='StartDateTime' /><Value Type='DateTime'>" + year + "-12-31 00:00:00</Value></Leq>");
                }
                camlwhere.Append("         </And>");
                camlwhere.Append("                <Eq> <FieldRef Name='Status' /><Value Type='Text'>"+FilterParameters["Status"].value+"</Value></Eq>");
                camlwhere.Append("      </And>");
                camlwhere.Append("       <Neq><FieldRef Name='CancelStatus' /><Value Type='Text'>Cancel</Value></Neq>");
                camlwhere.Append("</And>");
                camlwhere.Append("</Where>");


                string viewFields = "";// "<ViewFields><FieldRef Name='IsFullDay' /><FieldRef Name='TotalHours' /><FieldRef Name='RequestedBy' /><FieldRef Name='TimeOffType' /><FieldRef Name='Status' /></ViewFields>";
                camlQuery.ViewXml = @"<View><Query>" + camlwhere.ToString() + "</Query>" + viewFields + "</View>";
                listItems = selectedList.GetItems(camlQuery);
                clientContext.Load<Microsoft.SharePoint.Client.ListItemCollection>(listItems);
                clientContext.ExecuteQuery();
                TimeOffRequests objTimeOffRequests;
                foreach (Microsoft.SharePoint.Client.ListItem oListItem in listItems)
                {
                    objTimeOffRequests = new TimeOffRequests();
                    objTimeOffRequests.isFullDay = oListItem["IsFullDay"].ToString() == "True" ? "Full Day" : "Parital day";
                    objTimeOffRequests.TimeOffType = oListItem["TimeOffType"].ToString() == null ? "UnAssigned" : oListItem["TimeOffType"].ToString();
                    objTimeOffRequests.TotalHours = oListItem["TotalHours"].ToString() == null ? 0 : Convert.ToDecimal(oListItem["TotalHours"].ToString());
                    objTimeOffRequests.Status = oListItem["Status"].ToString() == null ? "" : oListItem["Status"].ToString();
                    var arr = oListItem["RequestedBy"] as Microsoft.SharePoint.Client.FieldLookupValue;
                    objTimeOffRequests.RequestedByID = arr == null ? 0 : arr.LookupId;
                    objTimeOffRequests.RequestedBy = arr == null ? "UnAssigned" : arr.LookupValue.ToString();

                    objTimeOffRequests.StartDate = DateTime.Parse(oListItem["StartDateTime"].ToString());
                    objTimeOffRequests.EndDate = DateTime.Parse(oListItem["EndDateTime"].ToString());
                    objTimeOffRequests.IsAccessible = (bool)oListItem["IsAccessible"];
                    objTimeOffRequests.Alternate = (bool)oListItem["HasAlternateContact"];

                    var docType = oListItem["Approver1"] as Microsoft.SharePoint.Client.FieldLookupValue;
                    if (docType != null)
                    {
                        objTimeOffRequests.Approver1 = docType == null ? "UnAssigned" : docType.LookupValue;
                        objTimeOffRequests.Approver1Id = docType == null ? 0 : docType.LookupId;
                    }
                    docType = oListItem["Approver2"] as Microsoft.SharePoint.Client.FieldLookupValue;
                    if (docType != null)
                    {
                        objTimeOffRequests.Approver2 = docType == null ? "UnAssigned" : docType.LookupValue;
                        objTimeOffRequests.Approver2Id = docType == null ? 0 : docType.LookupId;
                    }
                    docType = oListItem["Approver3"] as Microsoft.SharePoint.Client.FieldLookupValue;
                    if (docType != null)
                    {
                        objTimeOffRequests.Approver3 = docType == null ? "UnAssigned" : docType.LookupValue;
                        objTimeOffRequests.Approver3Id = docType == null ? 0 : docType.LookupId;
                    }


                    listTimeoffReq.Add(objTimeOffRequests);
                }
            }
                catch (Exception ex)
                    {
                        Microsoft.SharePoint.Client.Utilities.Utility.LogCustomRemoteAppError(clientContext, Global.ProductId, ex.Message);
                        clientContext.ExecuteQuery();
                        
                    }
            }
            return listTimeoffReq;
        }
        public List<TimeOffRequests> LoadObjectList(Microsoft.SharePoint.Client.ListItemCollection listItems)
        {
            List<TimeOffRequests> objTORList=new List<TimeOffRequests>();
            TimeOffRequests objTOR;

            foreach (Microsoft.SharePoint.Client.ListItem oListItem in listItems)
            {
                objTOR = new TimeOffRequests();
                objTOR.RequestedBy = (oListItem["RequestedBy"] as Microsoft.SharePoint.Client.FieldLookupValue).LookupValue != null ? (oListItem["RequestedBy"] as Microsoft.SharePoint.Client.FieldLookupValue).LookupValue : "";
                objTOR.RequestedOn = oListItem["Created"] != null ? oListItem["Created"].ToString() : "";
                objTOR.TimeOffType = (string)oListItem["TimeOffType"];
                objTOR.isFullDay = (bool)oListItem["IsFullDay"] == true ? "Full Day(s)" : "Partial Day";
                objTOR.StartDate = ((DateTime)oListItem["StartDateTime"]);
                objTOR.EndDate = ((DateTime)oListItem["EndDateTime"]);
                objTOR.Status = oListItem["Status"] != null ? oListItem["Status"].ToString() : "";
                objTOR.ExcludeWeekend = (bool)oListItem["ExcludeWeekends"];
                objTOR.ExcludeHoliday = (bool)oListItem["ExcludeHolidays"];
                objTOR.ExcludeOtherDay = (bool)oListItem["ExcludeOtherDays"];
                objTOR.Approver1 = (oListItem["Approver1"] as Microsoft.SharePoint.Client.FieldLookupValue) != null ? (oListItem["Approver1"] as Microsoft.SharePoint.Client.FieldLookupValue).LookupValue : "";
                objTOR.Approver2 = (oListItem["Approver2"] as Microsoft.SharePoint.Client.FieldLookupValue) != null ? (oListItem["Approver2"] as Microsoft.SharePoint.Client.FieldLookupValue).LookupValue : "";
                objTOR.Approver3 = (oListItem["Approver3"] as Microsoft.SharePoint.Client.FieldLookupValue) != null ? (oListItem["Approver3"] as Microsoft.SharePoint.Client.FieldLookupValue).LookupValue : "";
                objTOR.Approver1Id = (oListItem["Approver1"] as Microsoft.SharePoint.Client.FieldLookupValue) != null ? (oListItem["Approver1"] as Microsoft.SharePoint.Client.FieldLookupValue).LookupId : 0;
                objTOR.Approver2Id = (oListItem["Approver2"] as Microsoft.SharePoint.Client.FieldLookupValue) != null ? (oListItem["Approver2"] as Microsoft.SharePoint.Client.FieldLookupValue).LookupId : 0;
                objTOR.Approver3Id = (oListItem["Approver3"] as Microsoft.SharePoint.Client.FieldLookupValue) != null ? (oListItem["Approver3"] as Microsoft.SharePoint.Client.FieldLookupValue).LookupId : 0;
                objTOR.Approver1Status = oListItem["Approver1Status"] != null ? oListItem["Approver1Status"].ToString() : "";
                objTOR.Approver2Status = oListItem["Approver2Status"] != null ? oListItem["Approver2Status"].ToString() : "";
                objTOR.Approver3Status = oListItem["Approver3Status"] != null ? oListItem["Approver3Status"].ToString() : "";
                objTOR.RequestedByEmail = oListItem["RequestedByEmail"] != null ? oListItem["RequestedByEmail"].ToString() : "";
                objTOR.Alternate = (bool)oListItem["HasAlternateContact"];
                objTOR.IsAccessible = (bool)oListItem["IsAccessible"];
                objTOR.IsPrivate = (bool)oListItem["IsPrivate"];
                objTOR.CancelStatus = (string)oListItem["CancelStatus"];
                objTOR.Notes = oListItem["Notes"] != null ? oListItem["Notes"].ToString() : "";
                objTOR.RequestID = oListItem["RequestID"] != null ? oListItem["RequestID"].ToString() : "";
                objTOR.TotalHours = oListItem["TotalHours"] != null ? Convert.ToDecimal(oListItem["TotalHours"].ToString()) : 0;
                objTORList.Add(objTOR);
            }
            return objTORList;
        }
 public static List<TimeOffRequests> GetDetails(string year, string parameterkey, string parametervalue, string startdate, string enddate, string starttime, string endtime)
 {
     if (HttpContext.Current.Session["CurrentSPContext"] != null)
     {
      
         TimeOffRequests obj = new TimeOffRequests();
         if (startdate.Trim() == "")
             startdate = "01/01/" + year;
         if (enddate.Trim() == "")
             enddate = "12/31/" + year;
         DateTime? startDate;
         startDate = DateTime.Parse(GetDateTimeStatic(startdate, starttime));//DateTime.Parse(startdate.Trim());
         DateTime? endDate;
         endDate = DateTime.Parse(GetDateTimeStatic(enddate, endtime));
         return obj.GetDetails(HttpContext.Current.Session["CurrentSPContext"] as SharePointContext, year, parameterkey, parametervalue, startDate, endDate);
     }
     return new List<TimeOffRequests>();
 }
        public void createAccordianUsingRepeater()
        {
            TimeOffRequests obj = new TimeOffRequests();
            DateTime? startDate = null, endDate = null;
            try
            {
                if (this.txtStartDate.Text.Trim() != "" && this.txtEndDate.Text.Trim() != "")
                {
                    if (this.ddlsrttime.SelectedIndex != 0)
                    {
                        startDate = DateTime.Parse(GetDateTime(txtStartDate.Text, this.ddlsrttime.SelectedItem.Text));
                        endDate = DateTime.Parse(GetDateTime(this.txtEndDate.Text, this.ddlendtime.SelectedItem.Text));
                    }
                    else
                    {
                        startDate = DateTime.Parse(txtStartDate.Text + " 12:00:00 AM");
                        endDate = DateTime.Parse(this.txtEndDate.Text + " 12:00:00 PM");
                    }
                }
            }
            catch { }


            List<string> list = obj.GetDistinctYear(startDate, endDate);
            if (list.Count > 0)
            {
                repAccordian.DataSource = from c in list select new { YEAR = c };
                repAccordian.DataBind();
                this.faqscontainer.Visible = true;
                blankdiv.Visible = false;
            }
            else
            {
                this.faqscontainer.Visible = false;
                blankdiv.Visible = true;
            }
        }
        public void LoadGridCancel()
        {
           
                UserClass objUser = new UserClass();
                int intCurrentUserId = objUser.GetCurrentUserByApp().Id;

                TimeOffRequests objTOR = new TimeOffRequests();
                List<TimeOffRequests> objTORList = objTOR.GetMyCancelAlerts(intCurrentUserId);
                //ProcessDateOnFulldays(ref objTOR);
                if (objTORList.Count > 0)
                {
                    LVreqDetails.DataSource = objTORList;
                    LVreqDetails.DataBind();
                    LVreqDetails.Visible = true;
                    this.dummytable.Visible = false;
                }
                else
                {
                    LVreqDetails.Visible = false;
                    this.dummytable.Visible = false;
                    this.Table2.Visible = false;
                }            
           
        }
        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 "";
        }
        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
        }
        public List<TimeOffRequests> GetMyProcessingRequests( int userid, string userloginname="")
        {
            TimeOffRequests objTOR = new TimeOffRequests();
            Microsoft.SharePoint.Client.ListItemCollection listItems;
           // using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl, accessToken))
            var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext.Current);
            using (var clientContext = spContext.CreateAppOnlyClientContextForSPAppWeb())

            {
                Web web = clientContext.Web;
                ListCollection lists = web.Lists;
                List selectedList = lists.GetByTitle("TimeOffRequests");
                clientContext.Load<ListCollection>(lists); // this lists object is loaded successfully
                clientContext.Load<List>(selectedList);  // this list object is loaded successfully
                clientContext.ExecuteQuery();

                CamlQuery camlQuery = new CamlQuery();
                StringBuilder camlwhere = new StringBuilder();
                //camlwhere.Append("<Where>");
                //camlwhere.Append("<And>");
                //camlwhere.Append("<Eq><FieldRef Name='Approver1' LookupId='TRUE' /><Value Type='int'>" + userid + "</Value></Eq>");
                //camlwhere.Append("<Eq><FieldRef Name='Status'  /><Value Type='Text'>Pending Approval</Value></Eq>");
                //camlwhere.Append("</And>");               
                //camlwhere.Append("</Where>");

                camlwhere.Append("<Where>");
                camlwhere.Append("     <And>");
                camlwhere.Append("              <Or>");
                camlwhere.Append("                  <Or>");
                camlwhere.Append("                     <Eq><FieldRef Name='Approver1' LookupId='TRUE' /><Value Type='int'>" + userid + "</Value></Eq>");
                camlwhere.Append("                     <Eq><FieldRef Name='Approver2' LookupId='TRUE' /><Value Type='int'>" + userid + "</Value></Eq>");
                camlwhere.Append("                  </Or>");
                camlwhere.Append("                     <Eq><FieldRef Name='Approver3' LookupId='TRUE' /><Value Type='int'>" + userid + "</Value></Eq>");
                camlwhere.Append("             </Or>");
                camlwhere.Append("                <Eq><FieldRef Name='Status'  /><Value Type='Text'>Pending Approval</Value></Eq>");
                camlwhere.Append("        </And>");               
                camlwhere.Append("</Where>");
                camlQuery.ViewXml = @"<View><Query>" + camlwhere.ToString() + "</Query></View>";
                listItems = selectedList.GetItems(camlQuery);
                clientContext.Load<Microsoft.SharePoint.Client.ListItemCollection>(listItems);
                clientContext.ExecuteQuery();
                List<TimeOffRequests> objTemp= LoadObjectList(listItems);

                List<TimeOffRequests> objTemp2 = new List<TimeOffRequests>();

                if (userloginname != "")
                {
                    //int i = 0;
                    
                    foreach (var reqItem in objTemp)
                    {
                        //if (  (reqItem.Approver1Id != userid && reqItem.Approver1Status != "Pending Approval") ||
                        //      (reqItem.Approver2Id != userid && reqItem.Approver1Status != "Approved") ||
                        //      (reqItem.Approver3Id != userid && reqItem.Approver2Status != "Approved"))
                        //{
                        //    objTemp.RemoveAt(i);
                        //}
                        //i++;
                        if ((reqItem.Approver1Id == userid && reqItem.Approver1Status == "Pending Approval") ||
                              (reqItem.Approver2Id == userid && reqItem.Approver1Status == "Approved" && reqItem.Approver2Status == "Pending Approval") ||
                              (reqItem.Approver3Id == userid && reqItem.Approver2Status == "Approved" && reqItem.Approver3Status == "Pending Approval"))
                        {
                            objTemp2.Add(reqItem);
                        }

                    }
                    return objTemp2;
                }
                else
                    return objTemp;


            }
        }
        public List<TimeOffRequests> GetMyCancelAlerts( int userid)
        {
            TimeOffRequests objTOR = new TimeOffRequests();
            Microsoft.SharePoint.Client.ListItemCollection listItems;
           // using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl, accessToken))
            var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext.Current);
            using (var clientContext = spContext.CreateAppOnlyClientContextForSPAppWeb())
            {
                try
                {
                    Web web = clientContext.Web;
                    ListCollection lists = web.Lists;
                    List selectedList = lists.GetByTitle("TimeOffRequests");
                    clientContext.Load<ListCollection>(lists); // this lists object is loaded successfully
                    clientContext.Load<List>(selectedList);  // this list object is loaded successfully
                    clientContext.ExecuteQuery();

                    CamlQuery camlQuery = new CamlQuery();
                    StringBuilder camlwhere = new StringBuilder();
                    camlwhere.Append("<Where>");
                    camlwhere.Append("<And>");
                    camlwhere.Append("   <And>");
                    camlwhere.Append("     <Eq><FieldRef Name='Approver1' LookupId='TRUE' /><Value Type='int'>" + userid + "</Value></Eq>");
                    camlwhere.Append("     <Eq><FieldRef Name='Status'  /><Value Type='Text'>Approved</Value></Eq>");
                    camlwhere.Append("   </And>");
                    camlwhere.Append("  <Eq><FieldRef Name='CancelStatus'  /><Value Type='Text'>Cancel</Value></Eq>");
                    camlwhere.Append("</And>");
                    camlwhere.Append("</Where>");
                    camlQuery.ViewXml = @"<View><Query>" + camlwhere.ToString() + "</Query></View>";
                    listItems = selectedList.GetItems(camlQuery);
                    clientContext.Load<Microsoft.SharePoint.Client.ListItemCollection>(listItems);
                    clientContext.ExecuteQuery();
                    return LoadObjectList(listItems);
                }
                catch (Exception ex)
                {
                    Microsoft.SharePoint.Client.Utilities.Utility.LogCustomRemoteAppError(clientContext, Global.ProductId, ex.Message);
                    clientContext.ExecuteQuery();
                    return null;
                }
            }
        }
        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 bool IsDuplicateExists(int userid, DateTime startdate, DateTime endDate)
        {
            TimeOffRequests objTOR = new TimeOffRequests();
            Microsoft.SharePoint.Client.ListItemCollection listItems;
            //using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl, accessToken))

            var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext.Current);
            using (var clientContext = spContext.CreateAppOnlyClientContextForSPAppWeb())
            {
                try
                {
                    Web web = clientContext.Web;
                    ListCollection lists = web.Lists;
                    List selectedList = lists.GetByTitle("TimeOffRequests");
                    clientContext.Load<ListCollection>(lists); // this lists object is loaded successfully
                    clientContext.Load<List>(selectedList);  // this list object is loaded successfully
                    clientContext.ExecuteQuery();

                    CamlQuery camlQuery = new CamlQuery();
                    StringBuilder camlwhere = new StringBuilder();


                    //camlwhere.Append("<Where>");
                    //camlwhere.Append("<And>");
                    //camlwhere.Append("      <And>");
                    //camlwhere.Append("        <Geq><FieldRef Name='StartDateTime' /><Value Type='DateTime'>" + startdate.Year + "-" + startdate.Month + "-" + startdate.Day + " " + startdate.Hour + ":00:00</Value></Geq>");
                    //camlwhere.Append("        <Leq><FieldRef Name='EndDateTime' /><Value Type='DateTime'>" + endDate.Year + "-" + endDate.Month + "-" + endDate.Day + " " + endDate.Hour + ":00:00</Value></Leq>");
                    //camlwhere.Append("       </And>");
                    //camlwhere.Append("   <Eq><FieldRef Name='RequestedBy' LookupId='TRUE' /><Value Type='int'>" + userid + "</Value></Eq>");
                    ////camlwhere.Append("  <Eq><FieldRef Name='IsFullDay' /><Value Type='Integer'>1</Value> </Eq>");                    
                    //camlwhere.Append("</And>");
                    //camlwhere.Append("</Where>");


                    
                       
                    camlwhere.Append("<Where>");
                    camlwhere.Append("<Or>");
                    camlwhere.Append("       <And>"); 
                    camlwhere.Append("               <And>");
                    camlwhere.Append("                  <Geq><FieldRef Name='StartDateTime' /><Value Type='DateTime' >"+startdate.Year+"-"+startdate.Month+"-"+startdate.Day+" 00:00:00</Value></Geq>");
                    camlwhere.Append("                  <Leq><FieldRef Name='EndDateTime' /><Value Type='DateTime' >"+startdate.Year+"-"+startdate.Month+"-"+startdate.Day+" 00:00:00</Value></Leq>");
                    camlwhere.Append("                </And> ");  
                    camlwhere.Append("                <And> ");        
                    camlwhere.Append("                     <Eq><FieldRef Name='IsFullDay' /><Value Type='Integer'>1</Value> </Eq>");
                    camlwhere.Append("                     <Eq><FieldRef Name='RequestedBy' LookupId='TRUE' /><Value Type='int'>" + userid + "</Value></Eq>");
                    camlwhere.Append("                 </And>");
                    camlwhere.Append("       </And>");
                    camlwhere.Append("      <And>"); 
                    camlwhere.Append("               <And>");
                    camlwhere.Append("                          <Geq><FieldRef Name='StartDateTime' /><Value Type='DateTime' IncludeTimeValue='TRUE' >"+startdate.Year+"-"+startdate.Month+"-"+startdate.Day+"T"+startdate.Hour+":00:00Z</Value></Geq>");
                    camlwhere.Append("                          <Leq><FieldRef Name='EndDateTime' /><Value Type='DateTime' IncludeTimeValue='TRUE'  >"+startdate.Year+"-"+startdate.Month+"-"+startdate.Day+"T"+endDate.Hour+":00:00Z</Value></Leq>");
                    camlwhere.Append("                </And>");   
                    camlwhere.Append("                <And>  ");       
                    camlwhere.Append("                     <Eq><FieldRef Name='IsFullDay' /><Value Type='Integer'>0</Value> </Eq>");
                    camlwhere.Append("                     <Eq><FieldRef Name='RequestedBy' LookupId='TRUE' /><Value Type='int'>9</Value></Eq>");
                    camlwhere.Append("                 </And>");
                    camlwhere.Append("    </And>");
                    camlwhere.Append("</Or>");
                    camlwhere.Append("</Where>");

                    camlQuery.ViewXml = @"<View><Query>" + camlwhere.ToString() + "</Query></View>";
                    listItems = selectedList.GetItems(camlQuery);
                    clientContext.Load<Microsoft.SharePoint.Client.ListItemCollection>(listItems);
                    clientContext.ExecuteQuery();
                    if (listItems.Count > 0)
                        return true;
                    else
                        return false;
                }

                catch (Exception ex)
                {
                    Microsoft.SharePoint.Client.Utilities.Utility.LogCustomRemoteAppError(clientContext, Global.ProductId, ex.Message);
                    clientContext.ExecuteQuery();
                    return false;
                }
            }
        }
 public void LoadUIByGuid(string requestID, string accessToken)
 {
     if (sharepointUrl == null)
         sharepointUrl = new Uri(Config.ListURL);
     TimeOffRequests objTimeOffReq = new TimeOffRequests();
     objTimeOffReq.RequestID= Request.QueryString["RequestID"].ToString();
     objTimeOffReq = objTimeOffReq.GetRequestDetailbyRequestID(sharepointUrl.ToString(), accessToken);           
     //If(current user is concerned Approver, if it is cancelled request, and status=approved)
     if (IsCancelRequested(objTimeOffReq) && IsStatusApproved(objTimeOffReq) && IsConcernedApprover(objTimeOffReq))
     {
         LoadUI(objTimeOffReq);
     }
     else
         ShowUnAuthorizedInfo();
 
 }
        public List<TimeOffRequests> GetMyTimeOfRequests( string TimeOffRequests)
        {
            Microsoft.SharePoint.Client.ListItemCollection listItems;
           // using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl, accessToken))

            var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext.Current);
            using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) //CreateAppOnlyClientContextForSPAppWeb
            {
                try
                {
                    Web web = clientContext.Web;
                    ListCollection lists = web.Lists;
                    List selectedList = lists.GetByTitle(TimeOffRequests);
                    clientContext.Load<ListCollection>(lists); // this lists object is loaded successfully
                    clientContext.Load<List>(selectedList);  // this list object is loaded successfully
                    clientContext.ExecuteQuery();
                    clientContext.Load(web.CurrentUser);
                    clientContext.ExecuteQuery();
                    CamlQuery camlQuery = new CamlQuery();
                    StringBuilder camlwhere = new StringBuilder();
                    StringBuilder orderby = new StringBuilder();
                    orderby.Append("<OrderBy><FieldRef Name='StartDateTime' Ascending='FALSE'></FieldRef></OrderBy>");

                    camlwhere.Append("<Where>");
                    camlwhere.Append("<And>");
                    camlwhere.Append("<Eq><FieldRef Name='RequestedBy' LookupId='TRUE' /><Value Type='int'>" + clientContext.Web.CurrentUser.Id + "</Value></Eq>");

                    camlwhere.Append("<Geq><FieldRef Name='StartDateTime' /><Value Type='DateTime'><Today OffsetDays='-90' /></Value></Geq>");

                    camlwhere.Append("</And>");
                    camlwhere.Append("</Where>");
                    camlQuery.ViewXml = @"<View><Query>" + orderby.ToString() + camlwhere.ToString() + "</Query></View>";
                    listItems = selectedList.GetItems(camlQuery);
                    clientContext.Load<Microsoft.SharePoint.Client.ListItemCollection>(listItems);
                    clientContext.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    Microsoft.SharePoint.Client.Utilities.Utility.LogCustomRemoteAppError(clientContext, Global.ProductId, ex.Message);
                    clientContext.ExecuteQuery();
                    return null;
                }

            }

            List<TimeOffRequests> listTimeoffReq = new List<TimeOffRequests>();
            TimeOffRequests objTimeOffRequests;
            foreach (Microsoft.SharePoint.Client.ListItem oListItem in listItems)
            {
                objTimeOffRequests = new TimeOffRequests();
                //todo
                objTimeOffRequests.StartDate = Convert.ToDateTime(oListItem["StartDateTime"].ToString()); ;// oListItem["StartDateTime"] != null ? (DateTime)oListItem["StartDateTime"] : null;
                objTimeOffRequests.EndDate = Convert.ToDateTime(oListItem["EndDateTime"].ToString());// oListItem["EndDateTime"] != null ? Convert.ToDateTime(oListItem["StartDateTime"].ToString()) : null;
                objTimeOffRequests.TimeOffType = oListItem["TimeOffType"] != null ? oListItem["TimeOffType"].ToString() : "";
                objTimeOffRequests.Status = oListItem["Status"] != null ? oListItem["Status"].ToString() : "";
                if (oListItem["Notes"] != null)
                    objTimeOffRequests.Notes = oListItem["Notes"] != null ? oListItem["Notes"].ToString() : "";


                objTimeOffRequests.isFullDay = "Full Day";
                if ((bool)oListItem["IsFullDay"] == false)
                    objTimeOffRequests.isFullDay = "Partial Day";
                objTimeOffRequests.TotalHours = Convert.ToDecimal(oListItem["TotalHours"].ToString());
                objTimeOffRequests.RequestID = (string)oListItem["RequestID"];
                objTimeOffRequests.CancelStatus = (string)oListItem["CancelStatus"];
                //========================================
                listTimeoffReq.Add(objTimeOffRequests);
            }
            return listTimeoffReq;

        }
 public bool IsCancelRequested(TimeOffRequests objTOR)
 {
     return objTOR.CancelStatus == "Cancel" ? true : false;
 }