protected override void CreateChildControls()
        {
            tb.AddTimer();
            act        = new EPMLiveCore.Act(SPContext.Current.Web);
            activation = act.CheckFeatureLicense(EPMLiveCore.ActFeature.Timesheets);

            if (activation != 0)
            {
                return;
            }

            if (SPContext.Current.ViewContext.View != null)
            {
                try
                {
                    typeof(ListTitleViewSelectorMenu).GetField("m_wpSingleInit", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(Page.FindControl("ctl00$PlaceHolderPageTitleInTitleArea$ctl01$ctl00").Controls[1], true);
                }
                catch { }
                try
                {
                    typeof(ListTitleViewSelectorMenu).GetField("m_wpSingle", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(Page.FindControl("ctl00$PlaceHolderPageTitleInTitleArea$ctl01$ctl00").Controls[1], true);
                }
                catch { }
            }

            try
            {
                sPeriodId = Page.Request["NewPeriod"].ToString();
            }
            catch { }
            try
            {
                sUserId = Page.Request["Delegate"].ToString();
            }
            catch { }

            ///

            SPWeb web = SPContext.Current.Web;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                settings = new TimesheetSettings(web);

                SqlConnection cn = new SqlConnection(EPMLiveCore.CoreFunctions.getConnectionString(web.Site.WebApplication.Id));
                cn.Open();

                SqlCommand cmd  = new SqlCommand("spTSGetPeriodsForSite", cn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@siteid", web.Site.ID);

                DataSet ds = new DataSet();

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);

                DataTable dtPeriods = ds.Tables[0];

                DataRow[] drCur = dtPeriods.Select("CurPeriod='1'");
                if (drCur.Length > 0)
                {
                    iCurPeriodId   = int.Parse(drCur[0]["period_id"].ToString());
                    sCurPeriodName = ((DateTime)drCur[0]["period_start"]).ToShortDateString() + " - " + ((DateTime)drCur[0]["period_end"]).ToShortDateString();
                }
                if (dtPeriods.Rows.Count > 0)
                {
                    if (sPeriodId == "")
                    {
                        DataRow[] dr = dtPeriods.Select("CurPeriod='1'");
                        if (dr.Length > 0)
                        {
                            sPeriodId   = dr[0]["period_id"].ToString();
                            sPeriodName = ((DateTime)dr[0]["period_start"]).ToShortDateString() + " - " + ((DateTime)dr[0]["period_end"]).ToShortDateString();
                            bIsCurrentTimesheetPeriod = true;
                        }
                        else
                        {
                            sPeriodId   = dtPeriods.Rows[dtPeriods.Rows.Count - 1]["period_id"].ToString();
                            sPeriodName = ((DateTime)dtPeriods.Rows[dtPeriods.Rows.Count - 1]["period_start"]).ToShortDateString() + " - " + ((DateTime)dtPeriods.Rows[dtPeriods.Rows.Count - 1]["period_end"]).ToShortDateString();
                        }
                    }
                    else
                    {
                        DataRow[] dr = ds.Tables[0].Select("period_id='" + sPeriodId + "'");
                        if (dr.Length > 0)
                        {
                            sPeriodName = ((DateTime)dr[0]["period_start"]).ToShortDateString() + " - " + ((DateTime)dr[0]["period_end"]).ToShortDateString();
                            try
                            {
                                if (dr[0]["curPeriod"].ToString() == "1")
                                {
                                    bIsCurrentTimesheetPeriod = true;
                                }
                            }
                            catch { }
                        }
                        else
                        {
                            DataRow[] dr2 = ds.Tables[0].Select("CurPeriod='1'");
                            if (dr2.Length > 0)
                            {
                                sPeriodId   = dr2[0]["period_id"].ToString();
                                sPeriodName = ((DateTime)dr2[0]["period_start"]).ToShortDateString() + " - " + ((DateTime)dr2[0]["period_end"]).ToShortDateString();
                                bIsCurrentTimesheetPeriod = true;
                            }
                            else
                            {
                                sPeriodId   = dtPeriods.Rows[dtPeriods.Rows.Count - 1]["period_id"].ToString();
                                sPeriodName = ((DateTime)dtPeriods.Rows[dtPeriods.Rows.Count - 1]["period_start"]).ToShortDateString() + " - " + ((DateTime)dtPeriods.Rows[dtPeriods.Rows.Count - 1]["period_end"]).ToShortDateString();
                            }
                        }
                    }

                    string itmpprev = "";
                    bool bNext      = false;

                    foreach (DataRow dr in dtPeriods.Rows)
                    {
                        sPeriodList += "," + dr["period_id"].ToString() + "|" + ((DateTime)dr["period_start"]).ToShortDateString() + " - " + ((DateTime)dr["period_end"]).ToShortDateString();

                        if (bNext)
                        {
                            bNext = false;

                            iNextPeriod = int.Parse(dr["period_id"].ToString());
                        }

                        if (dr["period_id"].ToString() == sPeriodId)
                        {
                            if (itmpprev != "")
                            {
                                iPreviousPeriod = int.Parse(itmpprev);
                            }
                            bNext = true;
                        }

                        itmpprev = dr["period_id"].ToString();
                    }

                    sPeriodList = sPeriodList.Trim(',');

                    TSNotes = settings.AllowNotes.ToString().ToLower();


                    cmd = new SqlCommand("SELECT TSTYPE_ID, TSTYPE_NAME FROM TSTYPE where SITE_UID=@siteid", cn);
                    cmd.Parameters.AddWithValue("@siteid", web.Site.ID);

                    SqlDataReader drTypes = cmd.ExecuteReader();
                    while (drTypes.Read())
                    {
                        int id = drTypes.GetInt32(0);

                        TSColType = 2;

                        TSTypeObject += ",T" + id + ": '" + drTypes.GetString(1) + "'";
                    }
                    drTypes.Close();


                    TSTypeObject = "{" + TSTypeObject.Trim(',') + "}";

                    ArrayList arrPeriods = TimesheetAPI.GetPeriodDaysArray(cn, settings, web, sPeriodId);

                    foreach (DateTime dtStart in arrPeriods)
                    {
                        TSCols += "\"P" + dtStart.Ticks + "\": true,";
                    }

                    foreach (DateTime dtStart in arrPeriods)
                    {
                        TSDCols += "\"P" + dtStart.Ticks + "\": \"" + settings.DayDef.Split('|')[(int)dtStart.DayOfWeek * 3 + 1] + "|" + settings.DayDef.Split('|')[(int)dtStart.DayOfWeek * 3 + 2] + "\",";
                    }

                    TSCols  = "{" + TSCols.Trim(',') + "}";
                    TSDCols = "{" + TSDCols.Trim(',') + "}";

                    if (GridType == 0)
                    {
                        SPUser user = TimesheetAPI.GetUser(web, sUserId);

                        cmd = new SqlCommand("SELECT submitted, approval_status, locked FROM TSTIMESHEET where SITE_UID=@siteid and period_id=@period and username=@username", cn);
                        cmd.Parameters.AddWithValue("@siteid", web.Site.ID);
                        cmd.Parameters.AddWithValue("@period", sPeriodId);
                        cmd.Parameters.AddWithValue("@username", user.LoginName);

                        SqlDataReader drTS = cmd.ExecuteReader();
                        if (drTS.Read())
                        {
                            //Locked
                            if (drTS.GetBoolean(2))
                            {
                                bTsLocked = true;
                            }

                            //Submitted
                            if (drTS.GetBoolean(0))
                            {
                                if (drTS.GetInt32(1) == 1)
                                {
                                    sStatus = "Approved";
                                    if (!settings.DisableApprovals)
                                    {
                                        bTsLocked = true;
                                    }
                                }
                                else if (drTS.GetInt32(1) == 2)
                                {
                                    sStatus = "Rejected";
                                }
                                else
                                {
                                    sStatus = "Submitted";
                                }
                            }
                        }
                        drTS.Close();
                    }
                    else
                    {
                        bTsLocked = true;
                    }


                    cn.Close();

                    bHasPeriods = true;
                }
            });



            sDataParam   = "<Param GridId=\"" + sFullGridId + "\" Period=\"" + sPeriodId + "\" UserId=\"" + sUserId + "\"/>";
            sLayoutParam = "<Param GridId=\"" + sFullGridId + "\" Period=\"" + sPeriodId + "\" UserId=\"" + sUserId + "\" Editable=\"" + iEditable + "\" GridType=\"" + GridType + "\"/>";

            sDataParam   = System.Web.HttpUtility.HtmlEncode(System.Web.HttpUtility.HtmlEncode(sDataParam));
            sLayoutParam = System.Web.HttpUtility.HtmlEncode(System.Web.HttpUtility.HtmlEncode(sLayoutParam));
            ///


            DataTable dtTsDelegates = EPMLiveCore.API.APITeam.GetResourcePool("<Resources FilterField=\"TimesheetDelegates\" FilterFieldValue=\"" + web.CurrentUser.Name + "\" ><Columns>SimpleColumns</Columns></Resources>", web);

            foreach (DataRow dr in dtTsDelegates.Rows)
            {
                if (sUserId == dr["SPID"].ToString())
                {
                    sCurrentDelegate = dr["Title"].ToString();
                }

                sDelegates += dr["SPID"].ToString() + "|" + dr["Title"].ToString() + "^";
            }

            sDelegates = sDelegates.Trim('^');

            string serviceUrl = ((SPContext.Current.Web.ServerRelativeUrl == "/")
                                     ? ""
                                     : SPContext.Current.Web.ServerRelativeUrl) + "/_vti_bin/Workengine.asmx";

            ScriptManager scriptManager = ScriptManager.GetCurrent(Page);

            if (scriptManager != null)
            {
                scriptManager.Services.Add(new ServiceReference(serviceUrl));
            }
            else
            {
                scriptManager = new ScriptManager();
                scriptManager.Services.Add(new ServiceReference(serviceUrl));

                Page.Form.Controls.Add(scriptManager);
            }

            views = TimesheetAPI.GetViews(web);

            tb.StopTimer();
        }
