private STreeItem GetNode(SPFolder folder, STreeItem parent) { STreeItem node = new STreeItem(); SPListItem item = folder.Item; if (item == null && parent != null) { return(null); } if (item == null) { node.ID = 0; } else { node.ID = item.ID; } if (parent == null) { node.Depth = 0; } else { node.Depth = parent.Depth + 1; } node.Title = folder.Name; node.Name = folder.Name; if (item != null) { node.Title = item.Title; } else { node.Title = folder.Name; } node.ServerRelativeUrl = folder.ServerRelativeUrl; if (showIconEdit == true && item != null && item.DoesUserHavePermissions(SPBasePermissions.EditListItems) == true) { if (string.IsNullOrEmpty(item.ContentType.EditFormUrl) == false) { node.EditServerRelativeUrl = string.Format("{0}?ID={1}" , item.ContentType.EditFormUrl, item.ID); } else { node.EditServerRelativeUrl = string.Format("{0}?ID={1}" , editUrl, item.ID); } } else { node.EditServerRelativeUrl = ""; } node.Url = folder.Url; return(node); }
public static bool DoesPrincipalHasPermissions(SPListItem item, SPPrincipal principal, SPBasePermissions permissions) { if (principal is SPUser) { return(item.DoesUserHavePermissions((SPUser)principal, permissions)); } SPRoleAssignment assignmentByPrincipal = null; try { assignmentByPrincipal = item.RoleAssignments.GetAssignmentByPrincipal(principal); } catch { return(false); } return(assignmentByPrincipal.RoleDefinitionBindings.Cast <SPRoleDefinition>().Any(definition => (definition.BasePermissions & permissions) == permissions)); }
/// <summary> /// Cancels the workflows. This code is a re-engineering of the code that Microsoft uses /// when approving an item via the browser. That code is in Microsoft.SharePoint.ApplicationPages.ApprovePage. /// </summary> /// <param name="test">If true test the change only (don't make any changes).</param> /// <param name="list">The list.</param> /// <param name="item">The item.</param> private void CancelWorkflows(bool test, SPList list, SPListItem item) { if (list.DefaultContentApprovalWorkflowId != Guid.Empty && item.DoesUserHavePermissions((SPBasePermissions.ApproveItems | SPBasePermissions.EditListItems))) { // If the user has rights to do so then we need to cancel any workflows that // are associated with the item. SPSecurity.RunWithElevatedPrivileges( delegate { foreach (SPWorkflow workflow in item.Workflows) { if (workflow.ParentAssociation.Id != list.DefaultContentApprovalWorkflowId) { continue; } SPWorkflowManager.CancelWorkflow(workflow); Logger.Write("Cancelling workflow {0} for item: {1} ({2})", workflow.WebId.ToString(), item.ID.ToString(), item.Url); } }); } }
private static bool LIP(SPListItem listItem, SPBasePermissions spBasePermissions) { return(listItem.DoesUserHavePermissions(spBasePermissions)); }
public static List <Permissions> GetPermissions(string barCode, SPListItem listItem) { List <Permissions> permissions = new List <Permissions>(); string author = listItem.TryGetFieldValue(SPBuiltInFieldId.Author, string.Empty); if (!string.IsNullOrWhiteSpace(author)) { SPFieldUserValue authorUserValue = new SPFieldUserValue(listItem.Web, author); Permissions authorPermission = new Permissions { Barcode = barCode, CanWrite = true, UserGroupId = authorUserValue.User.ID }; permissions.Add(authorPermission); } try { using (SPSite evaluatedSite = new SPSite(listItem.ParentList.ParentWeb.Site.ID, SPUserToken.SystemAccount)) { using (SPWeb evaluatedWeb = evaluatedSite.OpenWeb(listItem.ParentList.ParentWeb.ID)) { SPList spList = evaluatedWeb.Lists[listItem.ParentList.ID]; SPListItem spListItem = spList.GetItemById(listItem.ID); foreach (SPRoleAssignment assignment in spListItem.RoleAssignments) { bool isAgroup = true; SPGroup aGroup = evaluatedWeb.Groups.Cast <SPGroup>().FirstOrDefault(g => g.ID == assignment.Member.ID); if (aGroup == null) { isAgroup = false; } if (isAgroup) { bool groupCanEdit = false; SPRoleAssignment spRoleAssignment = new SPRoleAssignment(aGroup); SPRoleDefinitionBindingCollection roleDefinitionBindings = spRoleAssignment.RoleDefinitionBindings; foreach (SPRoleDefinition roleDefinitionBinding in roleDefinitionBindings) { groupCanEdit = roleDefinitionBinding.BasePermissions.HasFlag(SPBasePermissions.EditListItems); } Permissions newGroupPermission = new Permissions { Barcode = barCode, CanWrite = groupCanEdit, UserGroupId = aGroup.ID }; if ( !permissions.Any( p => p.UserGroupId == newGroupPermission.UserGroupId && p.CanWrite == newGroupPermission.CanWrite)) { permissions.Add(newGroupPermission); } if (aGroup.Users.Count <= 0) { continue; } IEnumerable <Permissions> newPermissions = from SPUser aUser in aGroup.Users let canEdit = spListItem.DoesUserHavePermissions(aUser, SPBasePermissions.EditListItems) select new Permissions { Barcode = barCode, CanWrite = canEdit, UserGroupId = aUser.ID }; foreach (Permissions newPermission in newPermissions .Where( permissionse => !permissions.Any( p => p.UserGroupId == permissionse.UserGroupId && p.CanWrite == permissionse.CanWrite))) { permissions.Add(newPermission); } } else { SPUser spUser = spListItem.Web.Users.GetByID(assignment.Member.ID); bool canEdit = spListItem.DoesUserHavePermissions(spUser, SPBasePermissions.EditListItems); Permissions newPermission = new Permissions { Barcode = barCode, CanWrite = canEdit, UserGroupId = spUser.ID }; if ( !permissions.Any( p => p.UserGroupId == newPermission.UserGroupId && p.CanWrite == newPermission.CanWrite)) { permissions.Add(newPermission); } } } } } } catch (Exception ex) { Logger.WriteError(ex.Message, ex); } return(permissions); }
protected void Page_Load(object sender, EventArgs e) { SPListItemId = Request["SPListItemId"]; SPListURLDir = Request["SPListURLDir"]; SPListId = Request["SPListId"]; SPSource = Request["SPSource"]; currentUser = SPContext.Current.Web.CurrentUser; CurrentUserId = currentUser.ID; CurrentUserName = currentUser.Name; if (currentUser == null) { Response.Redirect(SPUrl, true); return; } SPList list = null; SPListItem item = null; try { list = SPContext.Current.Web.GetList(SPListURLDir); item = list.GetItemById(Int32.Parse(SPListItemId)); } catch (NullReferenceException ex) { Log.LogError(ex.Message); } if (item == null) { Response.Redirect(SPUrl, true); return; } // Make sure user has permissions to view the item if (!item.DoesUserHavePermissions(currentUser, SPBasePermissions.ViewListItems)) { Response.Redirect(SPUrl, true); return; } // To distinguish between commenters and viewers we have created a special reduced permission level - ViewOnly // It has no OpenItems base permissions. This way we distinguish between those who can comment and those who cannot. canComment = item.DoesUserHavePermissions(currentUser, SPBasePermissions.OpenItems); canEdit = item.DoesUserHavePermissions(currentUser, SPBasePermissions.EditListItems); SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(SPUrl)) { using (SPWeb web = site.OpenWeb()) { //check secret key //================================================================================== if (web.Properties["SharePointSecret"] == null) { var rnd = new Random(); var spSecret = ""; for (var i = 0; i < 6; i++) { spSecret = spSecret + rnd.Next(1, 9).ToString(); } web.AllowUnsafeUpdates = true; web.Update(); web.Properties.Add("SharePointSecret", spSecret); web.Properties.Update(); web.AllowUnsafeUpdates = true; web.Update(); } Secret = web.Properties["SharePointSecret"]; //read settings //================================================================================== if (web.Properties["DocumentServerHost"] != null) { DocumentSeverHost = web.Properties["DocumentServerHost"]; } DocumentSeverHost += DocumentSeverHost.EndsWith("/") ? "" : "/"; var lcid = (int)web.Language; var defaultCulture = new CultureInfo(lcid); lang = defaultCulture.IetfLanguageTag; GoToBackText = LoadResource("GoToBack"); //generate key and get file info for DocEditor //================================================================================== try { SPFile file = item.File; if (file != null) { Key = file.ETag; Key = GenerateRevisionId(Key); Folder = Path.GetDirectoryName(file.ServerRelativeUrl); Folder = Folder.Replace("\\", "/"); GoToBack = host + Folder; SPUser author = file.Author; FileAuthor = author.Name; var tzi = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneInfo.Local.Id); FileTimeCreated = TimeZoneInfo.ConvertTimeFromUtc(file.TimeCreated, tzi).ToString(); FileName = file.Name; var tmp = FileName.Split('.'); FileType = tmp[tmp.Length - 1]; //check document format try { if (FileUtility.CanViewTypes.Contains(FileType)) { var canEditType = FileUtility.CanEditTypes.Contains(FileType); canEdit = canEdit & canEditType; //FileEditorMode = canEdit == true ? "edit" : FileEditorMode; FileEditorMode = canComment == true ? "edit" : FileEditorMode; //documentType = FileUtility.docTypes[FileType]; DocType.GetDocType(FileName) documentType = FileUtility.GetDocType(FileType); } else { Response.Redirect(SPUrl); } } catch (Exception ex) { //if a error - redirect to home page Log.LogError(ex.Message); Response.Redirect(SPUrl); } } else { Response.Redirect(SPUrl); } } catch (Exception ex) { Log.LogError(ex.Message); Response.Redirect(SPUrl + "/_layouts/" + SPVersion + "error.aspx"); } } } }); //generate url hash //================================================================================== urlDocDownload = Encryption.GetUrlHash(SPListItemId, Folder, SPListURLDir, "download", Secret); urlDocTrack = Encryption.GetUrlHash(SPListItemId, Folder, SPListURLDir, "track", Secret); }
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"] + "'"; } } }
public override void ItemUpdated(SPItemEventProperties properties) { try { SPListItem item = properties.ListItem; SPUser assignedTo = item.GetFieldAsSPUser(eCaseConstants.FieldGuids.OOTB_ASSIGNEDTO); SPUser assignedToSupervisor = item.GetFieldAsSPUser(eCaseConstants.FieldGuids.ECASES_LIST_ASSIGNEDTOSUPERVISOR); string caseTitle = item[eCaseConstants.FieldGuids.OOTB_TITLE] as string; string caseWebUrl = item[eCaseConstants.FieldGuids.ECASES_LIST_CASEURL].ToString(); caseWebUrl = caseWebUrl.Split(',')[0]; SPSite site; SPWeb caseWeb; bool titleUpdated = false; using (site = new SPSite(caseWebUrl)) { using (caseWeb = site.OpenWeb()) { if (caseWeb.DoesUserHavePermissions(SPBasePermissions.ManageWeb)) { UpdateCaseWebTitle(caseWeb, caseTitle); titleUpdated = true; } } } if (titleUpdated == false) { SPSecurity.RunWithElevatedPrivileges(delegate() { using (site = new SPSite(caseWebUrl)) { using (caseWeb = site.OpenWeb()) { if (titleUpdated == false) { UpdateCaseWebTitle(caseWeb, caseTitle); } } } }); } if (item.DoesUserHavePermissions(SPBasePermissions.ManagePermissions)) { item.TryGrantPermission(assignedTo, SPRoleType.Administrator); item.TryGrantPermission(assignedToSupervisor, SPRoleType.Administrator); } else // We need to elevate to do this { SPSecurity.RunWithElevatedPrivileges(delegate() { using (site = new SPSite(properties.SiteId)) { using (SPWeb rootWeb = site.OpenWeb()) { SPList list = rootWeb.GetListByInternalName(properties.List.RootFolder.Name); SPListItem i = list.GetItemById(item.ID); i.TryGrantPermission(assignedToSupervisor, SPRoleType.Administrator); i.TryGrantPermission(assignedTo, SPRoleType.Administrator); } } }); } } catch (Exception x) { Logger.Instance.Error("Error in Cases list ItemUpdated", x, DiagnosticsCategories.eCaseExtensions); } }
public override void ItemUpdating(SPItemEventProperties properties) { try { // This represents the item as it WAS, not as it WILL BE SPListItem item = properties.ListItem; SPUser prevAssignedToUser = null; SPUser prevSupervisorUser = null; #region Determine Locking Behavior bool newLockCase, oldLockCase, lockCase, unlockCase; SPListItem oldCaseStatusItem = properties.ListItem.GetFieldLookupAsSPListItem("CaseStatusLookup"); SPListItem newCaseStatusItem = properties.AfterProperties.GetFieldLookupAsSPListItem("CaseStatusLookup", properties.List); if (bool.TryParse(newCaseStatusItem[eCaseConstants.FieldGuids.ECASE_STATUSES_LOCK_SITE].ToString(), out newLockCase) && bool.TryParse(oldCaseStatusItem[eCaseConstants.FieldGuids.ECASE_STATUSES_LOCK_SITE].ToString(), out oldLockCase)) { if (string.Compare(newCaseStatusItem[eCaseConstants.FieldGuids.OOTB_TITLE].ToString(), oldCaseStatusItem[eCaseConstants.FieldGuids.OOTB_TITLE].ToString()) != 0) { if (oldLockCase && !newLockCase) // If the status was locked, and now not, lets unlock { unlockCase = true; lockCase = false; } else if (oldLockCase && newLockCase) // If the status was locked, and still locked, do nothing { lockCase = unlockCase = false; } else if (!oldLockCase && newLockCase) // If the status was not locked, and now is locked, need to lock { unlockCase = false; lockCase = true; } else // !oldLockCase && !lockCase -- do nothing { lockCase = unlockCase = false; } } else // the status didn't change { lockCase = unlockCase = false; } } else // Something's wrong if we cannot parse one { throw new InvalidOperationException("Cannot parse Case Status Values"); } #endregion string caseWebUrl = item[eCaseConstants.FieldGuids.ECASES_LIST_CASEURL].ToString().Split(',')[0]; SPSite site; SPWeb caseWeb; SPSecurity.RunWithElevatedPrivileges(delegate() { using (site = new SPSite(caseWebUrl)) { using (caseWeb = site.OpenWeb()) { SPUser assignedToUser = null; SPUser supervisorUser = null; GetAssignedToAndSupervisor(item, properties.AfterProperties, caseWeb, ref assignedToUser, ref prevAssignedToUser, ref supervisorUser, ref prevSupervisorUser); if (assignedToUser != null || supervisorUser != null) { UpdateProxyGroups(caseWeb, assignedToUser, supervisorUser, prevAssignedToUser, prevSupervisorUser); } } } }); if (prevAssignedToUser == null) { prevAssignedToUser = item.GetFieldAsSPUser(eCaseConstants.FieldGuids.OOTB_ASSIGNEDTO); } if (prevSupervisorUser == null) { prevSupervisorUser = item.GetFieldAsSPUser(eCaseConstants.FieldGuids.ECASES_LIST_ASSIGNEDTOSUPERVISOR); } if (item.DoesUserHavePermissions(SPBasePermissions.ManagePermissions)) { item.TryRemovePermissions(prevAssignedToUser); item.TryRemovePermissions(prevSupervisorUser); } else // We need to elevate to do this { SPSecurity.RunWithElevatedPrivileges(delegate() { using (site = new SPSite(properties.SiteId)) { using (SPWeb rootWeb = site.OpenWeb()) { SPList list = rootWeb.GetListByInternalName(properties.List.RootFolder.Name); SPListItem i = list.GetItemById(item.ID); i.TryRemovePermissions(prevAssignedToUser); i.TryRemovePermissions(prevSupervisorUser); } } }); } if (lockCase || unlockCase) { SPSecurity.RunWithElevatedPrivileges(delegate() { using (site = new SPSite(caseWebUrl)) { using (caseWeb = site.OpenWeb()) { using (DbAdapter dbAdapter = new DbAdapter()) { SPList list = site.RootWeb.GetListByInternalName(properties.List.RootFolder.Name); SPListItem i = list.GetItemById(item.ID); _connectionString = site.RootWeb.Properties[eCaseConstants.PropertyBagKeys.ECASE_DB_CONNECTION_STRING]; dbAdapter.Connect(_connectionString); if (lockCase) { LockCaseSite(i, caseWeb, dbAdapter); } else { UnlockCaseSite(i, caseWeb, dbAdapter); } } } } }); } } catch (Exception x) { Logger.Instance.Error("Error in Cases list ItemUpdating", x, DiagnosticsCategories.eCaseSite); } }
private string[] GetCurrentUserPermissionsOnItem(SPWeb web, SPListItem item) { var permissions = new List<string>(); if (item.DoesUserHavePermissions(SPBasePermissions.EditListItems)) { permissions.Add("Edit"); // If users have permissions to edit all items or // if user should only have edit permissions on their own items var list = this.listLocator.GetByUrl(web, this.config.DiscussionListInfo.WebRelativeUrl); if ((list.WriteSecurity == 1) || (list.WriteSecurity == 2)) { var currentUserLogin = SPContext.Current.Web.CurrentUser.LoginName; var authorUserLogin = new SPFieldUserValue(list.ParentWeb, item[SPBuiltInFieldId.Author].ToString()).User.LoginName; if (authorUserLogin.Equals(currentUserLogin, StringComparison.OrdinalIgnoreCase)) { permissions.Add("EditAuthor"); } } } if (item.DoesUserHavePermissions(SPBasePermissions.ManageWeb)) { permissions.Add("ManageWeb"); } if (item.DoesUserHavePermissions(SPBasePermissions.ManageLists)) { permissions.Add("ManageLists"); } return permissions.ToArray(); }
private void processLiveHours(string id, Guid listGuid, SPList list) { SPListItem li = null; double hours = 0; try { string itemid = ""; try { itemid = Request[id + "_itemid"].ToString(); } catch { } if (id != "0") { li = list.GetItemById(int.Parse(itemid)); } if (li != null) { SqlCommand cmdHours = new SqlCommand("select cast(sum(hours) as float) from vwTSHoursByTask where list_uid=@listuid and item_id = @itemid", cn); cmdHours.Parameters.AddWithValue("@listuid", listGuid); cmdHours.Parameters.AddWithValue("@itemid", itemid); SqlDataReader dr1 = cmdHours.ExecuteReader(); if (dr1.Read()) { if (!dr1.IsDBNull(0)) { hours = dr1.GetDouble(0); } } dr1.Close(); if (li.DoesUserHavePermissions(SPBasePermissions.EditListItems)) { li["TimesheetHours"] = hours; list.ParentWeb.AllowUnsafeUpdates = true; li.SystemUpdate(); } else { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite s = new SPSite(list.ParentWeb.Site.ID)) { using (SPWeb w = s.OpenWeb(list.ParentWeb.ID)) { SPList l = w.Lists[listGuid]; SPListItem i = l.GetItemById(li.ID); i["TimesheetHours"] = hours; w.AllowUnsafeUpdates = true; i.SystemUpdate(); } } }); } } } catch { } }