private Tuple <string, string, string, string, bool>[] GetSocialActions(SPListItem listItem,
                                                                                GridGanttSettings settings, out Dictionary <string, string> di)
        {
            bool success = true;

            di = new Dictionary <string, string> {
                { "Social Actions", true.ToString() }
            };

            var actions = new Tuple <string, string, string, string, bool>[] { };

            try
            {
                actions = new[]
                {
                    AT("Comments", "comments", "/_layouts/epmlive/images/comments16.gif",
                       LIP(listItem, SPBasePermissions.EditListItems), "5"),
                    AT("Edit Team", "buildteam", "/_layouts/epmlive/images/buildteam16.gif",
                       LIP(listItem, SPBasePermissions.EditListItems) && settings.BuildTeam, "6")
                };
            }
            catch (Exception e)
            {
                success = false;
                di.Add("Social Actions Exception", e.Message);
            }

            di.Add("Social Actions Success", success.ToString());

            return(actions);
        }
        private void SaveGridGantSettings(SPList list, string internalName, string advancedLookup, int messageId)
        {
            var gSettings = new GridGanttSettings(list);

            var LookupArray = gSettings.Lookups.Split('|');

            var output = new StringBuilder();

            foreach (var sLookup in LookupArray)
            {
                if (!string.IsNullOrWhiteSpace(sLookup))
                {
                    var sLookupInfo = sLookup.Split('^');

                    if (sLookupInfo[0] != internalName)
                    {
                        output.Append("|")
                        .Append(sLookup);
                    }
                }
            }

            output.Append("|")
            .Append(internalName)
            .Append("^")
            .Append(advancedLookup);

            gSettings.Lookups = output.ToString().Trim('|');
            gSettings.SaveSettings(list);

            addMessage(ErrorLevels.NoError, "Enabled Advanced Lookup", string.Empty, messageId);
        }
        private static void SaveGridGanttSettings(SPList list, string internalName, string total)
        {
            var gridGanttSettings = new GridGanttSettings(list);

            var output = new StringBuilder();

            var fieldList = gridGanttSettings.TotalSettings.Split('\n');

            foreach (var field in fieldList)
            {
                if (!string.IsNullOrWhiteSpace(field))
                {
                    var fieldData = field.Split('|');
                    if (fieldData[0] != internalName)
                    {
                        output.Append("\n")
                        .Append(field);
                    }
                }
            }

            output.Append("\n")
            .Append(internalName)
            .Append("|")
            .Append(total);

            gridGanttSettings.TotalSettings = output.ToString().Trim('\n');
            gridGanttSettings.SaveSettings(list);
        }
Пример #4
0
        public void AddBuildTeamSecurityGroups_TypeGuest_UpdatesSecurityGroups()
        {
            // Arrange
            const SPRoleType type    = SPRoleType.Guest;
            var buildTeamPermissions = "1~2~3|1~2~3";
            var settingsDictionary   = new Dictionary <int, string>()
            {
                [33] = buildTeamPermissions
            };

            ShimCoreFunctions.getListSettingStringSPList = (_, __) =>
            {
                var settings = string.Empty;

                for (var index = 0; index <= 50; index++)
                {
                    if (settingsDictionary.ContainsKey(index))
                    {
                        settings += $"{settingsDictionary[index]};";
                    }
                    else
                    {
                        settings += $"{DummyString};";
                    }
                }
                return(settings.Replace(";", "\n"));
            };
            ShimSPRoleDefinition.AllInstances.TypeGet = _ => type;
            ShimSPRoleDefinitionBindingCollection.AllInstances.AddSPRoleDefinition = (_, __) =>
            {
                validations += 1;
            };
            ShimSecurityUpdate.AllInstances.AddNewItemLvlPermSPListItemSPWebSPRoleAssignment = (_, _1, _2, _3) =>
            {
                validations += 1;
            };
            ShimSPGroup.AllInstances.UsersGet = _ => new ShimSPUserCollection();
            ShimSPRoleDefinitionCollection.AllInstances.ItemGetString = (_, __) =>
            {
                validations += 1;
                throw new SPException(DummyString);
            };

            var ganttSettings = new GridGanttSettings(spList);

            // Act
            privateObject.Invoke(
                AddBuildTeamSecurityGroupsMethodName,
                publicInstance,
                new object[]
            {
                spWeb.Instance,
                ganttSettings,
                spListItem.Instance
            });

            // Assert
            validations.ShouldBe(3);
        }
Пример #5
0
        public static GridGanttSettings GetGridGanttSettings(SPList list)
        {
            GridGanttSettings gSettings = (EPMLiveCore.GridGanttSettings)EPMLiveCore.Infrastructure.CacheStore.Current.Get("GGS", "GridSettings-" + list.ID.ToString(), () =>
            {
                return(new EPMLiveCore.GridGanttSettings(list));
            }).Value;

            return(gSettings);
        }
Пример #6
0
        private string getGanttParams()
        {
            var gSettings      = new GridGanttSettings(rcList);
            var resources      = string.Empty;
            var strRollupLists = gSettings.RollupLists;
            var strRollupSites = gSettings.RollupSites;

            if (!string.IsNullOrWhiteSpace(sResourceList))
            {
                var arrRes     = sResourceList.Replace(";#", "\n").Split('\n');
                var arrListRes = new ArrayList();
                arrListRes.AddRange(arrRes);
                var resourceBuilder = new StringBuilder();

                foreach (SPListItem spListItem in reslist.Items)
                {
                    if (arrListRes.Contains(spListItem.ID.ToString()))
                    {
                        try
                        {
                            if (spListItem["SharePointAccount"] != null)
                            {
                                var fieldUserValue = new SPFieldUserValue(spListItem.Web, spListItem["SharePointAccount"].ToString());
                                resourceBuilder.Append($";#{HttpUtility.UrlEncode(fieldUserValue.LookupValue)}");
                            }
                        }
                        catch (Exception exception)
                        {
                            Trace.WriteLine(exception);
                        }
                    }
                }

                resources = resourceBuilder.ToString();

                if (resources.Length > 2)
                {
                    resources = resources.Substring(2);
                }
            }

            var data =
                $"Lists/Resource Center/DispForm.aspx\n{SPContext.Current.ViewContext.View.Title}\nStartDate\nDueDate\nPercentComplete\n\n\nTrue\n\n\n{strRollupLists}\n{Page.Request["FilterField1"]}\n{Page.Request["FilterValue1"]}\n{strRollupSites}\n{resources}\n{gSettings.UsePopup}";

            var toEncodeAsBytes = Encoding.ASCII.GetBytes(data);

            return(Convert.ToBase64String(toEncodeAsBytes));
        }
