public static SPUser GetFieldAsSPUser(this SPListItem item, Guid userFieldGuid) { SPUser user = null; // Verify that a user field exists SPFieldUser userField = item.Fields[userFieldGuid] as SPFieldUser; if (userField != null && item[userFieldGuid] != null) { // Convert the user field into an SPUser object SPFieldUserValue userFieldValue = userField.GetFieldValue(item[userFieldGuid].ToString()) as SPFieldUserValue; if (userFieldValue != null) { user = userFieldValue.User; } else { Logger.Instance.Error(string.Format("Cannot get user field {0} at {1}", userFieldGuid.ToString(), item.Url), DiagnosticsCategories.eCaseExtensions); } } else { Logger.Instance.Error(string.Format("Field with GUID {0} not found in List {1}", userFieldGuid, item.ParentList.RootFolder.Url), DiagnosticsCategories.eCaseExtensions); } return(user); }
private SPFieldUserValueCollection GetManagers(SPListItem item) { SPFieldUserValueCollection fieldValues = new SPFieldUserValueCollection(); if (item["Responsible"] != null) { SPFieldUserValue userValue = new SPFieldUserValue(item.Web, item["Responsible"].ToString()); fieldValues.Add(userValue); } SPFieldUser field = item.Fields["Person in charge"] as SPFieldUser; if (field != null && item["Person in charge"] != null) { SPFieldUserValueCollection picFieldValues = field.GetFieldValue(item["Person in charge"].ToString()) as SPFieldUserValueCollection; fieldValues.AddRange(picFieldValues); } if (item["Approver"] != null) { SPFieldUserValue userValue = new SPFieldUserValue(item.Web, item["Approver"].ToString()); fieldValues.Add(userValue); } string secondApprover = GetSecondApprover(item); if (secondApprover != string.Empty && item[secondApprover] != null) { SPFieldUserValue userValue = new SPFieldUserValue(item.Web, item[secondApprover].ToString()); fieldValues.Add(userValue); } return(fieldValues); }
/// <summary> /// 查询SharePoint列表项中用户/用户组栏中的用户(单个用户的字段) /// </summary> /// <param name="spItem">列表项</param> /// <param name="fieldName">栏名</param> /// <returns></returns> SPUser GetSPUserFromSPListItemByFieldName(SPListItem spItem, string fieldName) { string userName = spItem[fieldName].ToString(); SPFieldUser _user = (SPFieldUser)spItem.Fields[fieldName]; SPFieldUserValue userValue = (SPFieldUserValue)_user.GetFieldValue(userName); return(userValue.User); }
public static SPUser GetUser(SPListItem item, SPField userField) { string currentValue = item[userField.Title].ToString(); SPFieldUser field = (SPFieldUser)userField; SPFieldUserValue fieldValue = (SPFieldUserValue)field.GetFieldValue(currentValue); return(fieldValue.User); }
/// <summary> /// Public Methods /// </summary> /// <param name="listName"></param> /// <param name="properties"></param> /// <param name="fieldName"></param> /// <returns></returns> public string GetSPUserEmailID(string listName, SPItemEventProperties properties, string fieldName) { SPFieldUser userField = (SPFieldUser)properties.OpenWeb().Lists[listName].Fields.GetField(fieldName); SPFieldUserValue fieldValue = (SPFieldUserValue)userField.GetFieldValue(properties.ListItem[fieldName] + ""); SPUser user = fieldValue.User; return(user.Email); }
private string GetItemAuthorId(SPListItem item) { // get user object SPFieldUser author = (SPFieldUser)item.Fields[SPBuiltInFieldId.Author]; SPFieldUserValue userVal = (SPFieldUserValue)author.GetFieldValue(item[SPBuiltInFieldId.Author].ToString()); SPUser authorObj = userVal.User; return((authorObj == null) ? string.Empty : authorObj.ID.ToString()); }
private List <SPUser> GetSPUserObject(SPListItem spListItem, String fieldName) { List <SPUser> spUser = new List <SPUser>(); try { if (fieldName != string.Empty) { SPFieldUser field = spListItem.Fields[fieldName] as SPFieldUser; if (field != null && spListItem[fieldName] != null) { SPFieldUserValue fieldValue = field.GetFieldValue(spListItem[fieldName].ToString()) as SPFieldUserValue; if (fieldValue != null) { spUser.Add(fieldValue.User); } else { SPFieldUserValueCollection fieldValues = field.GetFieldValue(spListItem[fieldName].ToString()) as SPFieldUserValueCollection; foreach (SPFieldUserValue fv in fieldValues) { spUser.Add(fv.User); } } } else { if (field == null) { throw new Exception("GetSPUserObject: field is null "); } if (spListItem[fieldName] == null) { throw new Exception("GetSPUserObject: spListItem[fieldName] is null "); } } } } catch (Exception ex) { throw ex; } return(spUser); }
//Mit dieser Methode wird aus den Spalten "Name Besteller" und "Projektleiter" der "SPUser" erhalten; mit diesem kann auf Mail-Adresse und Anzeigename zugegriffen werden //Sie wird verwendet, um den Anzeigename in der Mail an die Zentrale verwenden zu können public String GetUserDisplayName(SPListItem listItem, String collumnName) { //Laden des userFields aus dem übergebenem Element (listitem) und der Spalte, die einen Nutzer enthält (spalte) SPFieldUser userField = (SPFieldUser)listItem.Fields.GetField(collumnName); SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(listItem[collumnName].ToString()); SPUser user = userFieldValue.User; //Zuweisen des Anzeigenamens und Rückgabe desselben string displayName = user.Name; return(displayName); }
private void GetSPUserObject(SPListItem item, String fieldName, SPRoleDefinition roleDefinition) { try { if (fieldName != string.Empty) { SPFieldUser field = item.Fields[fieldName] as SPFieldUser; if (field != null && item[fieldName] != null) { SPFieldUserValue fieldValue = field.GetFieldValue(item[fieldName].ToString()) as SPFieldUserValue; if (fieldValue != null) { AddPermissions(item, fieldValue.User, roleDefinition); } else { SPFieldUserValueCollection fieldValues = field.GetFieldValue(item[fieldName].ToString()) as SPFieldUserValueCollection; foreach (SPFieldUserValue fv in fieldValues) { AddPermissions(item, fv.User, roleDefinition); } } } else { if (field == null) { throw new Exception("GetSPUserObject: field is null "); } if (item[fieldName] == null) { throw new Exception("GetSPUserObject: spListItem[fieldName] is null "); } } } } catch (Exception ex) { throw ex; } }
private string GetSPUserObject(SPListItem sourceItem, String fieldName) { try { string emails = string.Empty; if (fieldName != string.Empty) { SPFieldUser field = sourceItem.Fields[fieldName] as SPFieldUser; if (field != null && sourceItem[fieldName] != null) { SPFieldUserValue fieldValue = field.GetFieldValue(sourceItem[fieldName].ToString()) as SPFieldUserValue; if (fieldValue != null) { emails = fieldValue.User.Email + ";"; } else { SPFieldUserValueCollection fieldValues = field.GetFieldValue(sourceItem[fieldName].ToString()) as SPFieldUserValueCollection; foreach (SPFieldUserValue fv in fieldValues) { emails += fv.User.Email + ";"; } } } else { if (field == null) { throw new Exception("GetSPUserObject: field is null "); } } } return(emails); } catch (Exception ex) { throw ex; } }
private List <SPUser> GetManagerProd(SPListItem sourceItem, String fieldName) { try { List <SPUser> allManagers = new List <SPUser>(); if (fieldName != string.Empty) { SPFieldUser field = sourceItem.Fields[fieldName] as SPFieldUser; if (field != null && sourceItem[fieldName] != null) { SPFieldUserValue fieldValue = field.GetFieldValue(sourceItem[fieldName].ToString()) as SPFieldUserValue; if (fieldValue != null) { allManagers.Add(fieldValue.User); } else { SPFieldUserValueCollection fieldValues = field.GetFieldValue(sourceItem[fieldName].ToString()) as SPFieldUserValueCollection; foreach (SPFieldUserValue fv in fieldValues) { allManagers.Add(fv.User); } } } else { if (field == null) { throw new Exception("GetManager: field is null "); } } } return(allManagers); } catch (Exception ex) { throw ex; } }
public static SPUser GetSPUser(SPListItem item, string key) { SPFieldUser field = item.Fields[key] as SPFieldUser; if (field != null) { SPFieldUserValue fieldValue = field.GetFieldValue(item[key].ToString()) as SPFieldUserValue; if (fieldValue != null) { return(fieldValue.User); } } return(null); }
public static User ToUserModel(this SPListItem item, string fieldName) { SPFieldUser spuserField = (SPFieldUser)item.Fields.GetField(fieldName); SPFieldUserValue spuserFieldValue = (SPFieldUserValue)spuserField.GetFieldValue(Convert.ToString(item[fieldName])); User user = new User(); if (spuserFieldValue != null) { user.UserName = spuserFieldValue.User.LoginName; user.FullName = spuserFieldValue.User.Name; // Duc.VoTan Add user.ID = spuserFieldValue.LookupId; } return(user); }
/// <summary> /// Get User from SPField /// </summary> private static SPUser GetUser(SPListItem item, SPField userField) { SPUser returnUser = null; try { string currentValue = item[userField.Title].ToString(); SPFieldUser field = (SPFieldUser)userField; SPFieldUserValue fieldValue = (SPFieldUserValue)field.GetFieldValue(currentValue); returnUser = fieldValue.User; } catch { Logger.Instance.Error(string.Format("Exception looking for user: {0}", "userField"), DiagnosticsCategories.eCaseSite); returnUser = null; } return(returnUser); }
/// <summary> /// Assigns the role user to the AUFGABE (Task) /// </summary> protected void Button1_Click(object sender, EventArgs e) { bool success = true; SPWeb contextWeb = SPContext.Current.Web; SPList rollenzuteilung = contextWeb.Lists["Rollenzuteilung"]; foreach (SPListItem item in rollenzuteilung.Items) { try { String rolle = item["Rolle"].ToString(); if (rolle != null) { if (item["Verantwortlich"] != null) { SPFieldUser assignedTo = (SPFieldUser)rollenzuteilung.Fields["Verantwortlich"]; SPFieldUserValue user = (SPFieldUserValue)assignedTo.GetFieldValue(item["Verantwortlich"].ToString()); SPUser userObject = user.User; UpdateAufgabe(rolle, userObject); UpdateErgebnisse(rolle, userObject); } } } catch (Exception ex) { success = false; if (Rollenzuteilung_failed_errormessage.Text != ex.Message) { Rollenzuteilung_failed_errormessage.Text = Rollenzuteilung_failed_errormessage.Text + " " + ex.Message; } } } if (success) { Rollenzuteilung_erledigt.Visible = true; } else { Rollenzuteilung_failed.Visible = true; Rollenzuteilung_failed_errormessage.Visible = true; } }
public LookupItem GetCurrentEmployeeProcessing(SPListItem listItem) { SPFieldUser spuserField = (SPFieldUser)listItem.Fields.GetField(ShiftManagementList.ApprovedByField); SPFieldUserValue spuserFieldValue = (SPFieldUserValue)spuserField.GetFieldValue(Convert.ToString(listItem[ShiftManagementList.ApprovedByField])); if (spuserFieldValue != null) { EmployeeInfo approver = _employeeInfoDAL.GetByADAccount(spuserFieldValue.LookupId); string approvalStatus = listItem[listItem.Fields.GetField(CommonSPListField.ApprovalStatusField).Id] + string.Empty; if (approver != null && IsShiftApproved(listItem.ID) == false) { return(new LookupItem { LookupId = approver.ID, LookupValue = approver.FullName }); } } return(null); }
/// <summary> /// User object is embedded in the field value as SPUserField object /// </summary> /// <param name="item"></param> /// <param name="field"></param> /// <returns></returns> private string GetSPUser(SPListItem item, SPField field) { string alias = string.Empty; // get the FieldUser object SPFieldUser fieldUser = item.Fields[field.Title] as SPFieldUser; // get the FieldUserValue object if (item[field.Title] != null) { SPFieldUserValue spUserValue = fieldUser.GetFieldValue(item[field.Title].ToString()) as SPFieldUserValue; // split out the name if we have one string[] name = (!string.IsNullOrEmpty(spUserValue.User.Name)) ? spUserValue.User.Name.Split(GlobalConstants.COMMA_DELIMITER) : new string[] { string.Empty, string.Empty }; // sometimes Share Point User does not have full name string firstName = string.Empty; string lastName = string.Empty; if (name.Length == 1) { firstName = name[0].Trim(); lastName = name[0].Trim(); } else { firstName = name[1].Trim(); lastName = name[0].Trim(); } // create a new KPUser object - consider using this? KPUser kpUser = new KPUser() { ID = spUserValue.User.ID, Alias = spUserValue.User.LoginName, FirstName = firstName, LastName = lastName, Email = spUserValue.User.Email }; // returning only the name and alias pipe (|) delimited for now alias = string.Format("{0}|{1}", spUserValue.User.Name, kpUser.Alias.Split('\\')[1]); } return(alias); }
/// <summary>Returns all files for an assignment grouped by learner.</summary> /// <param name="assignmentKey">The key of the assignment.</param> public Dictionary <string, List <SPFile> > AllFiles(long assignmentKey) { string queryXml = @"<Where> <And> <Eq><FieldRef Name='{0}'/><Value Type='Text'>{1}</Value></Eq> <Eq><FieldRef Name='{2}'/><Value Type='Boolean'>1</Value></Eq> </And> </Where>"; queryXml = string.Format(CultureInfo.InvariantCulture, queryXml, ColumnAssignmentId, assignmentKey, ColumnIsLatest); SPQuery query = new SPQuery(); query.ViewAttributes = "Scope=\"Recursive\""; query.Query = queryXml; SPListItemCollection items = DropBoxList.GetItems(query); SPFieldUser learnerField = (SPFieldUser)DropBoxList.Fields[ColumnLearner]; Dictionary <string, List <SPFile> > files = new Dictionary <string, List <SPFile> >(); foreach (SPListItem item in items) { SPFile file = item.File; SPFieldUserValue learnerValue = (SPFieldUserValue)learnerField.GetFieldValue(item[ColumnLearner].ToString()); SPUser learner = learnerValue.User; List <SPFile> learnerFiles; string learnerAccount = learner.LoginName.Replace("\\", "-"); if (files.TryGetValue(learnerAccount, out learnerFiles) == false) { learnerFiles = new List <SPFile>(); files.Add(learnerAccount, learnerFiles); } learnerFiles.Add(item.File); } return(files); }
private static void updateFromAD(Dictionary <string, Guid> indexedTaxonomy, TermSet termSet, string ldapServerUrl, string principalCID, SPListItem item, SPFieldUser staffUserId) { var chalmerUserId = staffUserId.GetFieldValue(item[Constants.ChalmersID].ToString()) as SPFieldUserValue; if (chalmerUserId != null) { string username = chalmerUserId.User.LoginName; LoggingService.WriteTrace(EventSeverity.Information, "Got username: "******"UserLoginName has claims: " + userLoginName, LogCategory.ChalmersPublicWeb); } if (!string.IsNullOrEmpty(userLoginName)) { ADuser aduser = new ADuser(userLoginName) { LdapServerUrl = ldapServerUrl, GivenName = string.Empty, SN = string.Empty, Mail = string.Empty, Organisation = string.Empty, TelephoneNumber = string.Empty, OtherTelephone = string.Empty }; #if DEBUG string value = ConfigurationFile.GetGonfigurationFile(Chalmers.PublicWeb.Core.Constants.ConfigurationFilePath).GetSettingValue("StaffSyncCID"); if (value.ToLower().Contains(aduser.CID.ToLower().Replace("net\\", string.Empty))) { string x = "asdf"; System.Diagnostics.Debug.Print(x.ToString()); } #endif LoggingService.WriteTrace(EventSeverity.Information, "aduser CID = " + aduser.CID, LogCategory.ChalmersPublicWeb); string domain = WebConfigurationManager.AppSettings["CurrentDomain"]; if (string.IsNullOrEmpty(domain)) { aduser.ADDomainName = @"net\"; } else { aduser.ADDomainName = domain + @"\"; } if (aduser.CID.IndexOf(@"\", StringComparison.OrdinalIgnoreCase) > 0) { aduser.CIDWithoutDomain = aduser.CID.Remove(0, aduser.CID.IndexOf(@"\", StringComparison.OrdinalIgnoreCase) + 1); #if DEBUG if (aduser.CIDWithoutDomain.ToString().ToLower().Equals("kain") || aduser.CIDWithoutDomain.ToString().ToLower().Equals("anderska")) { string x = aduser.CIDWithoutDomain.ToString(); System.Diagnostics.Debug.Print(x); } #endif } List <Term> terms = null; TaxonomyField managedField = null; aduser = ADUserProfile.GetUserProfileFromAD(aduser); if (aduser != null) { bool adUnitsHaveChanged = taxFieldChanged(indexedTaxonomy, termSet, item, aduser, ref terms, ref managedField); System.Text.StringBuilder phoneNumbers = new System.Text.StringBuilder(); if (!string.IsNullOrEmpty(aduser.TelephoneNumber)) { phoneNumbers.Append(aduser.TelephoneNumber); } if (phoneNumbers.Length > 0 && !string.IsNullOrEmpty(aduser.OtherTelephone)) { phoneNumbers.Append(", "); } if (!string.IsNullOrEmpty(aduser.OtherTelephone)) { phoneNumbers.Append(aduser.OtherTelephone); } if ( hasUpdatedValues(item, aduser, phoneNumbers) || DateTime.Now.DayOfWeek == DayOfWeek.Saturday || adUnitsHaveChanged || (aduser.CID.Equals(principalCID)) ) { item["EduPersonOrcid"] = aduser.EduPersonOrcid; item["FieldStaffGivenname"] = aduser.GivenName; item["FieldStaffLastName"] = aduser.SN; item["FieldStaffFullName"] = aduser.GivenName + " " + aduser.SN; item["Title"] = aduser.GivenName + " " + aduser.SN; item["FieldStaffOrganisation"] = aduser.Organisation; item["FieldStaffTelephone"] = phoneNumbers.ToString(); item["OfficeRoomNumber"] = aduser.OfficeRoomNumber; item["OfficeStreet"] = aduser.OfficeStreet; item["OfficeFloorNumber"] = aduser.OfficeFloorNumber; setEmail(principalCID, item, aduser); if (adUnitsHaveChanged) { if (terms == null) { terms = new List <Term>(); } managedField.SetFieldValue(item, terms); } trySaveChanges(item, aduser); } } } } }
public static IList <User> ToUserModelList(this SPListItem item, string fieldName) { SPFieldUser spuserField = (SPFieldUser)item.Fields.GetField(fieldName); IList <User> UserList = new List <User>(); SPFieldUserValueCollection spuserFieldValueList = (SPFieldUserValueCollection)spuserField.GetFieldValue(Convert.ToString(item[fieldName])); if (spuserFieldValueList != null) { foreach (var userFieldValue in spuserFieldValueList) { User user = new User(); user.UserName = userFieldValue.User.LoginName; user.FullName = userFieldValue.User.Name; UserList.Add(user); } } return(UserList); }
string GetUserEmailFromField(string strUserFieldValue, SPField personOrGroupField) { string emailAddressToReturn = string.Empty; if (!string.IsNullOrEmpty(strUserFieldValue) && strUserFieldValue.Contains(";#")) { if (personOrGroupField != null && personOrGroupField.Type == SPFieldType.User) { try { SPFieldUser userField = (SPFieldUser)personOrGroupField; if (userField != null) { if (userField.AllowMultipleValues) { SPFieldUserValueCollection userFieldValueColl = (SPFieldUserValueCollection)userField.GetFieldValue(strUserFieldValue); if (userFieldValueColl != null && userFieldValueColl.Count > 0) { foreach (SPFieldUserValue userValue in userFieldValueColl) { SPUser spUser = userValue.User; if (spUser != null && !string.IsNullOrEmpty(spUser.Email)) { if (!string.IsNullOrEmpty(emailAddressToReturn)) { if (!emailAddressToReturn.Contains(spUser.Email)) { emailAddressToReturn = emailAddressToReturn + "," + spUser.Email; } } else { emailAddressToReturn = spUser.Email; } } } } } else { SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(strUserFieldValue); if (userFieldValue != null) { SPUser spUser = userFieldValue.User; if (spUser != null && !string.IsNullOrEmpty(spUser.Email)) { emailAddressToReturn = spUser.Email; } } } } } catch { } } } return(emailAddressToReturn); }
private static void CreateMetadataPair(List <GuidewireWS.trg_MetadataPair> metadata, string key, string propertyName, SPListItem item) { try { GuidewireWS.trg_MetadataPair metadataPair = new GuidewireWS.trg_MetadataPair(); //SPListItem listItem = properties.ListItem; SPListItem listItem = item; if (listItem.Fields.ContainsField(propertyName)) { metadataPair.key = key; SPField propertyField = listItem.Fields[propertyName]; switch (propertyField.Type) { case SPFieldType.User: { SPFieldUser userField = propertyField as SPFieldUser; SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(listItem[propertyName].ToString()); if (userFieldValue != null && userFieldValue.User != null) { metadataPair.value = userFieldValue.User.Name; } else { metadataPair.value = (string)listItem[propertyName]; } } break; case SPFieldType.Lookup: { SPFieldLookup lookupField = propertyField as SPFieldLookup; SPFieldLookupValue lookupFieldValue = (SPFieldLookupValue)lookupField.GetFieldValue(listItem[propertyName].ToString()); if (lookupFieldValue != null && lookupFieldValue.LookupValue != null) { metadataPair.value = lookupFieldValue.LookupValue; } } break; // Bamboo selectors have type of invalid but work like lookup case SPFieldType.Invalid: { if (listItem[propertyName] != null) { if (propertyField.TypeAsString == "BusinessData") { metadataPair.value = (string)listItem[propertyName]; } else { SPFieldLookup lookupField = propertyField as SPFieldLookup; SPFieldLookupValue lookupFieldValue = (SPFieldLookupValue)lookupField.GetFieldValue(listItem[propertyName].ToString()); if (lookupFieldValue != null && lookupFieldValue.LookupValue != null) { metadataPair.value = lookupFieldValue.LookupValue; } } } } break; case SPFieldType.DateTime: { metadataPair.value = listItem[propertyName].ToString(); } break; default: if (listItem[propertyName] != null) { if (propertyName == "Name") { String fileName = (string)listItem[propertyName]; if (fileName.Length > 80) { String extension = fileName.Substring(fileName.LastIndexOf(".")); String name = fileName.Substring(0, fileName.Length - extension.Length); fileName = name.Substring(0, 80 - extension.Length) + extension; } metadataPair.value = fileName; } else { metadataPair.value = (string)listItem[propertyName]; } } break; } metadata.Add(metadataPair); } } catch (Exception e) { LogError("CreateMetadataPair failed with exception: " + e.Message); } }
public string Get_Group(string fieldname, SPListItem item, SPWeb web, string sp2016url, string restfieldId) { var property = ""; if (item[fieldname] != null) { SPFieldUser iksorumluField = (SPFieldUser)item.Fields.GetField(fieldname); SPFieldUserValue iksorumluValue = (SPFieldUserValue)iksorumluField.GetFieldValue(item[fieldname].ToString()); if (iksorumluValue.User == null) { try { SPGroup iksorumlugrp = web.SiteGroups[iksorumluValue.LookupValue]; int newuserid = RestHelper.GetIdOfUser(sp2016url + "_api/web/sitegroups/GetByName('" + iksorumlugrp.Name + "')?$select=id", sp2016url + "_api/contextinfo", iksorumlugrp.Name); if (newuserid != 0) { property = "'" + restfieldId + "':'" + newuserid + "'"; } else { RestHelper.AddGroup("{ '__metadata':{ 'type': 'SP.Group' }, 'Title':'" + iksorumlugrp.Name + "' }", sp2016url + "_api/contextinfo", sp2016url + "_api/web/sitegroups"); newuserid = RestHelper.GetIdOfUser(sp2016url + "_api/web/sitegroups/GetByName('" + iksorumlugrp.Name + "')?$select=id", sp2016url + "_api/contextinfo", iksorumlugrp.Name); property = "'" + restfieldId + "':'" + newuserid + "'"; } } catch (Exception ex) { Console.WriteLine(ex.Message); property = "'" + restfieldId + "':null"; } } else { try { SPUser user = web.EnsureUser(iksorumluValue.User.LoginName); int user_id = RestHelper.GetIdOfUser(sp2016url + "_api/web/siteusers(@v)?@v=%27i%3A0%23.w%7C" + user.LoginName + "%27", sp2016url + "_api/contextinfo", user.LoginName); if (user_id != 0) { property = "'" + restfieldId + "':'" + user_id + "'"; } else { property = "'" + restfieldId + "':null"; } } catch (Exception) { property = "'" + restfieldId + "':null"; } } } else { property = "'" + restfieldId + "':null"; } return(property); }
private static void StartProcess(string url) { try { Console.Write("\nOpening '" + url + "'..."); using (SPSite oSite = new SPSite(url)) { string[] webUrls = new string[] { "/en/staff/", "/en/staff/edit/", "/sv/personal/", "/sv/personal/redigera/" }; foreach (string webUrl in webUrls) { Console.Write("\nOpening '" + webUrl + "'..."); using (SPWeb oWeb = oSite.OpenWeb(webUrl)) { PublishingWeb pweb = PublishingWeb.GetPublishingWeb(oWeb); SPList staffSitePagesList = pweb.PagesList; SPListItemCollection col = staffSitePagesList.Items; SPField fieldFrom = (staffSitePagesList).Fields.GetField(fieldNameFrom); //SPField fieldTo = (staffSitePagesList).Fields.GetField(fieldNameTo); log("\nStarting processing pages..."); int i = 0; foreach (SPListItem item in col) { log(i++ + " Doing: " + item.Url); SPFieldUser staffUserId = item.Fields[fieldFrom.Id] as SPFieldUser; if (item[fieldNameFrom] == null) { log(" Item does not contain CID-value."); continue; } var chalmerUserId = staffUserId.GetFieldValue(item[fieldNameFrom].ToString()) as SPFieldUserValue; if (item[fieldNameTo] == null) { log(" To field is null"); } else { log(" To field is: " + item[fieldNameTo].ToString()); } string username = chalmerUserId.User.LoginName.ToLower().Replace("net\\", string.Empty); log(" Writing value: " + username); item[fieldNameTo] = username; log(" To field value is now: " + item[fieldNameTo].ToString()); if (item.File.Level != SPFileLevel.Checkout) { log(" Saving..."); item.SystemUpdate(false); log(" Done."); } else { log(" Checked out file. Can't update."); } } } } } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.Write("\n\nAn Error occured " + ex.Message + "\n\nEnsure that you have Administrative rights.\n"); // Also ensure platform target is x64 and not x86. Console.ForegroundColor = ConsoleColor.Gray; PrintHelpText(); } sendEmail("*****@*****.**", "Logg value from user field to text field", runLog.ToString()); }
private void BuildHTMLTableRowsForEachComment() { SPSite currentSite = SPContext.Current.Site; SPWeb currentWeb = SPContext.Current.Web; SPList commentsList = currentWeb.Lists.TryGetList("Comments"); // insert a table to serve as an anchor // for javascript to target and inject html dynamically // notice the display none css property pnlCommentsContainer.Controls.Add(new LiteralControl("<div style=\"float:left;width:100%\"> <table class=\"ms-socialCommentItem\" style=\" display: none;\" id=\"commentItem_PlaceHolder\"></table></div>")); SPQuery q = new SPQuery(); //q.Query = "<Where><And><Eq><FieldRef Name=\"ListId\" /><Value Type=\"Text\">" + _listId.ToString("D") + "</Value></Eq><Eq><FieldRef Name=\"ItemId\" /><Value Type=\"Text\">" + _itemId + "</Value></Eq></And></Where><OrderBy><FieldRef Name=\"Created\" Ascending=\"False\" /></OrderBy>"; q.Query = "<Where><And><Or><Eq><FieldRef Name=\"ListId\" /><Value Type=\"Text\">" + new Guid(_listId).ToString("D") + "</Value></Eq><Eq><FieldRef Name=\"ListId\" /><Value Type=\"Text\">" + new Guid(_listId).ToString("B") + "</Value></Eq></Or><Eq><FieldRef Name=\"ItemId\" /><Value Type=\"Text\">" + _itemId + "</Value></Eq></And></Where><OrderBy><FieldRef Name=\"Created\" Ascending=\"False\" /></OrderBy></Query>"; if (commentsList != null) { SPListItemCollection items = commentsList.GetItems(q); foreach (SPListItem item in items) { // get user object SPFieldUser author = null; author = (SPFieldUser)item.Fields[SPBuiltInFieldId.Author]; SPFieldUserValue user = (SPFieldUserValue)author.GetFieldValue(item[SPBuiltInFieldId.Author].ToString()); SPUser userObject = user.User; if (userObject == null) { continue; } //get user picture from user id SPList userInfoList = Web.SiteUserInfoList; SPListItem userItem = userInfoList.GetItemById(userObject.ID); string userPictureUrl = currentSite.MakeFullUrl(currentWeb.ServerRelativeUrl) + "/_layouts/epmlive/images/O14_person_placeHolder_32.png"; SPField fldPicture = null; try { fldPicture = userItem.Fields.GetFieldByInternalName("Picture"); } catch (ArgumentException x) { fldPicture = null; } if (fldPicture != null) { try { string[] picUrls = userItem[userItem.Fields.GetFieldByInternalName("Picture").Id].ToString().Split(','); userPictureUrl = picUrls[0]; } catch { userPictureUrl = currentSite.MakeFullUrl(currentWeb.ServerRelativeUrl) + "/_layouts/epmlive/images/O14_person_placeHolder_32.png"; } } string createdDate = item[commentsList.Fields.GetFieldByInternalName("Created").Id].ToString(); string userComment = string.Empty; object testObj = null; try { testObj = item[commentsList.Fields.GetFieldByInternalName("Comment").Id]; } catch { } if (testObj != null && !string.IsNullOrEmpty(item[commentsList.Fields.GetFieldByInternalName("Comment").Id].ToString())) { userComment = item[commentsList.Fields.GetFieldByInternalName("Comment").Id].ToString(); } if (userObject.ID == Web.CurrentUser.ID) { pnlCommentsContainer.Controls.Add(new LiteralControl("<div style=\"float:left;width:100%\"><table class=\"ms-socialCommentItem customCommentItem\" id=\"commentItem_" + item.ID.ToString() + "\">" + "<tbody>" + "<tr>" + "<td class=\"socialcomment-image\" vAlign=\"left\" rowSpan=\"2\">" + "<img alt=\"User Photo\" style=\"width:32px;height:32px\" src=\"" + userPictureUrl + "\">" + "</td>" + "<td class=\"socialcomment-IMPawn\" rowSpan=\"2\" align=\"left\">" + "<div id=\"DataFrameManager_ctl02_socomIM_0\" class=\"socialcomment-IMPawn\">" + "<span>" + "<img id=\"commentAvailBubble" + item.ID.ToString() + "\" alt=\"Status indicator\" src=\"/_layouts/images/imnhdr.gif\" width=\"12\" onload=\"QueuePopulateIMNRC('" + userObject.Email + "',this);\" height=\"12\" ShowOfflinePawn=\"1\">" + "</span>" + "</div>" + "</td>" + "<td class=\"socialcomment-top\" vAlign=\"left\">" + "<span class=\"socialcomment-username\">" + "<a href=\"" + _userProfileUrl + "\" target=\"_parent\">" + userObject.Name + "</a>" + "</span>" + "<span class=\"socialcomment-time\">" + createdDate.ToString() + "</span>" + "</td>" + "<td class=\"socialcomment-top socialcomment-cmdlink\" vAlign=\"right\">" + "<span class=\"socialcomment-cmdlink\">" + "<a onclick=\"javaScript:document.getElementById(\'" + hdnCommentItemId.ClientID + "\').value=\'" + item.ID.ToString() + "\'; EnterEditMode(" + item.ID.ToString() + "); return false;\" href=\'#\'>Edit</a>" + "<span class=\"separator\"> | </span>" + "<a onclick=\"javaScript:document.getElementById(\'" + hdnCommentItemId.ClientID + "\').value=\'" + item.ID.ToString() + "\'; ajaxPost(\'DeleteComment\'); return false;\" href=\'#\'>Delete</a>" + "</span>" + "</td>" + "</tr>" + "<tr>" + "<td class=\"socialcomment-bottom\" vAlign=\"left\" colSpan=\"3\">" + "<div id=\"divComment_" + item.ID.ToString() + "\" class=\"socialcomment-contents-TRC\">" + userComment + "</div>" + "</td>" + "</tr>" + "</tbody>" + "</table></div>")); } else { pnlCommentsContainer.Controls.Add(new LiteralControl("<div style=\"float:left;width:100%\"><table class=\"ms-socialCommentItem customCommentItem\" >" + "<tbody>" + "<tr>" + "<td class=\"socialcomment-image\" vAlign=\"left\" rowSpan=\"2\">" + "<img alt=\"User Photo\" style=\"width:32px;height:32px\" src=\"" + userPictureUrl + "\">" + "</td>" + "<td class=\"socialcomment-IMPawn\" rowSpan=\"2\" align=\"left\">" + "<div class=\"socialcomment-IMPawn\">" + "<span>" + "<img id=\"commentAvailBubble" + item.ID.ToString() + "\" alt=\"Status indicator\" src=\"/_layouts/images/imnhdr.gif\" width=\"12\" onload=\"QueuePopulateIMNRC('" + userObject.Email + "',this);\" height=\"12\" ShowOfflinePawn=\"1\">" + "</span>" + "</div>" + "</td>" + "<td class=\"socialcomment-top\" vAlign=\"left\">" + "<span class=\"socialcomment-username\">" + "<a href=\"" + (currentWeb.ServerRelativeUrl == "/" ? "" : currentWeb.ServerRelativeUrl) + "/_layouts/userdisp.aspx?Force=True&ID=" + userObject.ID + "&source" + HttpContext.Current.Request.Url.AbsolutePath + "\" target=\"_parent\">" + userObject.Name + "</a>" + "</span>" + "<span class=\"socialcomment-time\">" + createdDate.ToString() + "</span>" + "</td>" + // the edit and delete links are taken out for comments // not posted by currently logged in user "</tr>" + "<tr>" + "<td class=\"socialcomment-bottom\" vAlign=\"left\" colSpan=\"3\">" + "<div id=\"divComment_" + item.ID.ToString() + "\" class=\"socialcomment-contents-TRC\" >" + userComment + "</div>" + "</td>" + "</tr>" + "</tbody>" + "</table></div>")); } } } }
private void AddCommentersFields() { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite tempSite = new SPSite(SPContext.Current.Web.Url)) { using (SPWeb tempWeb = tempSite.OpenWeb()) { tempWeb.AllowUnsafeUpdates = true; SPList originList = tempWeb.Lists[new Guid(_listId)]; // add commenters field SPField fldCommenters = null; try { fldCommenters = originList.Fields.GetFieldByInternalName("Commenters"); } catch (System.ArgumentException x) { fldCommenters = null; } tempWeb.AllowUnsafeUpdates = true; if (fldCommenters == null) { string fldCommentersName = originList.Fields.Add("Commenters", SPFieldType.Note, false); fldCommenters = originList.Fields.GetFieldByInternalName(fldCommentersName) as SPFieldMultiLineText; fldCommenters.Sealed = false; fldCommenters.Hidden = true; fldCommenters.AllowDeletion = false; fldCommenters.DefaultValue = string.Empty; fldCommenters.Update(); originList.Update(); } SPField fldCommentersRead = null; // add commentersread field try { fldCommentersRead = originList.Fields.GetFieldByInternalName("CommentersRead"); } catch (System.ArgumentException x) { fldCommentersRead = null; } if (fldCommentersRead == null) { string fldCommentersReadName = originList.Fields.Add("CommentersRead", SPFieldType.Note, false); fldCommentersRead = originList.Fields.GetFieldByInternalName(fldCommentersReadName) as SPFieldMultiLineText; fldCommentersRead.Hidden = true; fldCommentersRead.Sealed = false; fldCommentersRead.AllowDeletion = false; fldCommentersRead.DefaultValue = string.Empty; fldCommentersRead.Update(); originList.Update(); } tempWeb.Update(); SPListItem originListItem = null; List <int> laCommenters = new List <int>(); List <int> laCommentersRead = new List <int>(); if (originList != null) { originListItem = originList.GetItemById(int.Parse(_itemId)); } if (originListItem != null) { string sCommenters = originListItem[originList.Fields.GetFieldByInternalName("Commenters").Id] != null ? originListItem[originList.Fields.GetFieldByInternalName("Commenters").Id].ToString() : string.Empty; foreach (string s in sCommenters.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { if (!string.IsNullOrEmpty(s.Trim())) { laCommenters.Add(int.Parse(s)); } } string sCommentersRead = originListItem[originList.Fields.GetFieldByInternalName("CommentersRead").Id] != null ? originListItem[originList.Fields.GetFieldByInternalName("CommentersRead").Id].ToString() : string.Empty; foreach (string s in sCommentersRead.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { if (!string.IsNullOrEmpty(s.Trim())) { laCommentersRead.Add(int.Parse(s)); } } // get user object SPFieldUser author = null; author = (SPFieldUser)originListItem.Fields[SPBuiltInFieldId.Author]; SPFieldUserValue userVal = (SPFieldUserValue)author.GetFieldValue(originListItem[SPBuiltInFieldId.Author].ToString()); SPUser authorObj = userVal.User; // (if current user is item creator OR in commenters column OR in the assigned to field) AND not in commentersread column if (((authorObj != null && SPContext.Current.Web.CurrentUser.ID == authorObj.ID) || (laCommenters.Contains(SPContext.Current.Web.CurrentUser.ID)) || (CommentManager.UserIsAssigned(SPContext.Current.Web.CurrentUser.ID, originListItem))) && (!laCommentersRead.Contains(SPContext.Current.Web.CurrentUser.ID))) { string sNewCommentersRead = originListItem[originList.Fields.GetFieldByInternalName("CommentersRead").Id] != null ? originListItem[originList.Fields.GetFieldByInternalName("CommentersRead").Id].ToString() : string.Empty; List <int> newCommenters = new List <int>(); if (!string.IsNullOrEmpty(sNewCommentersRead)) { string[] vals = sNewCommentersRead.Split(','); foreach (string s in vals) { if (!string.IsNullOrEmpty(s.Trim())) { newCommenters.Add(int.Parse(s)); } } } if (!newCommenters.Contains(SPContext.Current.Web.CurrentUser.ID)) { newCommenters.Add(SPContext.Current.Web.CurrentUser.ID); } StringBuilder sb = new StringBuilder(); foreach (int i in newCommenters) { sb.Append(i.ToString() + ","); } string s1 = sb.ToString(); s1 = s1.Remove(s1.LastIndexOf(",")); originListItem[originList.Fields.GetFieldByInternalName("CommentersRead").Id] = s1; } SocialEngineProxy.SetTransaction(originListItem.Web.ID, originListItem.ParentList.ID, originListItem.ID, "Comments", originListItem.Web); originListItem.SystemUpdate(); } } } }); }