Example #2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            EPMLiveCore.Act act        = new EPMLiveCore.Act(Web);
            int             activation = act.CheckFeatureLicense(EPMLiveCore.ActFeature.Timesheets);

            if (activation != 0)
            {
                pnlActivation.Visible = true;
                pnlTs.Visible         = false;
            }


            using (SPWeb web = SPContext.Current.Web)
            {
                dtSpStart.DatePickerFrameUrl = web.Url + "/_layouts/iframe.aspx";
                dtSpEnd.DatePickerFrameUrl   = web.Url + "/_layouts/iframe.aspx";

                try
                {
                    if (!SPContext.Current.Web.UserIsSiteAdmin)
                    {
                        Response.Redirect(SPContext.Current.Web.Url + "/_layouts/accessdenied.aspx");
                    }

                    siteUrl = SPContext.Current.Web.Url;

                    if (!IsPostBack)
                    {
                        //using (SPWeb web = SPContext.Current.Web)
                        {
                            if (!web.IsRootWeb)
                            {
                                pnlTL.Visible       = true;
                                hlAdmin.NavigateUrl = SPContext.Current.Site.Url + "/_layouts/epmlive/timesheetadmin.aspx";
                                pnlMain.Visible     = false;
                            }
                            else
                            {
                                TimesheetSettings settings = new TimesheetSettings(Web);

                                SPList oMyWork = web.Lists.TryGetList("My Work");

                                string sFields = "";

                                if (oMyWork != null)
                                {
                                    SortedList sl = new SortedList();

                                    foreach (SPField field in oMyWork.Fields)
                                    {
                                        if (field.Reorderable && field.InternalName != "Title")
                                        {
                                            sl.Add(field.Title, field.InternalName);
                                        }
                                    }

                                    foreach (DictionaryEntry de in sl)
                                    {
                                        if (settings.TimesheetFields.Contains(de.Value.ToString()))
                                        {
                                            sFields += "," + de.Value.ToString();
                                            ListItem li = new ListItem(de.Key.ToString(), de.Value.ToString());
                                            ddlTSFieldsS.Items.Add(li);
                                        }
                                        else
                                        {
                                            ListItem li = new ListItem(de.Key.ToString(), de.Value.ToString());
                                            ddlTSFieldsA.Items.Add(li);
                                        }
                                    }
                                }

                                sFields = sFields.Trim(',');

                                hdnTSFields.Value = sFields;

                                chkAllowStopWatch.Checked = settings.AllowStopWatch;



                                //using (SPSite site = SPContext.Current.Site)
                                SPSite site = SPContext.Current.Site;
                                {
                                    //using (SPWeb rweb = site.RootWeb)
                                    SPWeb rweb = site.RootWeb;
                                    {
                                        try
                                        {
                                            chkAllowUnassigned.Checked = bool.Parse(EPMLiveCore.CoreFunctions.getConfigSetting(rweb, "EPMLiveTSAllowUnassigned"));
                                        }
                                        catch { }
                                        try
                                        {
                                            chkAllowNotes.Checked = bool.Parse(EPMLiveCore.CoreFunctions.getConfigSetting(rweb, "EPMLiveTSAllowNotes"));
                                        }
                                        catch { }

                                        ddlFlagField.SelectedValue = EPMLiveCore.CoreFunctions.getConfigSetting(rweb, "EPMLiveTSFlag");
                                        txtLists.Text = EPMLiveCore.CoreFunctions.getConfigSetting(rweb, "EPMLiveTSLists");

                                        string dayDef = EPMLiveCore.CoreFunctions.getConfigSetting(rweb, "EPMLiveDaySettings");

                                        if (dayDef != "")
                                        {
                                            string[] daySettings = dayDef.Split('|');

                                            chkSunday.Checked = bool.Parse(daySettings[0]);
                                            txtSundayMin.Text = daySettings[1];
                                            txtSundayMax.Text = daySettings[2];

                                            chkMonday.Checked = bool.Parse(daySettings[3]);
                                            txtMondayMin.Text = daySettings[4];
                                            txtMondayMax.Text = daySettings[5];

                                            chkTuesday.Checked = bool.Parse(daySettings[6]);
                                            txtTuesdayMin.Text = daySettings[7];
                                            txtTuesdayMax.Text = daySettings[8];

                                            chkWednesday.Checked = bool.Parse(daySettings[9]);
                                            txtWednesdayMin.Text = daySettings[10];
                                            txtWednesdayMax.Text = daySettings[11];

                                            chkThursday.Checked = bool.Parse(daySettings[12]);
                                            txtThursdayMin.Text = daySettings[13];
                                            txtThursdayMax.Text = daySettings[14];

                                            chkFriday.Checked = bool.Parse(daySettings[15]);
                                            txtFridayMin.Text = daySettings[16];
                                            txtFridayMax.Text = daySettings[17];

                                            chkSaturday.Checked = bool.Parse(daySettings[18]);
                                            txtSaturdayMin.Text = daySettings[19];
                                            txtSaturdayMax.Text = daySettings[20];
                                        }
                                        chkCurrentData.Checked = bool.Parse(EPMLiveCore.CoreFunctions.getConfigSetting(rweb, "EPMLiveTSUseCurrent"));
                                        try { chkEnableNonTeamNotf.Checked = bool.Parse(EPMLiveCore.CoreFunctions.getConfigSetting(rweb, "EPMLiveEnableNonTeamNotf")); }
                                        catch { }
                                        txtPortManagerColumn.Text = EPMLiveCore.CoreFunctions.getConfigSetting(rweb, "EPMPortManagerColumn");
                                    }
                                }
                                SqlConnection cn = null;
                                SPSecurity.RunWithElevatedPrivileges(delegate()
                                {
                                    cn = new SqlConnection(EPMLiveCore.CoreFunctions.getConnectionString(web.Site.WebApplication.Id));
                                    cn.Open();
                                });

                                SqlCommand cmd = new SqlCommand("select top 1 period_end,period_id from tsperiod where site_id = @siteid order by period_id desc", cn);
                                cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID);
                                SqlDataReader dr = cmd.ExecuteReader();
                                if (dr.Read())
                                {
                                    lastPeriod = (dr.GetInt32(1) + 1).ToString();
                                    DateTime dtEnd = dr.GetDateTime(0);
                                    nextStart = dtEnd.AddDays(1).ToShortDateString();
                                    int stWeek = Microsoft.VisualBasic.DateAndTime.DatePart(Microsoft.VisualBasic.DateInterval.WeekOfYear, dtEnd.AddDays(1), Microsoft.VisualBasic.FirstDayOfWeek.Sunday, Microsoft.VisualBasic.FirstWeekOfYear.System);
                                    int enWeek = Microsoft.VisualBasic.DateAndTime.DatePart(Microsoft.VisualBasic.DateInterval.WeekOfYear, dtEnd.AddDays(7), Microsoft.VisualBasic.FirstDayOfWeek.Sunday, Microsoft.VisualBasic.FirstWeekOfYear.System);
                                    if (stWeek != enWeek && !(enWeek == 1 && stWeek == 53))
                                    {
                                        nextStartEnd = dtEnd.AddDays(6 - (int)dtEnd.DayOfWeek).ToShortDateString();
                                    }
                                    else if (dtEnd.AddDays(1).Month != dtEnd.AddDays(7).Month)
                                    {
                                        dtEnd        = dtEnd.AddDays(7);
                                        dtEnd        = dtEnd.AddDays(-1 * dtEnd.Day);
                                        nextStartEnd = dtEnd.ToShortDateString();
                                    }
                                    else
                                    {
                                        nextStartEnd = dtEnd.AddDays(7).ToShortDateString();
                                    }
                                    dtSpStart.SelectedDate       = DateTime.Parse(nextStart);
                                    dtSpStart.DatePickerFrameUrl = web.Url + "/_layouts/iframe.aspx";
                                    dtSpEnd.SelectedDate         = DateTime.Parse(nextStartEnd);
                                    dtSpEnd.DatePickerFrameUrl   = web.Url + "/_layouts/iframe.aspx";
                                }
                                dr.Close();

                                loadTypes(cn);

                                ddlNonWork.Items.Add(new ListItem("-- Select List --", ""));

                                foreach (SPList list in web.Lists)
                                {
                                    if (!list.Hidden)
                                    {
                                        ddlNonWork.Items.Add(new ListItem(list.Title, list.Title));
                                    }
                                }

                                ddlNonWork.SelectedValue        = EPMLiveCore.CoreFunctions.getConfigSetting(web, "EPMLiveTSNonWork");
                                ddlTimesheetHours.SelectedValue = EPMLiveCore.CoreFunctions.getConfigSetting(web, "EPMLiveTSTimesheetHours");
                                try
                                {
                                    chkDisableApprovals.Checked = bool.Parse(EPMLiveCore.CoreFunctions.getConfigSetting(web, "EPMLiveTSDisableApprovals"));
                                }
                                catch { }
                                try
                                {
                                    chkShowLiveHours.Checked = bool.Parse(EPMLiveCore.CoreFunctions.getConfigSetting(web, "EPMLiveTSLiveHours"));
                                }
                                catch { }
                                /////////
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Response.Write("Error: " + ex.Message);
                }
                ddlFieldLists.Items.Clear();
                //ddlFieldLists.Items.Add(new ListItem("Resources", "Resources"));
                string[] lists = txtLists.Text.Replace("\r\n", "\n").Split('\n');

                inputData = "";
                foreach (string list in lists)
                {
                    if (list != "Project Center")
                    {
                        addListFieldData(web, web, list);
                    }
                }



                string resUrl = EPMLiveCore.CoreFunctions.getConfigSetting(web, "EPMLiveResourceURL", true, false);

                if (resUrl != "")
                {
                    try
                    {
                        SPWeb resWeb;
                        if (resUrl.ToLower() != web.Url.ToLower())
                        {
                            using (SPSite tempSite = new SPSite(resUrl))
                            {
                                resWeb = tempSite.OpenWeb();
                                if (resWeb.Url.ToLower() != resUrl.ToLower())
                                {
                                    resWeb = null;
                                }
                            }
                        }
                        else
                        {
                            resWeb = web;
                        }
                        if (resWeb != null)
                        {
                            addListFieldData(resWeb, web, "Resources");
                            if (resWeb.ID != SPContext.Current.Web.ID)
                            {
                                resWeb.Close();
                            }
                        }
                    }
                    catch { }
                }
                addListFieldData(web, web, "Project Center");
            }
            ddlFieldLists.Attributes.Add("onchange", "switchList();");
        }
        private void ProcessItemRow(XmlNode ndRow, DataTable dtItems, SqlConnection cn, SPSite site, TimesheetSettings settings, bool liveHours, bool bSkipSP)
        {
            string id = iGetAttribute(ndRow, "UID");

            if (id != "")
            {
                DataRow[] drItem = dtItems.Select("TS_ITEM_UID='" + id + "'");

                try
                {
                    string webid  = iGetAttribute(ndRow, "WebID");
                    string listid = iGetAttribute(ndRow, "ListID");
                    string itemid = iGetAttribute(ndRow, "ItemID");

                    string itemtypeid = iGetAttribute(ndRow, "ItemTypeID");

                    if (itemtypeid == "")
                    {
                        itemtypeid = "1";
                    }

                    if (webid != "")
                    {
                        if (listid != "")
                        {
                            if (itemid != "")
                            {
                                try
                                {
                                    var        web = SaveDataJobExecuteCache.Cache.GetWeb(webid);
                                    SPListItem li  = null;

                                    var list = web.Lists[new Guid(listid)];

                                    var failures = 0;
                                    while (true)
                                    {
                                        try
                                        {
                                            try
                                            {
                                                li = SaveDataJobExecuteCache.Cache.GetListItem(web.ServerRelativeUrl, list.ID, int.Parse(itemid), refresh: failures > 0);
                                            }
                                            catch
                                            {
                                            }

                                            if (li != null)
                                            {
                                                int    projectid   = 0;
                                                string project     = "";
                                                string projectlist = "";
                                                try
                                                {
                                                    SPFieldLookupValue lv =
                                                        new SPFieldLookupValue(li[list.Fields.GetFieldByInternalName("Project").Id].ToString());
                                                    projectid = lv.LookupId;
                                                    project   = lv.LookupValue;
                                                }
                                                catch
                                                {
                                                }

                                                if (liveHours)
                                                {
                                                    if (!processLiveHours(li, list.ID))
                                                    {
                                                        return;
                                                    }

                                                    if (li.Fields.ContainsFieldWithInternalName("PercentComplete") &&
                                                        li.Fields.ContainsFieldWithInternalName("Status"))
                                                    {
                                                        SPField percentCompleteField = li.Fields.GetFieldByInternalName("PercentComplete");
                                                        SPField statusField          = li.Fields.GetFieldByInternalName("Status");
                                                        if (percentCompleteField != null && statusField != null)
                                                        {
                                                            Double value = Convert.ToDouble(li[percentCompleteField.InternalName]);
                                                            if (value == 0)
                                                            {
                                                                li[statusField.InternalName] = "Not Started";
                                                            }
                                                            else if (value > 0 & value < 1)
                                                            {
                                                                li[statusField.InternalName] = "In Progress";
                                                            }
                                                            else if (value == 1)
                                                            {
                                                                li[statusField.InternalName] = "Completed";
                                                            }
                                                        }
                                                    }
                                                }

                                                SPSecurity.RunWithElevatedPrivileges(delegate { li.Update(); });
                                            }
                                        }
                                        catch (SPException ex) when(ex.HResult == SaveConflictErrorCode && ++failures < MaxTaskFailures)
                                        {
                                            continue;
                                        }
                                        catch (Exception ex)
                                        {
                                            bErrors  = true;
                                            sErrors += "Item (" + id + ") Error: " + ex.ToString();
                                        }

                                        break;
                                    }
                                }
                                catch
                                {
                                }
                            }
                            else
                            {
                                bErrors  = true;
                                sErrors += "Item (" + id + ") missing item id";
                            }
                        }
                        else
                        {
                            bErrors  = true;
                            sErrors += "Item (" + id + ") missing list id";
                        }
                    }
                    else
                    {
                        bErrors  = true;
                        sErrors += "Item (" + id + ") missing web id";
                    }
                }
                catch (Exception ex)
                {
                    bErrors  = true;
                    sErrors += "Item (" + id + ") Error x2: " + ex.ToString();
                }
                finally
                {
                    if (drItem.Length > 0)
                    {
                        dtItems.Rows.Remove(drItem[0]);
                    }
                }
            }
            else
            {
                bErrors  = true;
                sErrors += "Could not get id for item";
            }
        }
        public void execute(SPSite site, string data)
        {
            DataTable dtItems = null;
            int       userid  = 0;

            WebAppId = site.WebApplication.Id;
            using (SqlConnection cn = CreateConnection())
            {
                try
                {
                    cn.Open();
                    try
                    {
                        WorkList = site.RootWeb.Lists["My Work"];
                    }
                    catch { }

                    XmlDocument docTimesheet = new XmlDocument();
                    docTimesheet.LoadXml(data);

                    using (SqlCommand cmd = new SqlCommand("SELECT     dbo.TSUSER.USER_ID FROM         dbo.TSUSER INNER JOIN dbo.TSTIMESHEET ON dbo.TSUSER.TSUSERUID = dbo.TSTIMESHEET.TSUSER_UID WHERE TS_UID=@tsuid", cn))
                    {
                        cmd.Parameters.AddWithValue("@tsuid", base.TSUID);
                        using (SqlDataReader dr = cmd.ExecuteReader())
                        {
                            if (dr.Read())
                            {
                                userid = dr.GetInt32(0);
                            }
                        }
                    }

                    //bool SaveAndSubmit = false;
                    //try
                    //{
                    //    SaveAndSubmit = bool.Parse(docTimesheet.FirstChild.Attributes["SaveAndSubmit"].Value);
                    //}
                    //catch { }

                    bool liveHours = false;

                    bool.TryParse(EPMLiveCore.CoreFunctions.getConfigSetting(site.RootWeb, "EPMLiveTSLiveHours"), out liveHours);

                    if (userid != 0)
                    {
                        SPUser user = TimesheetAPI.GetUser(site.RootWeb, userid.ToString());

                        if (user.ID != userid)
                        {
                            bErrors = true;
                            sErrors = "You do not have access to edit that timesheet.";
                        }
                        else
                        {
                            using (SqlCommand cmd1 = new SqlCommand("update TSQUEUE set percentcomplete=1 where TSQUEUE_ID=@QueueUid", cn))
                            {
                                cmd1.Parameters.AddWithValue("@queueuid", QueueUid);
                                cmd1.ExecuteNonQuery();
                            }

                            TimesheetSettings settings = new TimesheetSettings(site.RootWeb);

                            DataSet dsItems = new DataSet();

                            SPUser editUser = site.RootWeb.AllUsers.GetByID(base.userid);

                            using (var cache = SaveDataJobExecuteCache.InitializeCache(site))
                            {
                                using (SqlCommand cmd2 = new SqlCommand("SELECT * FROM TSITEM WHERE TS_UID=@tsuid", cn))
                                {
                                    cmd2.Parameters.AddWithValue("@tsuid", base.TSUID);
                                    using (SqlDataAdapter da = new SqlDataAdapter(cmd2))
                                    {
                                        da.Fill(dsItems);
                                        dtItems = dsItems.Tables[0];

                                        XmlNodeList ndItems = docTimesheet.FirstChild.SelectNodes("Item");

                                        float percent = 0;
                                        float count   = 0;
                                        float total   = ndItems.Count;

                                        using (SqlCommand cmd3 = new SqlCommand("update TSQUEUE set percentcomplete=2 where TSQUEUE_ID=@QueueUid",
                                                                                cn))
                                        {
                                            cmd3.Parameters.AddWithValue("@queueuid", QueueUid);
                                            cmd3.ExecuteNonQuery();
                                        }

                                        string preloadErrors;
                                        var    preloadHasErrors =
                                            cache.PreloadListItems(ndItems.Cast <XmlNode>().Select(i => new SaveDataJobExecuteCache.ListItemInfo
                                        {
                                            WebId      = iGetAttribute(i, "WebID"),
                                            ListId     = iGetAttribute(i, "ListID"),
                                            ListItemId = iGetAttribute(i, "ItemID")
                                        }), out preloadErrors);
                                        if (preloadHasErrors)
                                        {
                                            bErrors  = true;
                                            sErrors += preloadErrors;
                                        }

                                        foreach (XmlNode ndItem in ndItems)
                                        {
                                            string worktype = "";

                                            try
                                            {
                                                worktype = ndItem.Attributes["WorkTypeField"].Value;
                                            }
                                            catch
                                            {
                                            }

                                            ProcessItemRow(ndItem, dtItems, cn, site, settings, liveHours, worktype == settings.NonWorkList);

                                            count++;
                                            float pct = count / total * 98;

                                            if (pct >= percent + 10)
                                            {
                                                using (SqlCommand cmd4 =
                                                           new SqlCommand("update TSQUEUE set percentcomplete=@pct where TSQUEUE_ID=@QueueUid", cn))
                                                {
                                                    cmd4.Parameters.AddWithValue("@queueuid", QueueUid);
                                                    cmd4.Parameters.AddWithValue("@pct", pct);
                                                    cmd4.ExecuteNonQuery();
                                                }

                                                percent = pct;
                                            }
                                        }
                                    }
                                }

                                if (liveHours)
                                {
                                    sErrors += processProjectWork(cn, TSUID.ToString(), site, true, false);
                                }
                            }
                        }
                    }
                    else
                    {
                        bErrors = true;
                        sErrors = "Timesheet does not exist";
                    }
                }
                catch (Exception ex)
                {
                    bErrors = true;
                    sErrors = "Error: " + ex.ToString();
                }
                finally
                {
                    if (dtItems != null)
                    {
                        dtItems.Dispose();
                    }
                    if (site != null)
                    {
                        site.Dispose();
                    }
                    data = null;
                }
            }
        }
Example #5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(System.Web.HttpUtility.HtmlDecode(Request["Data"]));

            string sPeriodId = doc.FirstChild.SelectSingleNode("//Cfg").Attributes["PeriodId"].Value;
            string tsuid     = doc.FirstChild.SelectSingleNode("//Cfg").Attributes["TimesheetUID"].Value;
            bool   submit    = false;

            try
            {
                submit = bool.Parse(doc.FirstChild.SelectSingleNode("//Cfg").Attributes["SaveAndSubmit"].Value);
            }
            catch { }

            TimesheetSettings settings = new TimesheetSettings(SPContext.Current.Web);

            XmlNodeList ndListItems = doc.FirstChild.SelectNodes("//B/I");

            XmlDocument docTimesheet = new XmlDocument();

            int userId = SPContext.Current.Web.CurrentUser.ID;

            if (!string.IsNullOrEmpty(Page.Request["Delegate"]))
            {
                SPUser user = TimesheetAPI.GetUser(SPContext.Current.Web, Page.Request["Delegate"]);
                userId = user.ID;
            }

            docTimesheet.LoadXml("<Timesheet TSUID=\"" + tsuid + "\" Editable=\"0\" SaveAndSubmit=\"" + submit.ToString() + "\" TimesheetOwnerID=\"" + userId + "\"/>");

            try
            {
                docTimesheet.FirstChild.Attributes["Editable"].Value = doc.FirstChild.SelectSingleNode("//Cfg").Attributes["GridEditable"].Value;
            }
            catch { }

            SqlConnection cn = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                cn = new SqlConnection(EPMLiveCore.CoreFunctions.getConnectionString(SPContext.Current.Web.Site.WebApplication.Id));
                cn.Open();
            });



            SqlCommand cmd = new SqlCommand("SELECT * FROM TSTYPE where SITE_UID=@siteid", cn);

            cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID);

            DataSet        ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter(cmd);

            da.Fill(ds);

            DataTable dtTypes = ds.Tables[0];

            bool bTypes = false;

            if (dtTypes.Rows.Count > 0)
            {
                bTypes = true;
            }

            ArrayList arrPeriodDates    = TimesheetAPI.GetPeriodDaysArray(cn, settings, SPContext.Current.Web, sPeriodId);
            Hashtable arrPeriodDateCols = new Hashtable();

            foreach (DateTime dt in arrPeriodDates)
            {
                arrPeriodDateCols.Add("P" + dt.Ticks, dt.ToString("s"));
                if (bTypes)
                {
                    arrPeriodDateCols.Add("TSP" + dt.Ticks, dt.ToString("s"));
                }
            }

            cn.Close();

            foreach (XmlNode nd in ndListItems)
            {
                XmlNode ndRow      = docTimesheet.CreateNode(XmlNodeType.Element, "Item", docTimesheet.NamespaceURI);
                XmlNode ndRowHours = docTimesheet.CreateNode(XmlNodeType.Element, "Hours", docTimesheet.NamespaceURI);
                ndRow.AppendChild(ndRowHours);

                foreach (XmlAttribute attr in nd.Attributes)
                {
                    if (arrPeriodDateCols.Contains(attr.Name))
                    {
                        if (bTypes)
                        {
                            if (attr.Name.StartsWith("TS"))
                            {
                                JavaScriptSerializer a = new JavaScriptSerializer();
                                object o = a.DeserializeObject(attr.Value);

                                System.Collections.Generic.Dictionary <string, object> oo = (System.Collections.Generic.Dictionary <string, object>)o;

                                XmlNode ndDate = docTimesheet.CreateNode(XmlNodeType.Element, "Date", docTimesheet.NamespaceURI);

                                XmlAttribute attr1 = docTimesheet.CreateAttribute("Value");
                                attr1.Value = arrPeriodDateCols[attr.Name].ToString();
                                ndDate.Attributes.Append(attr1);

                                foreach (DataRow dr in dtTypes.Rows)
                                {
                                    try
                                    {
                                        XmlNode ndTime = docTimesheet.CreateNode(XmlNodeType.Element, "Time", docTimesheet.NamespaceURI);

                                        attr1       = docTimesheet.CreateAttribute("Hours");
                                        attr1.Value = oo["T" + dr["TSTYPE_ID"].ToString()].ToString();
                                        ndTime.Attributes.Append(attr1);

                                        attr1       = docTimesheet.CreateAttribute("Type");
                                        attr1.Value = dr["TSTYPE_ID"].ToString();
                                        ndTime.Attributes.Append(attr1);

                                        ndDate.AppendChild(ndTime);
                                    }
                                    catch { }
                                }

                                if (settings.AllowNotes)
                                {
                                    string notes = "";
                                    try
                                    {
                                        notes = oo["Notes"].ToString();
                                    }
                                    catch { }
                                    if (notes != "")
                                    {
                                        XmlNode ndNotes = docTimesheet.CreateNode(XmlNodeType.Element, "Notes", docTimesheet.NamespaceURI);
                                        ndNotes.InnerText = notes;
                                        ndDate.AppendChild(ndNotes);
                                    }
                                }

                                ndRowHours.AppendChild(ndDate);
                            }
                        }
                        else
                        {
                            XmlNode ndDate = docTimesheet.CreateNode(XmlNodeType.Element, "Date", docTimesheet.NamespaceURI);

                            XmlAttribute attr1 = docTimesheet.CreateAttribute("Value");
                            attr1.Value = arrPeriodDateCols[attr.Name].ToString();
                            ndDate.Attributes.Append(attr1);


                            XmlNode ndTime = docTimesheet.CreateNode(XmlNodeType.Element, "Time", docTimesheet.NamespaceURI);
                            ndDate.AppendChild(ndTime);

                            attr1       = docTimesheet.CreateAttribute("Hours");
                            attr1.Value = attr.Value;
                            ndTime.Attributes.Append(attr1);

                            if (settings.AllowNotes)
                            {
                                string notes = nd.Attributes["TS" + attr.Name].Value;
                                if (notes != "")
                                {
                                    XmlNode ndNotes = docTimesheet.CreateNode(XmlNodeType.Element, "Notes", docTimesheet.NamespaceURI);
                                    ndNotes.InnerText = notes;
                                    ndDate.AppendChild(ndNotes);
                                }
                            }

                            ndRowHours.AppendChild(ndDate);
                        }
                    }
                    else
                    {
                        XmlAttribute attr1 = docTimesheet.CreateAttribute(attr.Name);
                        attr1.Value = attr.Value;
                        ndRow.Attributes.Append(attr1);
                    }
                }

                docTimesheet.FirstChild.AppendChild(ndRow);
            }

            XmlDocument docRes = new XmlDocument();

            docRes.LoadXml(TimesheetAPI.SaveTimesheet(docTimesheet.OuterXml, SPContext.Current.Web));



            if (docRes.FirstChild.Attributes["Status"].Value == "0")
            {
                data = "<Grid><IO Result='" + docRes.FirstChild.Attributes["Status"].Value + "'/></Grid>";
            }
            else
            {
                data = "<Grid><IO Result='" + docRes.FirstChild.Attributes["Status"].Value + "' Message='" + docRes.FirstChild.InnerText + "'/></Grid>";
            }
        }