Пример #7
0
        private static bool GatherValidLists(DataTable listNames, SPWeb spWeb, DataTable listIds, bool hasError, StringBuilder errMsg)
        {
            Guard.ArgumentIsNotNull(listNames, nameof(listNames));
            Guard.ArgumentIsNotNull(spWeb, nameof(spWeb));
            Guard.ArgumentIsNotNull(listIds, nameof(listIds));
            Guard.ArgumentIsNotNull(errMsg, nameof(errMsg));

            try
            {
                if (listNames.Rows.Count > 0)
                {
                    var listName = string.Empty;

                    foreach (DataRow dataRow in listNames.Rows)
                    {
                        try
                        {
                            listName = dataRow[ListName].ToString();
                        }
                        catch (Exception exception)
                        {
                            Trace.WriteLine(exception);
                        }

                        if (!string.IsNullOrWhiteSpace(listName))
                        {
                            var tempList = spWeb.Lists.TryGetList(listName);

                            if (tempList != null)
                            {
                                var gSettings   = new GridGanttSettings(tempList);
                                var tempDataRow = listIds.Rows.Add();
                                tempDataRow[Id]       = tempList.ID;
                                tempDataRow[ListIcon] = gSettings.ListIcon;
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                hasError = true;
                errMsg.Append(exception.Message);
                Trace.WriteLine(exception);
            }

            return(hasError);
        }
Пример #8
0
        public static void SaveIconToReporting(SPList list)
        {
            try
            {
                var settings = new GridGanttSettings(list);

                var queryExecutor = new QueryExecutor(list.ParentWeb);
                queryExecutor.ExecuteReportingDBNonQuery(
                    @"INSERT INTO ReportListIds (Id, ListIcon) VALUES (@Id, @Icon)", new Dictionary <string, object>
                {
                    { "@Id", list.ID },
                    { "@Icon", settings.ListIcon }
                });
            }
            catch { }
        }
        private static string GetListIcon(SPList spList)
        {
            try
            {
                //Set List Icon
                var gSettings = new GridGanttSettings(spList);
                return(gSettings.ListIcon);
            }
            catch (Exception ex)
            {
                LoggingService.WriteTrace(
                    Area.EPMLiveCore,
                    Categories.EPMLiveCore.Event,
                    TraceSeverity.Verbose,
                    ex.ToString()
                    );
            }

            return(null);
        }
Пример #10
0
        private void BuildParams()
        {
            AppendParam("List", PropList);
            AppendParam("View", PropView);
            AppendParam("FilterField", Page.Request["FilterField1"]);
            AppendParam("FilterValue", Page.Request["FilterValue1"]);
            AppendParam("GridName", FullGridId);
            AppendParam("AGroups", "|");
            AppendParam("Expand", "False");

            var gridGanttSettings = new GridGanttSettings(SpList);

            AppendParam("Start", gridGanttSettings.StartDate);
            AppendParam("Finish", gridGanttSettings.DueDate);
            AppendParam("Percent", gridGanttSettings.Progress);
            AppendParam("WBS", gridGanttSettings.WBS);
            AppendParam("Milestone", gridGanttSettings.Milestone);
            AppendParam("Executive", gridGanttSettings.Executive.ToString());
            AppendParam("Info", gridGanttSettings.Information);
            AppendParam("LType", gridGanttSettings.ItemLink);
            AppendParam("RLists", gridGanttSettings.RollupLists);
            AppendParam("RSites", gridGanttSettings.RollupSites.Replace("\r\n", ","));
            AppendParam("HideNew", gridGanttSettings.HideNewButton.ToString());
            AppendParam("UsePerf", gridGanttSettings.Performance.ToString());
            AppendParam("AllowEdit", gridGanttSettings.AllowEdit.ToString());
            AppendParam("EditDefault", gridGanttSettings.EditDefault.ToString());
            AppendParam("ShowInsert", gridGanttSettings.ShowInsert.ToString());
            AppendParam("UseNew", gridGanttSettings.UseNewMenu.ToString());
            AppendParam("DisableNew", gridGanttSettings.DisableNewItemMod.ToString());
            AppendParam("NewName", gridGanttSettings.NewMenuName);
            AppendParam("UsePopup", gridGanttSettings.UsePopup.ToString());
            AppendParam("Requests", gridGanttSettings.EnableRequests.ToString());

            FullParamList = FullParamList.Substring(1);
            var toEncodeAsBytes = Encoding.ASCII.GetBytes(FullParamList);

            FullParamList = Convert.ToBase64String(toEncodeAsBytes);
        }
Пример #11
0
        public override bool Perform()
        {
            try
            {
                using (var spSite = new SPSite(Web.Site.ID))
                {
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        LogTitle(GetWebInfo(spWeb), 1);

                        SPList spList = spWeb.Lists.TryGetList("Project Center");

                        if (spList != null)
                        {
                            LogTitle(GetListInfo(spList), 2);

                            var settings = new GridGanttSettings(spList)
                            {
                                EnableRequests = true
                            };
                            settings.SaveSettings(spList);

                            LogMessage(string.Empty, MessageKind.SUCCESS, 3);
                        }
                        else
                        {
                            LogMessage("Cannot find the Project Center list.", MessageKind.FAILURE, 2);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LogMessage(e.Message, MessageKind.FAILURE, 2);
            }

            return(true);
        }
Пример #12
0
        private void InitFields()
        {
            var _cSite = SPContext.Current.Site;
            var _cWeb  = SPContext.Current.Web;

            GetQueryStringParameters();
            GetFeatures();

            _currentUserId = _cWeb.CurrentUser.ID.ToString();

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (var s = new SPSite(SPContext.Current.Site.ID))
                {
                    using (var lockedWeb = s.OpenWeb(CoreFunctions.getLockedWeb(Web)))
                    {
                        _createFromLiveTemp      = CoreFunctions.getConfigSetting(lockedWeb, "EPMLiveUseLiveTemplates");
                        _workEngineSvcUrl        = GetWorkengineServiceURL(lockedWeb);
                        _compLevels              = GetCompLevels(lockedWeb);
                        _projectWorkspaceSetting = CoreFunctions.getConfigSetting(lockedWeb, "EPMLiveNewProjectWorkspaceType");

                        if (!string.IsNullOrEmpty(_lstGuid))
                        {
                            GridGanttSettings gSettings = new GridGanttSettings(_cWeb.Lists[new Guid(_lstGuid)]);
                            _newItemName      = (!string.IsNullOrEmpty(_lstGuid) && !string.IsNullOrEmpty(gSettings.NewMenuName)) ? gSettings.NewMenuName : "workspace";
                            _newItemNameLwrCs = _newItemName.ToLower();
                            _listName         = GetListName();
                            _workspaceTitle   = GetWorkspaceTitle();
                            _rListName        = (!string.IsNullOrEmpty(gSettings.RollupLists)) ? gSettings.RollupLists.Split(',')[0].Split('|')[0] : string.Empty;
                            _reqListName      = gSettings.RequestList;
                        }

                        GetDefaultCreateWorkspaceUISettings(lockedWeb);
                    }
                }
            });
        }
Пример #13
0
        public WorkspaceInfoResult RequestWorkspaceInfo(Guid listId)
        {
            var result = new WorkspaceInfoResult();

            var login = SPContext.Current.Web.CurrentUser.LoginName;
            var url   = SPContext.Current.Web.Url;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (var mysite = new SPSite(url))
                {
                    using (var myweb = mysite.OpenWeb())
                    {
                        var list             = myweb.Lists[listId];
                        result.ListName      = list.Title;
                        result.WorkspaceName = string.Empty;

                        try
                        {
                            GridGanttSettings gSettings = new GridGanttSettings(list);
                            result.WorkspaceName        = gSettings.NewMenuName;
                        }
                        catch (Exception ex)
                        {
                            WriteTrace(Area.EPMLiveCore, Categories.EPMLiveCore.LayoutPage, TraceSeverity.VerboseEx, ex.ToString());
                        }

                        if (result.WorkspaceName == string.Empty)
                        {
                            result.WorkspaceName = result.ListName;
                        }
                    }
                }
            });

            return(result);
        }
Пример #14
0
        public WorkspaceInfoResult RequestWorkspaceInfo(Guid listId, int listItemId)
        {
            var result = new WorkspaceInfoResult();

            var login = SPContext.Current.Web.CurrentUser.LoginName;
            var url   = SPContext.Current.Web.Url;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (var mysite = new SPSite(url))
                {
                    using (var myweb = mysite.OpenWeb())
                    {
                        var list      = myweb.Lists[listId];
                        var gSettings = new GridGanttSettings(list);

                        try
                        {
                            var tRollupLists = gSettings.RollupLists.Split(',');
                            result.ListName  = tRollupLists[0].Split('|')[0];
                        }
                        catch (Exception ex)
                        {
                            WriteTrace(Area.EPMLiveCore, Categories.EPMLiveCore.LayoutPage, TraceSeverity.VerboseEx, ex.ToString());
                        }

                        result.WorkspaceName = string.Empty;

                        var li = list.GetItemById(listItemId);
                        result.WorkspaceName = li.Title;
                    }
                }
            });

            return(result);
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            SPWeb web = SPContext.Current.Web;
            {
                StringBuilder sb   = new StringBuilder();
                SPList        list = web.Lists[new Guid(Request.QueryString["List"])];

                foreach (Control ctl in pnlFields.Controls)
                {
                    if (ctl.GetType().ToString() == "System.Web.UI.WebControls.DropDownList")
                    {
                        System.Web.UI.WebControls.DropDownList ddl = (System.Web.UI.WebControls.DropDownList)ctl;
                        if (ddl.SelectedValue != "")
                        {
                            sb.Append(ddl.ID.Substring(3) + "|" + ddl.SelectedValue + "\n");
                        }
                    }
                }

                //if (web.Properties.ContainsKey("epmlivelisttotals-" + System.IO.Path.GetDirectoryName(list.DefaultView.Url)))
                //    web.Properties["epmlivelisttotals-" + System.IO.Path.GetDirectoryName(list.DefaultView.Url)] = sb.ToString();
                //else
                //    web.Properties.Add("epmlivelisttotals-" + System.IO.Path.GetDirectoryName(list.DefaultView.Url), sb.ToString());

                //web.Properties.Update();
                //web.Update();

                GridGanttSettings gSettings = new GridGanttSettings(list);
                gSettings.TotalSettings = sb.ToString();
                gSettings.SaveSettings(list);

                //CoreFunctions.setListSetting(list, "TotalSettings", sb.ToString());

                Microsoft.SharePoint.Utilities.SPUtility.Redirect("listedit.aspx?List=" + list.ID.ToString(), Microsoft.SharePoint.Utilities.SPRedirectFlags.RelativeToLayoutsPage, HttpContext.Current);
            }
        }
        private void HandleNoPostBack(SPList list)
        {
            if (!IsPostBack)
            {
                var gSettings = new GridGanttSettings(list);

                if (gSettings.TotalSettings != string.Empty)
                {
                    var fieldList = gSettings.TotalSettings.Split('\n');
                    foreach (var field in fieldList)
                    {
                        if (field != string.Empty)
                        {
                            var fieldData    = field.Split('|');
                            var dropDownList = (DropDownList)pnlFields.FindControl($"ddl{fieldData[0]}");
                            if (dropDownList != null)
                            {
                                dropDownList.SelectedValue = fieldData[1];
                            }
                        }
                    }
                }
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            SPList list = Web.Lists[new Guid(Request["List"])];

            GridGanttSettings gSettings = new GridGanttSettings(list);

            string[] LookupArray = gSettings.Lookups.Split('|');

            string output = "";

            foreach (string sLookup in LookupArray)
            {
                if (sLookup != "")
                {
                    string[] sLookupInfo = sLookup.Split('^');

                    if (sLookupInfo[0] != Request["field"])
                    {
                        output += "|" + sLookup;
                    }
                }
            }

            if (chkEnabled.Checked)
            {
                output += "|" + Request["field"] + "^" + ddlStyle.SelectedValue + "^" + ddlParentLookup.SelectedValue + "^" + ddlParentLookupField.SelectedValue + "^" + chkSecurity.Checked.ToString().ToLower();
            }

            gSettings.Lookups = output.Trim('|');
            gSettings.SaveSettings(list);

            string lookups = gSettings.Lookups;
            EnhancedLookupConfigValuesHelper x = new EnhancedLookupConfigValuesHelper(lookups);
            List <string> lsSecFields          = x.GetSecuredFields();

            if (lsSecFields.Count > 0)
            {
                string assemblyName = "EPM Live Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5";
                string className    = "EPMLiveCore.ItemSecurityEventReceiver";

                var evts = CoreFunctions.GetListEvents(
                    list,
                    assemblyName,
                    className,
                    new [] {
                    SPEventReceiverType.ItemAdded,
                    SPEventReceiverType.ItemUpdated,
                    SPEventReceiverType.ItemDeleting
                });

                foreach (SPEventReceiverDefinition evt in evts)
                {
                    evt.Delete();
                }

                list.EventReceivers.Add(SPEventReceiverType.ItemAdded, assemblyName, className);
                list.EventReceivers.Add(SPEventReceiverType.ItemUpdated, assemblyName, className);
                list.EventReceivers.Add(SPEventReceiverType.ItemDeleting, assemblyName, className);
                list.Update();
            }
            else if (!gSettings.BuildTeamSecurity)
            {
                string assemblyName = "EPM Live Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5";
                string className    = "EPMLiveCore.ItemSecurityEventReceiver";

                var evts = CoreFunctions.GetListEvents(
                    list,
                    assemblyName,
                    className,
                    new [] {
                    SPEventReceiverType.ItemAdded,
                    SPEventReceiverType.ItemUpdated,
                    SPEventReceiverType.ItemDeleting
                });
                foreach (SPEventReceiverDefinition evt in evts)
                {
                    evt.Delete();
                }

                list.Update();
            }
            Microsoft.SharePoint.Utilities.SPUtility.Redirect("epmlive/ListLookupConfig.aspx?List=" + Request["List"], Microsoft.SharePoint.Utilities.SPRedirectFlags.RelativeToLayoutsPage, System.Web.HttpContext.Current);
        }
        public DataTable GetMenuItems(Guid siteId, Guid webId, Guid listId, int itemId, int userId,
                                      out Dictionary <string, string> diagnosticInfo)
        {
            var info = new Dictionary <string, string>();

            var dataTable = new DataTable();

            dataTable.Columns.Add("Title", typeof(string));
            dataTable.Columns.Add("Command", typeof(string));
            dataTable.Columns.Add("ImageUrl", typeof(string));
            dataTable.Columns.Add("Kind", typeof(string));

            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                using (var site = new SPSite(siteId))
                {
                    using (SPWeb web = site.OpenWeb(webId))
                    {
                        info.Add("Web", web.Url);

                        SPUser user           = web.AllUsers.GetByID(userId);
                        SPUserToken userToken = user.UserToken;

                        info.Add("Username", user.LoginName);
                        info.Add("User", user.Name);

                        Task <object[]> t1 = Task.Factory.StartNew(() =>
                        {
                            Dictionary <string, string> di;

                            var result = new Tuple <string, string, string, string, bool>[] { };

                            try
                            {
                                using (var spSite = new SPSite(siteId, userToken))
                                {
                                    using (SPWeb spWeb = spSite.OpenWeb(webId))
                                    {
                                        SPList list = spWeb.Lists.GetList(listId, true);
                                        GridGanttSettings gSettings = ListCommands.GetGridGanttSettings(list);
                                        result = GetGeneralActions(gSettings.UsePopup, list, gSettings.EnableFancyForms, out di);
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                di = new Dictionary <string, string> {
                                    { "General Actions Exception", e.Message }
                                };
                            }

                            return(new object[] { result, di });
                        });

                        Task <object[]> t2 = Task.Factory.StartNew(() =>
                        {
                            Dictionary <string, string> di;

                            var result = new Tuple <string, string, string, string, bool>[] { };

                            try
                            {
                                using (var spSite = new SPSite(siteId, userToken))
                                {
                                    using (SPWeb spWeb = spSite.OpenWeb(webId))
                                    {
                                        SPList list = spWeb.Lists.GetList(listId, true);
                                        result      = GetPlannerActions(list, out di);
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                di = new Dictionary <string, string> {
                                    { "Planner Actions Exception", e.Message }
                                };
                            }

                            return(new object[] { result, di });
                        });

                        Task <object[]> t3 = Task.Factory.StartNew(() =>
                        {
                            Dictionary <string, string> di;

                            var result = new Tuple <string, string, string, string, bool>[] { };

                            try
                            {
                                using (var spSite = new SPSite(siteId, userToken))
                                {
                                    using (SPWeb spWeb = spSite.OpenWeb(webId))
                                    {
                                        SPList list     = spWeb.Lists.GetList(listId, true);
                                        SPListItem item = list.GetItemById(itemId);

                                        result = GetSocialActions(item, ListCommands.GetGridGanttSettings(list), out di);
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                di = new Dictionary <string, string> {
                                    { "Social Actions Exception", e.Message }
                                };
                            }

                            return(new object[] { result, di });
                        });

                        Task <object[]> t4 = Task.Factory.StartNew(() =>
                        {
                            Dictionary <string, string> di;

                            var result = new Tuple <string, string, string, string, bool>[] { };

                            try
                            {
                                using (var spSite = new SPSite(siteId, userToken))
                                {
                                    using (SPWeb spWeb = spSite.OpenWeb(webId))
                                    {
                                        SPList list     = spWeb.Lists.GetList(listId, true);
                                        SPListItem item = list.GetItemById(itemId);

                                        result = GetWorkspaceActions(item, out di);
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                di = new Dictionary <string, string> {
                                    { "Workspace Actions Exception", e.Message }
                                };
                            }

                            return(new object[] { result, di });
                        });

                        Task <object[]> t5 = Task.Factory.StartNew(() =>
                        {
                            Dictionary <string, string> di;

                            var result = new Tuple <string, string, string, string, bool>[] { };

                            try
                            {
                                using (var spSite = new SPSite(siteId, userToken))
                                {
                                    using (SPWeb spWeb = spSite.OpenWeb(webId))
                                    {
                                        SPList list = spWeb.Lists.GetList(listId, true);
                                        result      = GetPFEActions(list, out di);
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                di = new Dictionary <string, string> {
                                    { "PFE Actions Exception", e.Message }
                                };
                            }

                            return(new object[] { result, di });
                        });

                        var actions = new List <Tuple <string, string, string, string, bool> >();

                        foreach (var t in new[] { t1, t2, t3, t4, t5 })
                        {
                            object[] result = t.Result;

                            var et     = new Tuple <string, string, string, string, bool>(null, null, null, null, false);
                            var tuples = (Tuple <string, string, string, string, bool>[])(result[0] ?? new[] { et });

                            actions.AddRange(tuples);

                            var di = result[1] as Dictionary <string, string>;

                            if (di == null)
                            {
                                continue;
                            }

                            foreach (var pair in di)
                            {
                                info.Add(pair.Key, pair.Value);
                            }
                        }

                        if (!actions.Any())
                        {
                            return;
                        }

                        string lastTitle = string.Empty;

                        Tuple <string, string, string, string, bool> lastAction = actions.Last();

                        string sepItem = lastAction.Item1;
                        if (!string.IsNullOrEmpty(sepItem) && sepItem.Equals("--SEP--"))
                        {
                            actions.Remove(lastAction);
                        }

                        foreach (var action in actions)
                        {
                            if (!action.Item5)
                            {
                                continue;
                            }
                            if (action.Item1.Equals("--SEP--") && action.Item1.Equals(lastTitle))
                            {
                                continue;
                            }

                            lastTitle = action.Item1;

                            DataRow row = dataTable.NewRow();

                            row["Title"]    = action.Item1;
                            row["Command"]  = action.Item2;
                            row["ImageUrl"] = action.Item3;
                            row["Kind"]     = action.Item4;

                            dataTable.Rows.Add(row);
                        }
                    }
                }
            });

            diagnosticInfo = info;

            return(dataTable);
        }
Пример #19
0
        private void UpdateUI(Guid siteId, Guid webId)
        {
            SPWebCollection webCollection;

            using (SPSite spSite = new SPSite(siteId))
            {
                using (SPWeb spWeb = spSite.OpenWeb(webId))
                {
                    LogTitle(GetWebInfo(spWeb), 1);

                    try
                    {
                        string masterUrl = spWeb.MasterUrl;
                        string fileName  = Path.GetFileName(masterUrl).ToLower();

                        if (!fileName.Equals("uplandv5.master"))
                        {
                            var masterpages = new[]
                            {
                                "epmlive", "epmlivemasterv5blue", "masterv43lightbluetop",
                                "masterv43lightbluews", "wetoplevel",
                                "weworkspace", "weworkspacetopnav"
                            };

                            bool contains = false;
                            foreach (string masterpage in masterpages.Where(mp => (mp + ".master").Equals(fileName)))
                            {
                                contains = true;
                            }

                            if (contains)
                            {
                                ResetFeature(new Guid("046f0200-30e5-4545-b00f-c8c73aef9f0e"), "EPM Live Upland UI",
                                             spWeb);
                                ChangeMasterPage("UplandV5", spWeb);
                            }
                            else
                            {
                                LogMessage("The current default MasterPage is not one of EPM Live MasterPage.",
                                           MessageKind.SKIPPED, 2);
                            }
                        }
                        else
                        {
                            LogMessage("The default MasterPage is already set to UplandV5.", MessageKind.SKIPPED, 2);
                        }

                        SPList spList = spWeb.Lists.TryGetList("Team");
                        if (spList != null)
                        {
                            var settings = new GridGanttSettings(spList)
                            {
                                HideNewButton = true
                            };
                            settings.SaveSettings(spList);
                        }
                    }
                    catch (Exception exception)
                    {
                        LogMessage(exception.Message, MessageKind.FAILURE, 3);
                    }
                    finally
                    {
                        webCollection = spWeb.Webs;
                    }
                }
            }

            if (webCollection == null)
            {
                return;
            }

            foreach (SPWeb spWeb in webCollection)
            {
                try
                {
                    UpdateUI(siteId, spWeb.ID);
                }
                catch (Exception ex)
                {
                    LogMessage(ex.Message, MessageKind.FAILURE, 3);
                }
                finally { if (spWeb != null)
                          {
                              spWeb.Dispose();
                          }
                }
            }
        }
Пример #20
0
        /// <summary>
        /// Gets the field properties.
        /// </summary>
        /// <param name="spList">The sp list.</param>
        /// <returns></returns>
        internal static Dictionary <string, Dictionary <string, string> > GetFieldProperties(SPList spList)
        {
            GridGanttSettings gSettings = new GridGanttSettings(spList);

            return(ListDisplayUtils.ConvertFromString(gSettings.DisplaySettings));
        }
Пример #21
0
        public void AddBuildTeamSecurityGroups_TypeNotGuest_UpdatesSecurityGroups()
        {
            // Arrange
            const SPRoleType type    = SPRoleType.Administrator;
            var buildTeamPermissions = "1~2~3|1~2~3";
            var methodHit            = 0;
            var settingsDictionary   = new Dictionary <int, string>()
            {
                [33] = buildTeamPermissions
            };

            ShimCoreFunctions.getListSettingStringSPList = (_, __) =>
            {
                var settings = string.Empty;

                for (var index = 0; index <= 50; index++)
                {
                    if (settingsDictionary.ContainsKey(index))
                    {
                        settings += $"{settingsDictionary[index]};";
                    }
                    else
                    {
                        settings += $"{DummyString};";
                    }
                }
                return(settings.Replace(";", "\n"));
            };
            ShimSPRoleDefinition.AllInstances.TypeGet = _ => type;
            ShimSPRoleDefinitionBindingCollection.AllInstances.AddSPRoleDefinition = (_, __) =>
            {
                validations += 1;
            };
            ShimSecurityUpdate.AllInstances.AddNewItemLvlPermSPListItemSPWebSPRoleAssignment = (_, _1, _2, _3) =>
            {
                validations += 1;
            };
            ShimSPGroup.AllInstances.UsersGet = _ => new ShimSPUserCollection();
            ShimSPBaseCollection.AllInstances.GetEnumerator = _ =>
            {
                methodHit += 1;
                if (methodHit.Equals(One))
                {
                    var roleAssignments = new List <SPRoleAssignment>()
                    {
                        new ShimSPRoleAssignment()
                        {
                            MemberGet = () => new ShimSPGroup()
                            {
                                NameGet       = () => "Owner",
                                AddUserSPUser = __ =>
                                {
                                    validations += 1;
                                },
                                Update = () =>
                                {
                                    validations += 1;
                                }
                            }.Instance
                        }
                    }.GetEnumerator();
                    return(roleAssignments);
                }
                var users = new List <SPUser>()
                {
                }.GetEnumerator();
                return(users);
            };

            var ganttSettings = new GridGanttSettings(spList);

            // Act
            privateObject.Invoke(
                AddBuildTeamSecurityGroupsMethodName,
                publicInstance,
                new object[]
            {
                spWeb.Instance,
                ganttSettings,
                spListItem.Instance
            });

            // Assert
            validations.ShouldBe(3);
        }
        public void execute(SPSite site, SPWeb web, Guid listId, int itemId, int userid, string data)
        {
            SPList            list        = null;
            SPListItem        li          = null;
            GridGanttSettings settings    = null;
            List <string>     cNewGrps    = null;
            List <string>     fields      = null;
            SPUser            orignalUser = null;
            EnhancedLookupConfigValuesHelper valueHelper = null;
            SPList             lookupPrntList            = null;
            GridGanttSettings  prntListSettings          = null;
            SPFieldLookupValue lookupVal  = null;
            SPListItem         targetItem = null;

            try
            {
                list     = web.Lists[listId];
                li       = list.GetItemById(itemId);
                settings = new GridGanttSettings(list);
                cNewGrps = new List <string>();
                bool isSecure = false;
                try
                {
                    isSecure = settings.BuildTeamSecurity;
                }
                catch { }

                orignalUser = web.AllUsers.GetByID(userid);

                string safeTitle = !string.IsNullOrEmpty(li.Title) ? GetSafeGroupTitle(li.Title) : string.Empty;

                if (string.IsNullOrEmpty(safeTitle) && list.BaseTemplate == SPListTemplateType.DocumentLibrary)
                {
                    safeTitle = GetSafeGroupTitle(li.Name); //Assign Name instead of Title - This should perticularly happen with Document libraries.
                }
                if (isSecure)
                {
                    if (!li.HasUniqueRoleAssignments)
                    {
                        web.AllowUnsafeUpdates = true;
                        safeGroupTitle         = safeTitle;

                        safeTitle = GetIdenticalGroupName(site.ID, web.ID, safeTitle, 0);

                        // step 1 perform actions related to "parent item"
                        // ===============================================
                        Dictionary <string, SPRoleType> pNewGrps = null;
                        try
                        {
                            pNewGrps = AddBasicSecurityGroups(web, safeTitle, orignalUser, li);

                            li.BreakRoleInheritance(false);

                            foreach (KeyValuePair <string, SPRoleType> group in pNewGrps)
                            {
                                SPGroup g = web.SiteGroups[group.Key];
                                AddNewItemLvlPerm(li, web, group.Value, g);
                                g = null;
                            }

                            AddBuildTeamSecurityGroups(web, settings, li);
                        }
                        catch { }
                        finally
                        {
                            pNewGrps = null;
                        }
                    }
                }


                // step 2 perform actions related to "child item"
                // ====================================
                // find lookups that has security enabled
                string lookupSettings = settings.Lookups;
                //string rawValue = "Region^dropdown^none^none^xxx|State^autocomplete^Region^Region^xxx|City^autocomplete^State^State^xxx";
                valueHelper = new EnhancedLookupConfigValuesHelper(lookupSettings);

                if (valueHelper == null)
                {
                    return;
                }

                fields = valueHelper.GetSecuredFields();

                bool bHasLookup = false;

                foreach (string fld in fields)
                {
                    SPFieldLookup lookup = null;
                    try
                    {
                        lookup = list.Fields.GetFieldByInternalName(fld) as SPFieldLookup;
                    }
                    catch { }

                    if (lookup == null)
                    {
                        continue;
                    }

                    lookupPrntList   = web.Lists[new Guid(lookup.LookupList)];
                    prntListSettings = new GridGanttSettings(lookupPrntList);
                    string sVal = string.Empty;
                    try
                    {
                        sVal = li[fld].ToString();
                    }
                    catch { }
                    if (!string.IsNullOrEmpty(sVal))
                    {
                        bHasLookup = true;
                        break;
                    }
                }
                if (bHasLookup)
                {
                    // has security fields
                    if (fields.Count > 0)
                    {
                        // if the list is not a security list itself
                        if (isSecure)
                        {
                            li.BreakRoleInheritance(false);
                        }

                        foreach (string fld in fields)
                        {
                            SPFieldLookup lookup = null;
                            try
                            {
                                lookup = list.Fields.GetFieldByInternalName(fld) as SPFieldLookup;
                            }
                            catch { }

                            if (lookup == null)
                            {
                                continue;
                            }

                            lookupPrntList   = web.Lists[new Guid(lookup.LookupList)];
                            prntListSettings = new GridGanttSettings(lookupPrntList);
                            bool isEnableSecurity = false;
                            bool isParentSecure   = false;
                            try
                            {
                                isParentSecure = prntListSettings.BuildTeamSecurity;
                            }
                            catch { }

                            string[]  LookupArray = settings.Lookups.Split('|');
                            string[]  sLookupInfo = null;
                            Hashtable hshLookups  = new Hashtable();
                            foreach (string sLookup in LookupArray)
                            {
                                if (sLookup != "")
                                {
                                    sLookupInfo = sLookup.Split('^');
                                    hshLookups.Add(sLookupInfo[0], sLookupInfo);
                                }
                            }
                            try
                            {
                                if (sLookupInfo != null && sLookupInfo[4].ToLower() == "true")
                                {
                                    isEnableSecurity = true;
                                }
                                else
                                {
                                    isEnableSecurity = false;
                                }
                            }
                            catch { isEnableSecurity = false; }

                            // skip fields with empty lookup values
                            string sVal = string.Empty;
                            try { sVal = li[fld].ToString(); }
                            catch { }
                            if (string.IsNullOrEmpty(sVal))
                            {
                                continue;
                            }

                            lookupVal  = new SPFieldLookupValue(sVal.ToString());
                            targetItem = lookupPrntList.GetItemById(lookupVal.LookupId);
                            if (!targetItem.HasUniqueRoleAssignments)
                            {
                                continue;
                            }
                            else
                            {
                                //EPML-4422: When a project is not using unique security, and a child list like tasks is set to Inherit security from the project lookup, It sets the task to unique, but does not add any groups. It should not get set to Unique.
                                if (!isSecure && isParentSecure && isEnableSecurity)
                                {
                                    web.AllowUnsafeUpdates = true;
                                    li.BreakRoleInheritance(false);
                                }
                            }

                            SPRoleAssignmentCollection raCol = targetItem.RoleAssignments;
                            string itemMemberGrp             = "Member";
                            foreach (SPRoleAssignment ra in raCol)
                            {
                                // add their groups to this item but change permission lvl
                                if (ra.Member.Name.Contains(itemMemberGrp))
                                {
                                    SPRoleAssignment newRa  = new SPRoleAssignment(ra.Member);
                                    SPRoleDefinition newDef = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
                                    newRa.RoleDefinitionBindings.Add(newDef);
                                    li.RoleAssignments.Add(newRa);
                                }
                                else
                                {
                                    li.RoleAssignments.Add(ra);
                                }

                                cNewGrps.Add(ra.Member.Name);
                            }
                        }
                    }
                }
                ProcessSecurity(site, list, li, userid);

                // we wait until all groups have been created to createworkspace
                // only if there isn't a current process creating ws
                WorkspaceTimerjobAgent.QueueWorkspaceJobOnHoldForSecurity(site.ID, web.ID, list.ID, li.ID);
            }

            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                list             = null;
                li               = null;
                lookupPrntList   = null;
                prntListSettings = null;
                settings         = null;
                cNewGrps         = null;
                fields           = null;
                orignalUser      = null;
                valueHelper      = null;
                lookupVal        = null;
                targetItem       = null;
                fields           = null;
                if (web != null)
                {
                    web.Dispose();
                }
                if (site != null)
                {
                    site.Dispose();
                }
                data = null;
            }
        }
        public void AddBuildTeamSecurityGroups(SPWeb ew, GridGanttSettings settings, SPListItem eI)
        {
            string teamPerm = string.Empty;

            try
            {
                teamPerm = settings.BuildTeamPermissions;
            }
            catch { }
            if (!string.IsNullOrEmpty(teamPerm))
            {
                string[] strOuter = settings.BuildTeamPermissions.Split(new string[] { "|~|" }, StringSplitOptions.None);
                //SPListItem eI = ew.Lists[base.ListUid].GetItemById(base.ItemID);

                foreach (string strInner in strOuter)
                {
                    string[]         strInnerMost = strInner.Split('~');
                    SPGroup          g            = null;
                    SPRoleDefinition r            = null;

                    try
                    {
                        g = ew.SiteGroups.GetByID(Convert.ToInt32(strInnerMost[0]));
                        r = ew.RoleDefinitions.GetById(Convert.ToInt32(strInnerMost[1]));
                    }
                    catch { }
                    if (g != null && r != null)
                    {
                        if (r.Type != SPRoleType.Guest)
                        {
                            SPRoleAssignment assign = new SPRoleAssignment(g);
                            assign.RoleDefinitionBindings.Add(r);
                            AddNewItemLvlPerm(eI, ew, assign);

                            //Adding users with Full Control permission levels to Owners group.
                            if (r.Type == SPRoleType.Administrator) //Full Control Permission Level
                            {
                                //Add users to Owners group.
                                SPUserCollection groupUsers = g.Users;

                                foreach (SPRoleAssignment role in eI.RoleAssignments)
                                {
                                    try
                                    {
                                        if (role.Member.GetType() == typeof(SPGroup))
                                        {
                                            SPGroup group = (SPGroup)role.Member;
                                            if (group.Name.EndsWith("Owner"))
                                            {
                                                try
                                                {
                                                    foreach (SPUser user in groupUsers)
                                                    {
                                                        group.AddUser(user);
                                                    }
                                                    group.Update();
                                                }
                                                catch { }
                                            }
                                        }
                                    }
                                    catch { }
                                }
                            }
                        }
                        else
                        {
                            // create our custom limited access role
                            SPRoleDefinition roleDef = new SPRoleDefinition();

                            try
                            {
                                roleDef = ew.RoleDefinitions["Limited Access Permission"];
                            }
                            catch (SPException)
                            {
                                ew.AllowUnsafeUpdates = true;
                                // give it a name and description
                                roleDef.Name        = "Limited Access Permission";
                                roleDef.Description = "Identical to standard Limited Access rights. Used to provide access to parent objects of uniquely permissioned content";
                                // apply the base permissions required
                                roleDef.BasePermissions = SPBasePermissions.ViewFormPages | SPBasePermissions.Open | SPBasePermissions.BrowseUserInfo | SPBasePermissions.UseClientIntegration | SPBasePermissions.UseRemoteAPIs;
                                // add it to the web
                                ew.RoleDefinitions.Add(roleDef);
                                ew.Update();
                            }

                            try
                            {
                                SPRoleAssignment assign = new SPRoleAssignment(g);
                                assign.RoleDefinitionBindings.Add(roleDef);
                                AddNewItemLvlPerm(eI, ew, assign);
                            }
                            catch { }
                        }
                    }
                }
            }

            //return createdGrps;
        }
Пример #24
0
        public static RibbonProperties GetRibbonProps(SPList list)
        {
            RibbonProperties rp = new RibbonProperties();

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        GridGanttSettings gSettings = GetGridGanttSettings(list);

                        string pubPC  = EPMLiveCore.CoreFunctions.getLockConfigSetting(web, "EPMLivePublisherProjectCenter", false);
                        string pubTC  = EPMLiveCore.CoreFunctions.getLockConfigSetting(web, "EPMLivePublisherTaskCenter", false);
                        bool foundmpp = false;

                        try
                        {
                            SPDocumentLibrary lib = (SPDocumentLibrary)web.Lists["Project Schedules"];
                            if (lib != null)
                            {
                                if (lib.ContentTypesEnabled)
                                {
                                    foreach (SPContentType ct in lib.ContentTypes)
                                    {
                                        string template = ct.DocumentTemplateUrl;
                                        if (template.Substring(template.Length - 3, 3) == "mpp")
                                        {
                                            foundmpp = true;
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    string template = lib.DocumentTemplateUrl;
                                    if (template.Substring(template.Length - 3, 3) == "mpp")
                                    {
                                        foundmpp = true;
                                    }
                                }
                            }
                        }
                        catch { }

                        if (gSettings.BuildTeam && list.Fields.GetFieldByInternalName("AssignedTo") != null)
                        {
                            if (list.DoesUserHavePermissions(SPBasePermissions.EditListItems))
                            {
                                rp.bBuildTeam = true;
                            }
                        }

                        bool.TryParse(EPMLiveCore.CoreFunctions.getConfigSetting(web, "EPMLiveDisablePublishing"), out rp.bDisableProject);
                        bool.TryParse(EPMLiveCore.CoreFunctions.getConfigSetting(web, "EPMLiveDisablePlanners"), out rp.bDisablePlan);

                        if (site.Features[new Guid("158c5682-d839-4248-b780-82b4710ee152")] != null)
                        {
                            ArrayList arr = new ArrayList(EPMLiveCore.CoreFunctions.getConfigSetting(site.RootWeb, "EPKLists").ToLower().Split(','));
                            if (arr.Contains(list.Title.ToLower()))
                            {
                                string menus = "";
                                menus        = EPMLiveCore.CoreFunctions.getConfigSetting(site.RootWeb, "EPK" + list.Title.Replace(" ", "") + "_menus");
                                if (menus == "")
                                {
                                    menus = EPMLiveCore.CoreFunctions.getConfigSetting(site.RootWeb, "EPKMenus");
                                }

                                rp.aEPKButtons = new ArrayList(menus.Split('|'));

                                string noactivex = "";
                                noactivex        = EPMLiveCore.CoreFunctions.getConfigSetting(site.RootWeb, "EPK" + list.Title.Replace(" ", "") + "_nonactivexs");
                                if (noactivex == "")
                                {
                                    noactivex = EPMLiveCore.CoreFunctions.getConfigSetting(site.RootWeb, "epknonactivexs");
                                }

                                rp.aEPKActivex = new ArrayList(noactivex.Split('|'));
                            }
                        }
                    }
                }
            });
            return(rp);
        }
Пример #25
0
        private static void iSetGridRowEdit(ref XmlDocument doc, SPWeb oWeb, XmlDocument DocIn)
        {
            Guid ListId = new Guid(DocIn.FirstChild.Attributes["listid"].Value);
            int  itemid = int.Parse(DocIn.FirstChild.Attributes["itemid"].Value);

            SPList     list      = oWeb.Lists[ListId];
            SPListItem li        = list.GetItemById(itemid);
            var        gSettings = new GridGanttSettings(list);

            oWeb.AllowUnsafeUpdates = true;

            foreach (XmlNode nd in DocIn.FirstChild.SelectNodes("//Field"))
            {
                SPField oField = null;
                try
                {
                    if (nd.Attributes["Name"].Value == "FState")
                    {
                        oField = list.Fields.GetFieldByInternalName("State");
                    }
                    else
                    {
                        oField = list.Fields.GetFieldByInternalName(nd.Attributes["Name"].Value);
                    }
                }
                catch { }
                if (oField != null)
                {
                    string sFieldValue = System.Web.HttpUtility.UrlDecode(nd.InnerText);

                    switch (oField.Type)
                    {
                    case SPFieldType.User:
                        if (nd.InnerText != "")
                        {
                            string[] sUVals = sFieldValue.Split(';');
                            SPFieldUserValueCollection uvc = new SPFieldUserValueCollection();
                            foreach (string sVal in sUVals)
                            {
                                SPFieldUserValue lv = new SPFieldUserValue(oWeb, sVal);
                                uvc.Add(lv);
                            }
                            li[oField.Id] = uvc;
                        }
                        else
                        {
                            li[oField.Id] = null;
                        }
                        break;

                    case SPFieldType.Lookup:
                        // Need to check for null / empty value otherwise it will display invalid lookup value error message
                        // when we click outside the grid after editing lookup field value by double clicking on the field.
                        if (!string.IsNullOrEmpty(nd.InnerText))
                        {
                            string[] sVals = sFieldValue.Split(';');
                            SPFieldLookupValueCollection lvc = new SPFieldLookupValueCollection();
                            foreach (string sVal in sVals)
                            {
                                SPFieldLookupValue lv = new SPFieldLookupValue(sVal);
                                lvc.Add(lv);
                            }
                            li[oField.Id] = lvc;
                        }
                        else
                        {
                            li[oField.Id] = null;
                        }
                        break;

                    case SPFieldType.MultiChoice:
                        li[oField.Id] = sFieldValue.Replace(";", ";#");
                        break;

                    case SPFieldType.Currency:
                        if (nd.InnerText == "")
                        {
                            li[oField.Id] = null;
                        }
                        else
                        {
                            li[oField.Id] = sFieldValue;
                        }
                        break;

                    case SPFieldType.Number:
                        SPFieldNumber fNum = (SPFieldNumber)oField;
                        if (fNum.ShowAsPercentage)
                        {
                            try
                            {
                                li[oField.Id] = float.Parse(sFieldValue, CultureInfo.InvariantCulture) / 100;
                            }
                            catch { li[oField.Id] = null; }
                        }
                        else
                        {
                            if (nd.InnerText == "")
                            {
                                li[oField.Id] = null;
                            }
                            else
                            {
                                li[oField.Id] = sFieldValue;
                            }
                        }
                        break;

                    case SPFieldType.DateTime:
                        if (nd.InnerText == "")
                        {
                            li[oField.Id] = null;
                        }
                        else
                        {
                            li[oField.Id] = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds(double.Parse(sFieldValue));
                        }
                        break;

                    default:
                        li[oField.Id] = sFieldValue;
                        break;
                    }
                }
            }

            try
            {
                if (gSettings.EnableWorkList)
                {
                    if (li.Fields.ContainsField(FieldCompleteName))
                    {
                        if ((bool)li[FieldCompleteName])
                        {
                            li[FieldCompletePercentName] = 1;
                            if (list.Title == ListProjectCenterName)
                            {
                                li[FieldProjectCompletePercentName] = 1;
                            }
                        }
                    }
                }
            }
            catch {}

            li.Update();

            iGetRowValue(ref doc, oWeb, DocIn, list, li, true);
        }
Пример #26
0
        protected void Page_Load(object sender, EventArgs e)
        {
            SPWeb  web    = SPContext.Current.Web;
            string resUrl = "";

            web.Site.CatchAccessDeniedException = false;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb aweb = site.OpenWeb(web.ID))
                    {
                        resUrl = CoreFunctions.getConfigSetting(aweb, "EPMLiveResourceURL", true, false);
                    }
                }
            });

            //bool canManageAGroup = false;
            SPListItem oLi      = null;
            SPList     oList    = null;
            bool       bUseTeam = false;

            Guid listid = Guid.Empty;
            int  itemid = 0;

            try
            {
                listid = new Guid(Request["listid"]);
                itemid = int.Parse(Request["id"]);

                oList = web.Lists[listid];
                oLi   = oList.GetItemById(itemid);
                GridGanttSettings gSettings = new GridGanttSettings(oList);
                bUseTeam = gSettings.BuildTeam;
            }
            catch (Exception)
            {
                try
                {
                    APITeam.VerifyProjectTeamWorkspace(web, out itemid, out listid);
                    if (itemid > 0 && listid != Guid.Empty)
                    {
                        try
                        {
                            while (!web.IsRootWeb) //Inherit | Open
                            {
                                if (web.IsRootWeb)
                                {
                                    break;
                                }
                                web = web.ParentWeb;
                            }

                            oList = web.Lists[listid];
                            GridGanttSettings gSettings = ListCommands.GetGridGanttSettings(oList);
                            bUseTeam = gSettings.BuildTeam;
                            oLi      = oList.GetItemById(itemid);
                        }
                        catch { }
                    }
                }
                catch { }
            }

            if (bUseTeam)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite tSite = new SPSite(web.Site.ID))
                    {
                        using (SPWeb tWeb = tSite.OpenWeb(web.ID))
                        {
                            SPListItem spListItem = null;
                            SPList tList          = tWeb.Lists[listid];
                            try
                            {
                                spListItem = tList.GetItemById(itemid);
                            }
                            catch (ArgumentException ex)
                            {
                                throw new SPException("The associated project does not exist or has been deleted.", ex);
                            }
                            web.Site.CatchAccessDeniedException = false;

                            foreach (SPRoleAssignment assn in spListItem.RoleAssignments)
                            {
                                if (assn.Member.GetType() == typeof(Microsoft.SharePoint.SPGroup))
                                {
                                    try
                                    {
                                        SPGroup group = web.SiteGroups.GetByID(assn.Member.ID);

                                        if (group.CanCurrentUserEditMembership)
                                        {
                                            string[] sG = group.Name.Split(' ');
                                            if (sG[sG.Length - 1] == "Member")
                                            {
                                                sDefaultGroup = group.ID.ToString();
                                            }

                                            bCanEditTeam = "true";
                                        }
                                    }
                                    catch { }
                                }
                            }
                        }
                    }
                });
            }
            else
            {
                foreach (SPGroup g in web.Groups)
                {
                    string[] sG = g.Name.Split(' ');
                    if (sG[sG.Length - 1] == "Member")
                    {
                        sDefaultGroup = g.ID.ToString();
                    }

                    if (g.CanCurrentUserEditMembership)
                    {
                        bCanEditTeam = "true";
                    }
                }
            }

            if (itemid > 0 && listid != Guid.Empty && PfeData.ConnectionProvider.AllowDatabaseConnections(web))
            {
                // collect pfe database project id for processing in UI part
                var repository = new PfeData.ProjectRepository();
                projectIdInPfe = repository.FindProjectId(web, listid, itemid);
            }

            if (web.Features[new Guid("84520a2b-8e2b-4ada-8f48-60b138923d01")] == null && !bUseTeam)
            {
                sDisable = "_spBodyOnLoadFunctionNames.push(\"ShowDisable\");";
                SPList teamlist = web.Lists["Team"];
                //if(web.DoesUserHavePermissions(SPBasePermissions.ManagePermissions))
                //{
                //    bCanEditTeam = "true";
                //}
            }
            else
            {
                try
                {
                    using (SPSite rsite = new SPSite(resUrl))
                    {
                        using (SPWeb rweb = rsite.OpenWeb())
                        {
                            SPList list = rweb.Lists["Resources"];
                            //DataTable dtTemp = list.Items.GetDataTable();
                            bCanAccessResourcePool = "true";
                            if (list.DoesUserHavePermissions(SPBasePermissions.AddListItems))
                            {
                                bCanAddResource = "true";
                                sNewResUrl      = list.Forms[PAGETYPE.PAGE_NEWFORM].ServerRelativeUrl;
                            }
                        }
                    }
                }
                catch { }

                XmlDocument doc = new XmlDocument();
                doc.LoadXml("<Grid/>");



                if (bUseTeam)
                {
                    try
                    {
                        if (oLi.DoesUserHavePermissions(SPBasePermissions.EditListItems))
                        {
                            bCanEditTeam = "true";
                        }

                        XmlAttribute attr = doc.CreateAttribute("WebId");
                        attr.Value = Convert.ToString(web.ID);
                        doc.FirstChild.Attributes.Append(attr);

                        attr       = doc.CreateAttribute("ListId");
                        attr.Value = Convert.ToString(listid);
                        doc.FirstChild.Attributes.Append(attr);

                        attr       = doc.CreateAttribute("ItemId");
                        attr.Value = Convert.ToString(itemid);
                        doc.FirstChild.Attributes.Append(attr);
                    }
                    catch
                    {
                    }
                }
                else
                {
                    SPList teamlist = web.Lists.TryGetList("Team");

                    if (teamlist == null)
                    {
                        web.AllowUnsafeUpdates = true;
                        web.Lists.Add("Team", "Use this list to manage your project team", SPListTemplateType.GenericList);
                        teamlist = web.Lists.TryGetList("Team");
                        try
                        {
                            teamlist.Fields.Add("ResID", SPFieldType.Number, false);
                            teamlist.Update();
                        }
                        catch { }
                    }
                }

                sLayoutParam = HttpUtility.HtmlEncode(doc.OuterXml);

                if (bCanEditTeam == "true")
                {
                    sResPool = Properties.Resources.txtBuildTeamResPool.Replace("#LayoutParam#", sLayoutParam).Replace("#DataParam#", sLayoutParam);
                    sResGrid = @"TreeGrid(   { 
                    Layout:{ Url:""../../_vti_bin/WorkEngine.asmx"",Timeout:0, Method:""Soap"",Function:""Execute"",Namespace:""workengine.com"",Param:{Function:""GetResourceGridLayout"",Dataxml:""" + sLayoutParam + @""" } } ,
                    Data:{ Url:""../../_vti_bin/WorkEngine.asmx"",Timeout:0, Method:""Soap"",Function:""Execute"",Namespace:""workengine.com"",Param:{Function:""GetResourceGridData"",Dataxml:""" + sLayoutParam + @""" } }, 
                    Debug:"""",SuppressMessage:""3""
                    }, 
	                ""divResPool"" );"    ;
                }
            }

            sUserInfoList = web.SiteUserInfoList.ID.ToString().ToUpper();

            if (Request["isDlg"] == "1")
            {
                sClose = "SP.SOD.execute('SP.UI.Dialog.js', 'SP.UI.ModalDialog.commonModalDialogClose', SP.UI.DialogResult.OK, '');";
            }
            else
            {
                if (String.IsNullOrEmpty(Request["Source"]))
                {
                    sClose = "location.href='" + ((web.ServerRelativeUrl == "/") ? "" : web.ServerRelativeUrl) + "'";
                }
                else
                {
                    sClose = "location.href='" + Request["Source"] + "'";
                }
            }
        }
Пример #27
0
        private string GetNewItemButtonLists()
        {
            SPWeb myworkWeb = SPContext.Current.Web;

            string newItemButtonLists = string.Empty;
            var    newItemLists       = new List <string>();

            List <myworksettings.MWList> excludedMyWorkLists =
                myworksettings.GetMyWorkListsFromDb(myworkWeb, EPMLiveCore.API.MyWork.GetArchivedWebs(myworkWeb.Site.ID));

            if (!UseCentralizedSettings)
            {
                foreach (
                    string myWorkSelectedList in
                    MyWorkSelectedLst.Where(myWorkSelectedList => !string.IsNullOrEmpty(myWorkSelectedList)))
                {
                    newItemLists.Add(myWorkSelectedList);
                    excludedMyWorkLists.RemoveAll(l => l.Name.Equals(myWorkSelectedList));
                }

                foreach (string selectedList in SelectedLst.Where(selectedList => !string.IsNullOrEmpty(selectedList))
                         )
                {
                    newItemLists.Add(selectedList);
                    excludedMyWorkLists.RemoveAll(l => l.Name.Equals(selectedList));
                }
            }
            else
            {
                SPWeb theWeb    = SPContext.Current.Web;
                Guid  lockedWeb = CoreFunctions.getLockedWeb(theWeb);

                using (SPWeb configWeb = (theWeb.ID != lockedWeb
                    ? theWeb.Site.OpenWeb(lockedWeb)
                    : theWeb.Site.OpenWeb(theWeb.ID)))
                {
                    myworkWeb = configWeb;

                    foreach (
                        string list in
                        CoreFunctions.getConfigSetting(configWeb, myworksettings.GeneralSettingsSelectedMyWorkLists)
                        .Split(new[] { ',' }).Where(list => !string.IsNullOrEmpty(list)))
                    {
                        newItemLists.Add(list);
                        excludedMyWorkLists.RemoveAll(l => l.Name.Equals(list));
                    }

                    foreach (
                        string list in
                        CoreFunctions.getConfigSetting(configWeb, myworksettings.GeneralSettingsSelectedLists)
                        .Split(new[] { ',' }).Where(list => !string.IsNullOrEmpty(list)))
                    {
                        newItemLists.Add(list);
                        excludedMyWorkLists.RemoveAll(l => l.Name.Equals(list));
                    }
                }
            }

            newItemLists = newItemLists.Distinct().OrderBy(l => l).ToList();

            if (newItemLists.Count > 0)
            {
                var newItemListsFormatted = new List <string>();

                foreach (string newItemList in newItemLists)
                {
                    SPList spList = myworkWeb.Lists.TryGetList(newItemList);


                    if (spList == null)
                    {
                        continue;
                    }

                    var gSettings = new GridGanttSettings(spList);

                    string rollupLists = gSettings.RollupLists;
                    bool   usePopUp    = gSettings.UsePopup;

                    if (string.IsNullOrEmpty(rollupLists))
                    {
                        if (spList.Hidden || !spList.DoesUserHavePermissions(SPBasePermissions.AddListItems) ||
                            gSettings.HideNewButton)
                        {
                            continue;
                        }

                        newItemListsFormatted.Add(string.Format(@"{{Name:'{0}',ListID:'{1}',UsePopUp:'{2}',Rollup:false}}", newItemList, spList.ID, usePopUp));
                    }
                    else
                    {
                        newItemListsFormatted.Add(string.Format(@"{{Name:'{0}',ListID:'{1}',UsePopUp:'{2}',Rollup:true}}", newItemList, spList.ID, usePopUp));
                    }
                }

                newItemButtonLists = string.Join(",", newItemListsFormatted.ToArray());
            }

            return(newItemButtonLists);
        }
Пример #28
0
        public void StartRefresh(Guid timerjobguid, out DataTable dtResults, bool refreshAll)
        {
            DataTable dt             = InitializeResultsDT(_sListNames, refreshAll);
            string    _errorListName = string.Empty;

            try
            {
                SPList spList          = null;
                string sSiteIdListName = string.Empty;
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    using (_web)
                    {
                        if (refreshAll)
                        {
                            // we need to refresh work hours
                            // and resources first because
                            // SPProcessAssignments depends on data in LSTWorkHours and LSTResources

                            #region refresh work hours list

                            SPList lworkhours = _web.Lists.TryGetList("Work Hours");

                            //if (lworkhours == null)
                            //{
                            //    _DAO.LogStatus(
                            //        string.Empty,
                            //        string.Empty,
                            //        "Work Hours list does not exist at web: " + _web.ID + ".",
                            //        "Work Hours list does not exist at web: " + _web.ID + ".",
                            //        2,
                            //        3,
                            //        timerjobguid.ToString());
                            //}

                            // if a reporting list
                            if (lworkhours != null && IsReportingList("Work Hours"))
                            {
                                try
                                {
                                    _errorListName = "Work Hours";
                                    //Clear out dataset
                                    _dsLists       = new DataSet();
                                    _dsMyWorkLists = new DataSet();

                                    spList      = null;
                                    _sTableName = _DAO.GetTableName(lworkhours.ID);
                                    _siteID     = _web.ID;
                                    //Add sSiteIdListName string to array, that will be used to create dyn. sql to do a batch delete
                                    _ArrayListTableNames.Add(_sTableName);
                                    //throw new System.InvalidOperationException("exeception handling test");
                                    bool error;
                                    string sErrMsg;
                                    AddItems(timerjobguid, lworkhours.Title, out error, out sErrMsg);
                                    //Add all current list items to the database (from the corresponding sharepoint list)
                                    if (error)
                                    {
                                        DataRow[] dr = dt.Select("ListName='" + lworkhours.Title + "'");
                                        if (sErrMsg.ToLower().Contains("does not exist at site with url"))
                                        {
                                            if (dr[0]["ResultText"] == null)
                                            {
                                                dr[0]["ResultText"] = "&nbsp;" + "List not present.";
                                            }
                                            else
                                            {
                                                dr[0]["ResultText"] = dr[0]["ResultText"] + "&nbsp;" +
                                                                      "List not present.";
                                            }
                                        }
                                        else
                                        {
                                            if (dr[0]["ResultText"] == null)
                                            {
                                                dr[0]["ResultText"] = "&nbsp;" + sErrMsg;
                                            }
                                            else
                                            {
                                                dr[0]["ResultText"] = dr[0]["ResultText"] + "&nbsp;" + sErrMsg;
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    DataRow[] dr = dt.Select("ListName='" + lworkhours.Title + "'");
                                    if (ex.Message.ToLower().Contains("does not exist at site with url"))
                                    {
                                    }
                                    else
                                    {
                                        if (dr[0]["ResultText"] == null)
                                        {
                                            dr[0]["ResultText"] = "&nbsp;" + ex.Message;
                                        }
                                        else
                                        {
                                            dr[0]["ResultText"] = dr[0]["ResultText"] + "&nbsp;" + ex.Message;
                                        }
                                    }
                                }

                                if (_dsLists.Tables.Count > 0)
                                {
                                    _DAO.InsertAllItemsDB(_dsLists, timerjobguid);
                                }
                            }

                            #endregion // refresh work hours list

                            #region refresh resources list

                            SPList lResource = _web.Lists.TryGetList("Resources");
                            //if (lResource == null)
                            //{
                            //    _DAO.LogStatus(
                            //        string.Empty,
                            //        string.Empty,
                            //        "Resources list does not exist at web: " + _web.ID + ".",
                            //        "Resources list does not exist at web: " + _web.ID + ".",
                            //        2,
                            //        3,
                            //        timerjobguid.ToString());
                            //}
                            // if a reporting list
                            if (lResource != null && IsReportingList("Resources"))
                            {
                                try
                                {
                                    _errorListName = "Resources";
                                    //Clear out dataset
                                    _dsLists       = new DataSet();
                                    _dsMyWorkLists = new DataSet();

                                    spList      = null;
                                    _sTableName = _DAO.GetTableName(lResource.Title);
                                    _siteID     = _web.ID;
                                    //Add sSiteIdListName string to array, that will be used to create dyn. sql to do a batch delete
                                    _ArrayListTableNames.Add(_sTableName);
                                    //throw new System.InvalidOperationException("exeception handling test");
                                    bool error;
                                    string sErrMsg;
                                    AddItems(timerjobguid, lResource.Title, out error, out sErrMsg);
                                    //Add all current list items to the database (from the corresponding sharepoint list)
                                    if (error)
                                    {
                                        DataRow[] dr = dt.Select("ListName='" + lResource.Title + "'");
                                        if (sErrMsg.ToLower().Contains("does not exist at site with url"))
                                        {
                                            if (dr[0]["ResultText"] == null)
                                            {
                                                dr[0]["ResultText"] = "&nbsp;" + "List not present.";
                                            }
                                            else
                                            {
                                                dr[0]["ResultText"] = dr[0]["ResultText"] + "&nbsp;" +
                                                                      "List not present.";
                                            }
                                        }
                                        else
                                        {
                                            if (dr[0]["ResultText"] == null)
                                            {
                                                dr[0]["ResultText"] = "&nbsp;" + sErrMsg;
                                            }
                                            else
                                            {
                                                dr[0]["ResultText"] = dr[0]["ResultText"] + "&nbsp;" + sErrMsg;
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    DataRow[] dr = dt.Select("ListName='" + lResource.Title + "'");
                                    if (ex.Message.ToLower().Contains("does not exist at site with url"))
                                    {
                                    }
                                    else
                                    {
                                        if (dr[0]["ResultText"] == null)
                                        {
                                            dr[0]["ResultText"] = "&nbsp;" + ex.Message;
                                        }
                                        else
                                        {
                                            dr[0]["ResultText"] = dr[0]["ResultText"] + "&nbsp;" + ex.Message;
                                        }
                                    }
                                }

                                if (_dsLists.Tables.Count > 0)
                                {
                                    _DAO.InsertAllItemsDB(_dsLists, timerjobguid);
                                }
                            }

                            #endregion // refresh work hours list

                            #region refresh all

                            var allLists =
                                new List <string>(_sListNames.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
                            var allSpLists = new List <SPList>();
                            foreach (string l in allLists)
                            {
                                SPList list = _web.Lists.TryGetList(l);

                                if (list != null)
                                {
                                    allSpLists.Add(list);
                                }

                                if (list == null ||
                                    list.Title == "Work Hours" ||
                                    list.Title == "Resources")
                                {
                                    continue;
                                }

                                _errorListName = list.Title;

                                //Clear out dataset
                                _dsLists       = new DataSet();
                                _dsMyWorkLists = new DataSet();

                                // if a mywork list
                                var settings = new GridGanttSettings(list);
                                if (settings.EnableWorkList)
                                {
                                    try
                                    {
                                        _sTableName = "LSTMyWork";
                                        _siteID     = _web.ID;
                                        bool error;
                                        string sErrMsg;
                                        AddItems_MyWork(timerjobguid, list.Title, list.ID, out error, out sErrMsg);
                                        HandleError(error, dt, list, sErrMsg);
                                    }
                                    catch (Exception ex)
                                    {
                                        DataRow[] dr = dt.Select("ListName='" + list.Title + "'");
                                        if (ex.Message.ToLower().Contains("does not exist at site with url"))
                                        {
                                        }
                                        else
                                        {
                                            if (dr[0]["ResultText"] == null)
                                            {
                                                dr[0]["ResultText"] = "&nbsp;" + ex.Message;
                                            }
                                            else
                                            {
                                                dr[0]["ResultText"] = dr[0]["ResultText"] + "&nbsp;" + ex.Message;
                                            }
                                        }
                                    }

                                    if (_dsMyWorkLists.Tables.Count > 0)
                                    {
                                        _DAO.InsertAllItemsDB(_dsMyWorkLists, timerjobguid);
                                    }
                                }

                                // if a reporting list
                                if (IsReportingList(list.Title))
                                {
                                    try
                                    {
                                        spList      = null;
                                        _sTableName = _DAO.GetTableName(list.ID);
                                        _siteID     = _web.ID;
                                        //Add sSiteIdListName string to array, that will be used to create dyn. sql to do a batch delete
                                        _ArrayListTableNames.Add(_sTableName);
                                        //throw new System.InvalidOperationException("exeception handling test");
                                        bool error;
                                        string sErrMsg;
                                        AddItems(timerjobguid, list.Title, out error, out sErrMsg);
                                        //Add all current list items to the database (from the corresponding sharepoint list)
                                        HandleError(error, dt, list, sErrMsg);
                                    }
                                    catch (Exception ex)
                                    {
                                        DataRow[] dr = dt.Select("ListName='" + list.Title + "'");
                                        if (ex.Message.ToLower().Contains("does not exist at site with url"))
                                        {
                                        }
                                        else
                                        {
                                            if (dr[0]["ResultText"] == null)
                                            {
                                                dr[0]["ResultText"] = "&nbsp;" + ex.Message;
                                            }
                                            else
                                            {
                                                dr[0]["ResultText"] = dr[0]["ResultText"] + "&nbsp;" + ex.Message;
                                            }
                                        }
                                    }

                                    if (_dsLists.Tables.Count > 0)
                                    {
                                        _DAO.InsertAllItemsDB(_dsLists, timerjobguid);
                                    }
                                }
                            }

                            #endregion // refresh all lists

                            #region refresh security groups for all lists

                            try
                            {
                                ProcessSecurity.ProcessSecurityOnRefreshAll(_web, allSpLists,
                                                                            _DAO.GetClientReportingConnection());
                                _DAO.LogStatus(
                                    string.Empty,
                                    string.Empty,
                                    "ProcessSecurity processed successfully on refresh all for web: " + _web.Title,
                                    "ProcessSecurity processed successfully on refresh all for web: " + _web.Title,
                                    0,
                                    1,
                                    timerjobguid.ToString());
                            }
                            catch (Exception ex)
                            {
                                _DAO.LogStatus(
                                    string.Empty,
                                    string.Empty,
                                    "ProcessSecurity failed on refresh all.",
                                    ex.Message,
                                    2,
                                    3,
                                    timerjobguid.ToString());
                            }

                            #endregion
                        }
                        else
                        {
                            #region refreshing individual lists

                            //loop thru all lists
                            foreach (string sListName in _ArrayListNames)
                            {
                                try
                                {
                                    _errorListName = sListName;

                                    //set to null
                                    spList = null;

                                    //Init. list
                                    spList = _web.Lists[sListName];

                                    //Init. list sqltable name
                                    _sTableName = _DAO.GetTableName(spList.ID);//_DAO.GetTableName(sListName);

                                    //Init. web id
                                    _siteID = _web.ID;

                                    //Add sSiteIdListName string to array, that will be used to create dyn. sql to do a batch delete
                                    _ArrayListTableNames.Add(_sTableName);

                                    //Delete items in LSTMyWork associated to this list, then re-add
                                    var settings = new GridGanttSettings(spList);
                                    if (settings.EnableWorkList)
                                    {
                                        _DAO.DeleteMyWork(spList.ID);

                                        try
                                        {
                                            _sTableName = "LSTMyWork";
                                            _siteID     = _web.ID;
                                            bool bError;
                                            string sErr;
                                            AddItems_MyWork(timerjobguid, spList.Title, spList.ID, out bError, out sErr);
                                            if (bError)
                                            {
                                                DataRow[] dr = dt.Select("ListName='" + spList.Title + "'");
                                                if (sErr.ToLower().Contains("does not exist at site with url"))
                                                {
                                                    if (dr[0]["ResultText"] == null)
                                                    {
                                                        dr[0]["ResultText"] = "&nbsp;" + "List not present.";
                                                    }
                                                    else
                                                    {
                                                        dr[0]["ResultText"] = dr[0]["ResultText"] + "&nbsp;" +
                                                                              "List not present.";
                                                    }
                                                }
                                                else
                                                {
                                                    if (dr[0]["ResultText"] == null)
                                                    {
                                                        dr[0]["ResultText"] = "&nbsp;" + sErr;
                                                    }
                                                    else
                                                    {
                                                        dr[0]["ResultText"] = dr[0]["ResultText"] + "&nbsp;" + sErr;
                                                    }
                                                }
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            DataRow[] dr = dt.Select("ListName='" + spList.Title + "'");
                                            if (ex.Message.ToLower().Contains("does not exist at site with url"))
                                            {
                                            }
                                            else
                                            {
                                                if (dr[0]["ResultText"] == null)
                                                {
                                                    dr[0]["ResultText"] = "&nbsp;" + ex.Message;
                                                }
                                                else
                                                {
                                                    dr[0]["ResultText"] = dr[0]["ResultText"] + "&nbsp;" + ex.Message;
                                                }
                                            }
                                        }

                                        if (_dsMyWorkLists.Tables.Count > 0)
                                        {
                                            _DAO.InsertAllItemsDB(_dsMyWorkLists, timerjobguid);
                                        }
                                    }

                                    //throw new System.InvalidOperationException("exeception handling test");

                                    bool error;
                                    string sErrMsg;
                                    _sTableName = _DAO.GetTableName(spList.ID);
                                    AddItems(timerjobguid, sListName, out error, out sErrMsg);

                                    //Add all current list items to the database (from the corresponding sharepoint list)
                                    //AddItems(timerjobguid,sListName);

                                    if (error)
                                    {
                                        DataRow[] dr = dt.Select("ListName='" + sListName + "'");
                                        if (sErrMsg.ToLower().Contains("does not exist at site with url"))
                                        {
                                            if (dr[0]["ResultText"] == null)
                                            {
                                                dr[0]["ResultText"] = "&nbsp;" + "List not present.";
                                            }
                                            else
                                            {
                                                dr[0]["ResultText"] = dr[0]["ResultText"] + "&nbsp;" +
                                                                      "List not present.";
                                            }
                                        }
                                        else
                                        {
                                            if (dr[0]["ResultText"] == null)
                                            {
                                                dr[0]["ResultText"] = "&nbsp;" + sErrMsg;
                                            }
                                            else
                                            {
                                                dr[0]["ResultText"] = dr[0]["ResultText"] + "&nbsp;" + sErrMsg;
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    DataRow[] dr = dt.Select("ListName='" + sListName + "'");
                                    if (ex.Message.ToLower().Contains("does not exist at site with url"))
                                    {
                                        //DO NOTHING...
                                        //if (dr[0]["ResultText"] == null)
                                        //{
                                        //    dr[0]["ResultText"] = "&nbsp;" + "List not present.";
                                        //}
                                        //else
                                        //{
                                        //    dr[0]["ResultText"] = dr[0]["ResultText"] + "&nbsp;" + "List not present.";
                                        //}
                                    }
                                    else
                                    {
                                        if (dr[0]["ResultText"] == null)
                                        {
                                            dr[0]["ResultText"] = "&nbsp;" + ex.Message;
                                        }
                                        else
                                        {
                                            dr[0]["ResultText"] = dr[0]["ResultText"] + "&nbsp;" + ex.Message;
                                        }
                                    }
                                }

                                #region refresh security groups for list

                                try
                                {
                                    if (spList != null)
                                    {
                                        ProcessSecurity.ProcessSecurityOnListRefresh(_web, spList,
                                                                                     _DAO.GetClientReportingConnection());
                                        _DAO.LogStatus(
                                            string.Empty,
                                            string.Empty,
                                            "ProcessSecurity processed successfully on list: " + spList.Title +
                                            " in web: " + _web.Title,
                                            "ProcessSecurity processed successfully on list: " + spList.Title +
                                            " in web: " + _web.Title,
                                            0,
                                            1,
                                            timerjobguid.ToString());
                                    }
                                }
                                catch (Exception ex)
                                {
                                    DataRow[] dr = dt.Select("ListName='" + sListName + "'");
                                    if (dr[0]["ResultText"] == null)
                                    {
                                        dr[0]["ResultText"] = "&nbsp;" + ex.Message;
                                    }
                                    else
                                    {
                                        dr[0]["ResultText"] = dr[0]["ResultText"] + "&nbsp;" + ex.Message;
                                    }
                                }

                                #endregion
                            }

                            if (_dsLists.Tables.Count > 0)
                            {
                                _DAO.InsertAllItemsDB(_dsLists, timerjobguid);
                            }

                            #endregion
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                _DAO.LogStatus(string.Empty, string.Empty,
                               "Refresh not completed due to error. Web: " + _web.Title + ". List: " + _errorListName + ". Error: " +
                               ex.Message, ex.StackTrace, 2, 3, timerjobguid.ToString());
            }

            _DAO.Dispose();
            dtResults = dt;
        }
Пример #29
0
        public void execute(SPSite site, SPWeb web, string data)
        {
            try
            {
                Guid intlistid = new Guid(base.key);

                API.Integration.IntegrationCore core = new API.Integration.IntegrationCore(site.ID, web.ID);
                Hashtable hshParms = new Hashtable();
                hshParms.Add("intlistid", intlistid);
                DateTime dtStarted = DateTime.Now;

                DataSet   DS            = core.GetDataSet("SELECT * FROM INT_LISTS where INT_LIST_ID=@intlistid", hshParms);
                DataRow   drIntegration = DS.Tables[0].Rows[0];
                Hashtable hshProperties = null;
                DataSet   dsColumns     = null;
                DataTable dtCols        = null;
                DataTable dtItem        = null;
                DataSet   dsUserFields  = null;
                DataTable dtUserFields  = null;
                Hashtable hshUserMap    = null;
                DataTable dtRet         = null;
                DataSet   dsItem        = null;
                try
                {
                    hshProperties = core.GetProperties(intlistid);

                    dsColumns = core.GetDataSet("SELECT * FROM INT_COLUMNS where INT_LIST_ID=@intlistid", hshParms);
                    dtCols    = dsColumns.Tables[0];

                    dtItem = new DataTable();
                    dtItem.Columns.Add("ID");
                    foreach (DataRow drCol in dtCols.Rows)
                    {
                        dtItem.Columns.Add(drCol["IntegrationColumn"].ToString());
                    }

                    DateTime dtLastSynch = new DateTime(1900, 1, 1);

                    try
                    {
                        dtLastSynch = DateTime.Parse(drIntegration["LASTSYNCH"].ToString());
                    }
                    catch { }

                    if (drIntegration["TIMEINCOMING"].ToString() == "True")
                    {
                        dtItem = core.PullData(dtItem, intlistid, new Guid(drIntegration["LIST_ID"].ToString()), dtLastSynch);

                        base.totalCount = dtItem.Rows.Count + 1;

                        int count = 0;

                        bool allowAdd = false;

                        try
                        {
                            allowAdd = bool.Parse(hshProperties["AllowAddList"].ToString());
                        }
                        catch { }

                        SPList list = web.Lists[new Guid(drIntegration["LIST_ID"].ToString())];

                        GridGanttSettings settings = new GridGanttSettings(list);

                        bool bBuildTeamSec = settings.BuildTeamSecurity;

                        dsUserFields = core.GetDataSet(list, "", intlistid);
                        dtUserFields = dsUserFields.Tables[1];
                        if (dtUserFields.Select("Type='1'").Length > 0 || bBuildTeamSec)
                        {
                            hshUserMap = core.GetUserMap(drIntegration["INT_LIST_ID"].ToString(), true);
                        }

                        bool bSPCol = false;
                        try
                        {
                            if (hshProperties["SPColumn"].ToString() != "")
                            {
                                bSPCol = true;
                            }
                        }
                        catch { }

                        dtRet = new DataTable();
                        dtRet.Columns.Add("ID");

                        if (bSPCol)
                        {
                            dtRet.Columns.Add(hshProperties["SPColumn"].ToString());
                        }

                        foreach (DataRow dr in dtItem.Rows)
                        {
                            int spid = core.iProcessItemRow(dr, list, dtCols, hshProperties, drIntegration["INT_COLID"].ToString(), intlistid, new Guid(drIntegration["MODULE_ID"].ToString()), allowAdd, dtUserFields, hshUserMap);

                            try
                            {
                                if (spid != 0 && bSPCol)
                                {
                                    dtRet.Rows.Add(new string[] { dr["ID"].ToString(), spid.ToString() });
                                }
                            }
                            catch { }

                            base.updateProgress(count++);
                        }

                        if (bSPCol)
                        {
                            core.PostIntegrationUpdateToExternal(dtRet, intlistid, list.ID);
                        }

                        core.LogMessage(intlistid.ToString(), drIntegration["LIST_ID"].ToString(), "Timer: Imported " + dtItem.Rows.Count + " Items", 1);
                    }
                    else if (drIntegration["TIMEOUTGOING"].ToString() == "True")
                    {
                        SPList list = web.Lists[new Guid(drIntegration["LIST_ID"].ToString())];
                        core.OpenConnection();
                        dsItem = core.GetDataSet(list, "", intlistid);

                        SPQuery query = new SPQuery();
                        query.Query = "<Where><Gt><FieldRef Name=\"Modified\" /><Value IncludeTimeValue=\"TRUE\" Type=\"DateTime\">" + Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(dtLastSynch) + "</Value></Gt></Where>";
                        SPListItemCollection lic = list.GetItems(query);

                        base.totalCount = lic.Count * 2;
                        int count = 0;
                        foreach (SPListItem li in lic)
                        {
                            core.ProcessItem(dsItem, li, list);
                            updateProgress(count++);
                        }

                        core.PostIntegration(dsItem.Tables[0].Copy(), dsItem.Tables[1], dsItem.Tables[2], list);

                        core.LogMessage(intlistid.ToString(), drIntegration["LIST_ID"].ToString(), "Timer: Exported " + lic.Count + " Items", 1);
                    }

                    hshParms.Add("lastsynch", dtStarted.ToString());
                    core.ExecuteQuery("UPDATE INT_LISTS set lastsynch=@lastsynch where INT_LIST_ID=@intlistid", hshParms, true);

                    core.CloseConnection(true);
                }
                catch (Exception ex)
                {
                    core.LogMessage(intlistid.ToString(), drIntegration["LIST_ID"].ToString(), "Timer: " + ex.Message, 3);
                    sErrors += "General Error: " + ex.Message;
                    bErrors  = true;
                }
                finally
                {
                    hshParms      = null;
                    hshUserMap    = null;
                    hshProperties = null;
                    if (DS != null)
                    {
                        DS.Dispose();
                    }
                    if (dsColumns != null)
                    {
                        dsColumns.Dispose();
                    }
                    if (dtCols != null)
                    {
                        dtCols.Dispose();
                    }
                    if (dtItem != null)
                    {
                        dtItem.Dispose();
                    }
                    if (dsUserFields != null)
                    {
                        dsUserFields.Dispose();
                    }
                    if (dtUserFields != null)
                    {
                        dtUserFields.Dispose();
                    }
                    if (dtRet != null)
                    {
                        dtRet.Dispose();
                    }
                    if (dsItem != null)
                    {
                        dsItem.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                sErrors += "General Error: " + ex.Message;
                bErrors  = true;
            }
            finally
            {
                if (web != null)
                {
                    web.Dispose();
                }
                if (site != null)
                {
                    site.Dispose();
                }
                data = null;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SPList list = Web.Lists[new Guid(Request["List"])];

                lblList.Text = list.Title;
                SPField oField = list.Fields.GetFieldByInternalName(Request["field"]);
                lblField.Text = oField.Title;

                PopulateLookupFields(list);


                GridGanttSettings gSettings   = new GridGanttSettings(list);
                string[]          LookupArray = gSettings.Lookups.Split('|');

                Hashtable hshLookups = new Hashtable();
                foreach (string sLookup in LookupArray)
                {
                    if (sLookup != "")
                    {
                        string[] sLookupInfo = sLookup.Split('^');
                        hshLookups.Add(sLookupInfo[0], sLookupInfo);
                    }
                }

                if (hshLookups.Contains(Request["field"]))
                {
                    chkEnabled.Checked           = true;
                    ddlParentLookup.Enabled      = true;
                    ddlParentLookupField.Enabled = true;
                    ddlStyle.Enabled             = true;
                    chkSecurity.Enabled          = true;

                    string[] sLookupInfo = (string[])hshLookups[Request["field"]];
                    try
                    {
                        ddlStyle.SelectedValue = sLookupInfo[1];
                    }
                    catch { }
                    try
                    {
                        chkSecurity.Checked = bool.Parse(sLookupInfo[4]);
                    }
                    catch { }
                    try
                    {
                        ddlParentLookup.SelectedValue = sLookupInfo[2];
                    }
                    catch { }


                    PopulateLookupFieldsFields();
                    try
                    {
                        ddlParentLookupField.SelectedValue = sLookupInfo[3];
                    }
                    catch { }
                }
                else
                {
                    chkEnabled.Checked           = false;
                    ddlParentLookup.Enabled      = false;
                    ddlParentLookupField.Enabled = false;
                    ddlStyle.Enabled             = false;
                    chkSecurity.Enabled          = false;
                }
            }
            else
            {
                if (chkEnabled.Checked)
                {
                    ddlParentLookup.Enabled      = true;
                    ddlParentLookupField.Enabled = true;
                    ddlStyle.Enabled             = true;
                    chkSecurity.Enabled          = true;
                }
                else
                {
                    ddlParentLookup.Enabled      = false;
                    ddlParentLookupField.Enabled = false;
                    ddlStyle.Enabled             = false;
                    chkSecurity.Enabled          = false;
                }
            }
        }