/// <summary> /// Responds to delegation updating. /// </summary> /// <param name="properties">The properties.</param> /// <param name="web">The web.</param> public static void RespondToDelegationUpdating(SPItemEventProperties properties, SPWeb web) { SPFieldLookupValue statusValue = new SPFieldLookupValue(properties.AfterProperties[DelegationsFields.DelegationStatus.Name].ToString()); string description = properties.AfterProperties[DelegationsFields.DelegationNote.Name].ToString(); var list = web.Lists[properties.ListId]; var listItem = list.Items.GetItemById(properties.ListItemId); if (statusValue.LookupId == Draft) { if (String.IsNullOrEmpty(description)) { properties.Cancel = true; properties.ErrorMessage = "Description cannot be empty."; properties.Status = SPEventReceiverStatus.CancelWithError; } else { SPFieldUserValue userValue = new SPFieldUserValue(properties.Web, properties.ListItem[SPBuiltInFieldId.Author].ToString()); Permissions.GrantPermission(web, listItem, userValue.User.Name, SPRoleType.Contributor); SendMail(web, userValue.User.Email, description); } } else if (statusValue.LookupId == ForApproval) { SPFieldUserValue userValue = new SPFieldUserValue(web, properties.ListItem[SPBuiltInFieldId.Author].ToString()); Permissions.RevokePremission(web, listItem, userValue.User.Name); SendMail(web, approvalEmail, properties.ListItem.Url); } else if (statusValue.LookupId == Approved) { SPFieldUserValue userValue = new SPFieldUserValue(properties.Web, properties.ListItem[SPBuiltInFieldId.Author].ToString()); Permissions.GrantPermission(web, listItem, userValue.User.Name, SPRoleType.Reader); SendMail(web, userValue.User.Email, properties.ListItem.Url); } }
/// <summary> /// Создание на основе значения поля элемента списка /// </summary> /// <param name="web">Сайт</param> /// <param name="fieldValue">Значение поля</param> public UserData(SPWeb web, SPFieldUserValue fieldValue) { if (fieldValue.User != null) { Init(fieldValue.User); } else { if (string.IsNullOrEmpty(fieldValue.LookupValue)) { this.Name = string.Empty; this.Email = string.Empty; //this.Type = UserDataType.Empty; } else { try { SPGroup group = web.SiteGroups[fieldValue.LookupValue]; Init(group); } catch { #warning need log with warning level this.Id = fieldValue.LookupId; this.Name = fieldValue.LookupValue; this.LoginName = fieldValue.User.LoginName; //this.Type = UserDataType.UnKnown; } } } }
/// <summary> /// An item was updated. /// </summary> public override void ItemUpdated(SPItemEventProperties properties) { base.ItemUpdated(properties); SPListItem item = properties.ListItem; var createdByLeaveRequest = new SPFieldUserValue(properties.Web,item["Created By"].ToString()); if (item["Status"].ToString() == "Approved") { SPSite myDestinationSite = new SPSite(properties.WebUrl); SPWeb myDestinationWeb = myDestinationSite.OpenWeb(); SPList myDestinationList = myDestinationWeb.Lists["LeaveDays"]; SPListItem myDestinationListItem = myDestinationList.Items[0]; var EmpNameLeavedays = new SPFieldUserValue(properties.Web, myDestinationListItem["Employee Name"].ToString()); myDestinationListItem["PaidLeaveBalance"] = item["Dup Paid Leave Balance"];//SourceEmpId; myDestinationListItem["PaidLeaveUtilized"] = item["Dup Paidleaveutilize"];// SourceEmpName; myDestinationWeb.AllowUnsafeUpdates = true; if(createdByLeaveRequest.User.ID == EmpNameLeavedays.User.ID) { myDestinationListItem.Update(); myDestinationWeb.AllowUnsafeUpdates = false; } } }
/// <summary> /// Ensures the user by lookup value. /// </summary> /// <param name="web">The web.</param> /// <param name="userValue">The user value.</param> /// <returns>SPUser object.</returns> public static SPUser EnsureUserByLookupValue(this SPWeb web, string userValue) { if (userValue.IsNullOrEmpty()) return null; var user = new SPFieldUserValue(web, userValue); return user.LookupId == -1 ? web.EnsureUser(user.LookupValue) : user.User; }
/// <summary> /// Converts the specified value. /// </summary> /// <param name="value">The value.</param> /// <param name="arguments">The arguments.</param> /// <returns> /// The converted value. /// </returns> public override object Convert(object value, SharePointListItemConversionArguments arguments) { UserValue userValue = null; var sharepointUserValue = new SPFieldUserValue(arguments.ListItem.Web, value as string); var principal = sharepointUserValue.User; userValue = principal != null ? new UserValue(principal) : null; return userValue; }
/// <summary> /// Sends the leader notification. /// </summary> /// <param name="properties">The properties.</param> private void SendLeaderNotification(SPItemEventProperties properties) { string title = properties.ListItem[SPBuiltInFieldNames.Title].ToString(); string subject = string.Format(Values.LeaderApprovalRequestMailHeader, title); string taskLink = EmailHelper.GenerateTaskLink(properties.Web, properties.ListItemId, title); string content = string.Format(Values.LeaderApprovalRequestMailContent, taskLink); string serviceMail = Values.HolidayServiceMailAddress; SPFieldUserValue manager = new SPFieldUserValue(properties.Web, properties.ListItem[SPBuiltInFieldId.AssignedTo].ToString()); EmailHelper.SendEmail(properties.Web, serviceMail, manager.User.Email, subject, content); }
//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 spalte) { //Laden des userFields aus dem übergebenem Element (listitem) und der Spalte, die einen Nutzer enthält (spalte) SPFieldUser userField = (SPFieldUser)listitem.Fields.GetField(spalte); SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(listitem[spalte].ToString()); SPUser user = userFieldValue.User; //Zuweisen des Anzeigenamens und Rückgabe desselben string anzeigename = user.Name; return(anzeigename); }
/// <summary> /// Asynchronous After event that occurs after a new item has been added to its containing object. /// </summary> /// <param name="properties">Properties object.</param> public override void ItemAdded(SPItemEventProperties properties) { base.ItemAdded(properties); SPFieldUserValue author = new SPFieldUserValue(properties.Web, properties.ListItem[SPBuiltInFieldId.Author].ToString()); DateTime? start = properties.ListItem[HolidaysFields.StartDate.Name] as DateTime?; DateTime? end = properties.ListItem[HolidaysFields.EndDate.Name] as DateTime?; string title = string.Format("{0} ({1:d} - {2:d})", author.User.Name, start, end); properties.ListItem[SPBuiltInFieldId.Title] = title; properties.ListItem.Update(); }
/// <summary> /// An item was deleted. /// </summary> public override void ItemDeleted(SPItemEventProperties properties) { SPSecurity.RunWithElevatedPrivileges(delegate() { SPFieldUserValue keyPersonValue = new SPFieldUserValue(properties.Web.Site.RootWeb, properties.ListItem["KeyPerson"].ToString()); properties.Web.RoleAssignments.Remove(keyPersonValue.User); properties.Web.Update(); }); base.ItemDeleted(properties); }
private void CreateTaskWithPMTaskContentType_MethodInvoking(object sender, EventArgs e) { taskId = Guid.NewGuid(); contentTypeId = HolidayContentTypes.ProjectLeaderTask.Id; var author = workflowProperties.Item[SPBuiltInFieldNames.CreatedBy]; SPFieldUserValue employee = new SPFieldUserValue(workflowProperties.Web, workflowProperties.Item[SPBuiltInFieldNames.CreatedBy].ToString()); var start = workflowProperties.Item[HolidaysFields.StartDate.Name]; var end = workflowProperties.Item[HolidaysFields.EndDate.Name]; SPFieldUserValue manager = new SPFieldUserValue(workflowProperties.Web, workflowProperties.Item[HolidaysFields.ProjectLeader.Name].ToString()); taskProperties.AssignedTo = manager.User.LoginName; taskProperties.Title = string.Format("{0} ({1:d} - {2:d})", employee.User.Name, start, end); }
public int SaveOrUpdate(ShiftManagement newItem) { int returnId = 0; using (SPSite site = new SPSite(SiteUrl)) { using (SPWeb web = site.OpenWeb()) { web.AllowUnsafeUpdates = true; SPList splist = web.GetList($"{web.Url}{ListUrl}"); SPListItem spListItem; if (newItem.ID > 0) { spListItem = splist.GetItemById(newItem.ID); if (spListItem != null) { spListItem["Modified"] = System.DateTime.Now.ToString(StringConstant.DateFormatTZForCAML); //spListItem[StringConstant.ShiftManagementList.CommonAddApprover1Field] = ConvertMultUser(newItem.CommonAddApprover1, web); } } else { spListItem = splist.AddItem(); spListItem[StringConstant.ShiftManagementList.MonthField] = newItem.Month; spListItem[StringConstant.ShiftManagementList.YearField] = newItem.Year; spListItem[StringConstant.CommonSPListField.ApprovalStatusField] = newItem.ApprovalStatus; var requester = _employeeInfoDAL.GetByADAccount(web.CurrentUser.ID); var requesterLookupId = newItem.Requester.LookupId == 0 ? requester.ID : newItem.Requester.LookupId; spListItem[StringConstant.CommonSPListField.RequesterField] = requesterLookupId; spListItem[StringConstant.CommonSPListField.CommonDepartmentField] = newItem.Department.LookupId; spListItem[StringConstant.CommonSPListField.CommonLocationField] = newItem.Location.LookupId; SPUser approver = SPContext.Current.Web.EnsureUser(newItem.ApprovedBy.UserName); SPFieldUserValue approverValue = new SPFieldUserValue(SPContext.Current.Web, approver.ID, approver.LoginName); spListItem[StringConstant.ShiftManagementList.ApprovedByField] = approverValue; if (newItem.RequestDueDate != null && newItem.RequestDueDate != default(DateTime)) { spListItem[StringConstant.CommonSPListField.CommonReqDueDateField] = newItem.RequestDueDate; } //spListItem[StringConstant.ShiftManagementList.CommonAddApprover1Field] = ConvertMultUser(newItem.CommonAddApprover1, web); } spListItem.Update(); returnId = spListItem.ID; web.AllowUnsafeUpdates = false; } } return(returnId); }
/// <summary> /// Reads a field value from a list item version /// </summary> /// <param name="itemVersion">The list item version we want to extract a field value from</param> /// <param name="fieldInternalName">The key to find the field in the item's columns</param> /// <returns>The ImageValue extracted from the list item's field</returns> public override UserValue ReadValueFromListItemVersion(SPListItemVersion itemVersion, string fieldInternalName) { var fieldValue = itemVersion[fieldInternalName]; if (fieldValue != null) { var userFieldVal = new SPFieldUserValue(itemVersion.ListItem.ParentList.ParentWeb, fieldValue.ToString()); return(new UserValue(userFieldVal.User)); } return(null); }
/// <summary> /// Reads a field value from a DataRow returned by a CAML query /// </summary> /// <param name="web">The context's web</param> /// <param name="dataRowFromCamlResult">The CAML-query-result data row we want to extract a field value from</param> /// <param name="fieldInternalName">The key to find the field among the data row cells</param> /// <returns>The value extracted from the data row's corresponding cell</returns> public override PrincipalValue ReadValueFromCamlResultDataRow(SPWeb web, DataRow dataRowFromCamlResult, string fieldInternalName) { var fieldValue = dataRowFromCamlResult[fieldInternalName]; if (fieldValue != null && fieldValue != System.DBNull.Value) { var userFieldVal = new SPFieldUserValue(web, fieldValue.ToString()); return(new PrincipalValue(userFieldVal.User.ID)); } return(null); }
private void checkReportFromManager() { using (SPSite site = new SPSite("http://xrm")) { using (SPWeb webApp = site.OpenWeb("crm")) { Guid guidObj = new Guid("6318a62c-dfbd-4452-af42-919e3c66f011"); //получаем список обьекты по GUID SPList listObj = webApp.Lists[guidObj]; SPListItemCollection spListObjectsColl = listObj.Items; Guid guidInfoList = new Guid("043891f9-e187-4365-9d80-dfa908f5ced0"); //получаем список записей от менеджеров по GUID SPList listInfo = webApp.Lists[guidInfoList]; SPListItemCollection spListInfoColl = listInfo.Items; DateTime CurrentDay = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).AddDays(-7); //получаем записи из списка обьектов var listObjects = from i in spListObjectsColl.OfType <SPListItem>() where i["Status"].ToString() == "Текущий" && i["Manager"] != null select i; //записи из списка с информацией от управляющих созданых за последние 7 дней. var listqueryInfoColl = from i in spListInfoColl.OfType <SPListItem>() where ((DateTime)i["Created"]).Date >= CurrentDay && i["Object"] != null select i; //создаем список из ИД оьтектов списка информации от управляющих List <int> listidobjects = new List <int>(); foreach (SPListItem item in listqueryInfoColl) { SPFieldLookupValue fieldLookupValue = new SPFieldLookupValue(item["Object"].ToString()); int lookupIDObject = fieldLookupValue.LookupId; listidobjects.Add((int)lookupIDObject); } // выбираем обьекты у которых нет записей var noexistObjectList = from itemObj in listObjects where !listidobjects.Any(infoitem => (infoitem.ToString() == itemObj["ID"].ToString())) select itemObj; //перебираем записи, от правляем уведомления управляющим foreach (SPListItem item in noexistObjectList) { SPFieldUserValue managercantin = new SPFieldUserValue(webApp, item["Manager"].ToString()); //учетная запись управляющего if (IsValidEmailId(managercantin.User.Email)) { sendEmail(managercantin.User.Email, "Журнал - Информация от управляющих", managercantin.User.Name); } } } } }
public void generateInitialTasks(Matter matter, string taskListLocation) { StringBuilder tasksCreated = new StringBuilder(); // Grab the tasks created for log output. // read LitigationTasks.config (custom XML file) to dataset for value retrieval. DataSet ds = new DataSet(); try { ds.ReadXml("LitigationTasks.config"); } catch (Exception ex) { log.addError(ex.ToString()); } #region Get the litigation manager user as SPFieldUserValue // This strange articulation must be done because the task list is located in a different web, and therefore the user object has a different key/id // While SharePoint could perform an internal cast of SPUser.ToString(), it seems retrival from the hashtable using the addListItem method prevents this. SPFieldUserValue taskAssignedTo = null; try { using (SPWeb tasksWeb = new SPSite(taskListLocation).OpenWeb()) { // Ensure the Litigation Manager has access to the web containing tasks, or SharePoint might kibby and die. SPUser user = tasksWeb.EnsureUser(matter.LitigationManagerSPUser.ToString()); taskAssignedTo = new SPFieldUserValue(tasksWeb, user.ID, user.LoginName); } } catch (Exception ex) { log.addWarning("Unable to determine an appropriate user to assign tasks to for matter " + matter.LMNumber + ", so they will need to be assigned manually." + " The Exception was: " + ex.ToString()); } #endregion foreach (DataRow task in ds.Tables[0].Rows) { var description = task["description"]; var associatedURL = task["url"]; var daysUntilDue = Convert.ToInt32(task["daysuntildue"]); Hashtable taskFields = new Hashtable(); taskFields.SetProperty("Due Date", DateTime.Now.AddDays(daysUntilDue)); taskFields.SetProperty("Matter Name", matter.MatterName); taskFields.SetProperty("Task Description", description); taskFields.SetProperty("Assigned To", taskAssignedTo); taskFields.SetProperty("Allow Manual Completion", true); taskFields.SetProperty("Related URL", associatedURL); taskFields.SetProperty("Associated Site ID", matter.LMNumber); taskFields.SetProperty("Data Source", "LitMatterSyncService"); taskFields.SetProperty("Additional Source Information", "Provisioned with Site"); addListItem(taskListLocation, taskFields); tasksCreated.AppendLine(description.ToString() + "(Due in " + daysUntilDue.ToString() + " days)"); } log.addInformation("Generated the following initial tasks for matter " + matter.LMNumber + "\n" + tasksCreated); }
public void Execute(TaskActionArgs actionData) { UpdateWorkflowItemWithKeywordSettings updateWFItemSettings = actionData.GetActionData<UpdateWorkflowItemWithKeywordSettings>(); if (!actionData.WorkflowProperties.Item.Fields.ContainFieldId(new Guid(updateWFItemSettings.FieldId))) return; SPField fieldUpdate = actionData.WorkflowProperties.Item.Fields[new Guid(updateWFItemSettings.FieldId)]; if (!fieldUpdate.ReadOnlyField && !fieldUpdate.Hidden) { try { SPListItem item = actionData.WorkflowProperties.Item; switch (fieldUpdate.Type) { case SPFieldType.DateTime: bool isConvertSuccessful = false; DateTime updated = CovnertKeywordToDateTime(updateWFItemSettings.Value, out isConvertSuccessful); if (isConvertSuccessful) { SPFieldDateTime fieldDate = (SPFieldDateTime)fieldUpdate; item[fieldUpdate.Id] = updated; } break; case SPFieldType.User: if (updateWFItemSettings.Value.Trim().ToUpper() == "[ME]") { //UpdateWorkflowItemHelper.DoUpdateItem(item, fieldUpdate, actionData.WorkflowProperties.OriginatorUser.LoginName); SPFieldUser fieldUser = (SPFieldUser)fieldUpdate; SPUser initiator = actionData.WorkflowProperties.OriginatorUser; SPFieldUserValue userValue = new SPFieldUserValue(item.Web, initiator.ID, initiator.Name); item[fieldUpdate.Id] = userValue; } break; case SPFieldType.Text: break; } item[SPBuiltInFieldId.WorkflowVersion] = 1; item.SystemUpdate(); } catch { Utility.LogInfo("Error update workfkow item field " + fieldUpdate.Title + " with data " + updateWFItemSettings.Value + " is error", "TVMCORP.TVS.WORKFLOWS"); } } }
public static SPFieldUserValue TryGetFieldUserValue(this SPListItem spListItem, dynamic fieldIdentifier) { SPFieldUserValue defaultValue = null; SPField field = null; try { if (fieldIdentifier is Guid) { if (!spListItem.Fields.Contains((Guid)fieldIdentifier)) { return(defaultValue); } field = spListItem.Fields[(Guid)fieldIdentifier]; } else if (fieldIdentifier is int) { if (spListItem.Fields[(int)fieldIdentifier] == null) { return(defaultValue); } field = spListItem.Fields[(int)fieldIdentifier]; } else if (fieldIdentifier is string) { if (!spListItem.Fields.ContainsField(fieldIdentifier as string)) { if (!spListItem.Fields.ContainsFieldWithStaticName(fieldIdentifier as string)) { return(defaultValue); } field = spListItem.Fields.TryGetFieldByStaticName(fieldIdentifier as string); } else { field = spListItem.Fields.GetField(fieldIdentifier as string); } } if (field == null) { return(defaultValue); } defaultValue = new SPFieldUserValue(spListItem.Web, spListItem[field.Id].ToString()); return(defaultValue); } catch { return(defaultValue); } }
public static SPFieldUserValueCollection PickUserValue(PeopleEditor peopleEditor) { SPFieldUserValueCollection fieldUserValues = new SPFieldUserValueCollection(); foreach (PickerEntity entity in peopleEditor.ResolvedEntities) { SPPrincipal principal = MOSSPrincipal.FindUserOrSiteGroup(entity.Key); SPFieldUserValue userValue = new SPFieldUserValue(MOSSContext.Current.Web, principal.ID,principal.Name); fieldUserValues.Add(userValue); } return fieldUserValues; }
public UserPickerEntity EnsureUser(SPFieldUserValue spUserVal) { var upe = new UserPickerEntity(spUserVal.User == null ? spUserVal.LookupValue : spUserVal.User.LoginName); upe.DisplayText = spUserVal.User == null ? spUserVal.LookupValue : spUserVal.User.Name; if (spUserVal.User != null) { upe.EntityData = new UserPickerEntityData(); upe.EntityData.Email = spUserVal.User.Email; upe.EntityData.PrincipalType = "User"; } return(this.EnsureUser(upe)); }
/// <summary> /// Создание на основе значения (в текстовом виде) поля элемента списка /// </summary> /// <param name="userFieldValue"></param> /// <param name="site"></param> public UserData(string userFieldValue, SPSite site) { SPFieldUserValue field = new SPFieldUserValue(site.RootWeb, userFieldValue); if (field.User != null) { Init(field.User); } else { SPGroup group = site.RootWeb.SiteGroups[field.LookupValue]; Init(group); } }
public override object ConvertFieldValueToPropertyValue(PropertyInfo propertyInfo, object fieldValue) { var userValue = new SPFieldUserValue(Web, fieldValue.ToString()); var principal = userValue.User ?? (SPPrincipal)Web.SiteGroups.GetByID(userValue.LookupId); return(new SPPrincipalInfo { ID = principal.ID, Name = principal.Name, UrlMask = (principal is SPGroup) ? "/_layouts/people.aspx?MembershipGroupId=" : "/_layouts/userdisp.aspx?ID=", IsUser = principal is SPUser }); }
protected void assign_role(SPSite site, SPListItem item, string field_name, string field_guid, SPRoleDefinition definition) { try { string value = item[field_name].ToString(); SPFieldUserValue field_user_value = (SPFieldUserValue)item.Fields[new Guid(field_guid)].GetFieldValue(value); bind_role(item, field_user_value.User, definition); } catch (Exception ex) { log(site, "为项目【" + item["Title"] + "】的【" + field_name + "】授权时发生错误", "错误", ex.ToString()); } }
private SPFieldUserValueCollection GetUserValues(SPWeb web) { SPFieldUserValueCollection values = new SPFieldUserValueCollection(); foreach (PickerEntity entity in spPeoplePicker.ResolvedEntities) { SPUser user = web.EnsureUser(entity.Key); SPFieldUserValue fuv = new SPFieldUserValue(web, user.ID, user.LoginName); values.Add(fuv); } return(values); }
/// <summary> /// Adds the invitations to public and private calendars. /// </summary> private void AddInvitationsToCalendars() { string title = string.Format(Values.CalendarMailHeader, workflowProperties.Item[SPBuiltInFieldNames.Title]); SPFieldUserValue employee = new SPFieldUserValue(workflowProperties.Web, workflowProperties.Item[SPBuiltInFieldNames.CreatedBy].ToString()); string organizer = employee.User.Name; string organizerAddress = employee.User.Email; string privateCalendar = employee.User.Email; string publicCalendar = Values.PublicCalendarMailAddress; DateTime? start = workflowProperties.Item[HolidaysFields.StartDate.Name] as DateTime?; DateTime? end = workflowProperties.Item[HolidaysFields.EndDate.Name] as DateTime?; CalendarHelper.SendCalendarInvitation(workflowProperties.Web, organizer, organizerAddress, publicCalendar, start, end, title); CalendarHelper.SendCalendarInvitation(workflowProperties.Web, organizer, organizerAddress, privateCalendar, start, end, title); }
private void btnImport_Click(object sender, EventArgs e) { if (txtSourceListName.Text == "" || txtDesListName.Text == "") { MessageBox.Show("导入导出的列表名称不能为空"); return; } if (txtSourceCol.Text == "" || txtDesCol.Text == "") { MessageBox.Show("导入导出的列表列不能为空"); return; } string txtNames = txtSourceCol.Text.Trim().Replace(";", ";"); txtNames = txtNames.Replace(" ", "").TrimEnd(';'); string[] srcCols = txtNames.Split(';'); txtNames = txtDesCol.Text.Trim().Replace(";", ";"); txtNames = txtNames.Replace(" ", "").TrimEnd(';'); string[] desCols = txtNames.Split(';'); if (srcCols.Length != desCols.Length) { MessageBox.Show("导入导出的列表列个数不同"); return; } using (SPSite mySite = new SPSite("http://localhost")) { SPWeb myWeb = mySite.AllWebs[txtWebSourceUrl.Text]; SPList mySourceList = myWeb.Lists[txtSourceListName.Text]; SPWeb desWeb = mySite.AllWebs[txtWebDesUrl.Text]; SPList myDesList = desWeb.Lists[txtDesListName.Text];//查阅项 //DirectoryEntry de= AdHelper.GetDirectoryEntryByAccount("xueqingxia"); SPUser user = myWeb.EnsureUser("ccc\\xueqingxia"); SPFieldUserValue fUser = new SPFieldUserValue(myWeb, user.ID, user.LoginName); foreach (SPListItem myItem in mySourceList.Items) { SPListItem newItem = myDesList.AddItem(); for (int i = 0; i < srcCols.Length; i++) { newItem[srcCols[i]] = myItem.ID + ";#" + myItem[desCols[i]]; newItem["评审人"] = fUser; } newItem.Update(); } MessageBox.Show("ok"); } }
/// <summary> /// Converts the specified value. /// </summary> /// <param name="value">The value.</param> /// <param name="arguments">The arguments.</param> /// <returns> /// The converted value. /// </returns> public override object Convert(object value, DataRowConversionArguments arguments) { if (value == DBNull.Value) { return null; } UserValue userValue = null; var sharepointUserValue = new SPFieldUserValue(arguments.Web, value as string); var principal = sharepointUserValue.User; userValue = principal != null ? new UserValue(principal) : null; return userValue; }
public string GetFieldValueUserLogin(SPListItem item, string fieldName) { if (item != null) { SPFieldUserValue userValue = new SPFieldUserValue(item.Web, item[fieldName] as string); return userValue.User.LoginName; } else { return string.Empty; } }
private void createTask1_MethodInvoking(object sender, EventArgs e) { TaskId = Guid.NewGuid(); SPFieldUserValue approverUserValue = new SPFieldUserValue(workflowProperties.Web, workflowProperties.Item[SPBuiltInFieldId.AssignedTo].AsString()); taskProperties.Title = string.Format("Please review {0}'s approval application", workflowProperties.OriginatorUser.Name); taskProperties.AssignedTo = approverUserValue.User.LoginName; taskProperties.PercentComplete = 0; taskProperties.StartDate = DateTime.Today; workflowProperties.Item[SPBuiltInFieldId.Outcome] = SPUtility.GetLocalizedString("$Resources:Tasks_InProgress;", "core", workflowProperties.Web.Language); workflowProperties.Item.Update(); }
private void Manage_CMD_Zatwierdz_WyslijInfo_Zadanie(SPListItem item) { string cmd = GetCommand(item); string notatka = item["colInformacjaDlaKlienta"] != null ? item["colInformacjaDlaKlienta"].ToString() : string.Empty; int klientId = item["selKlient"] != null ? new SPFieldLookupValue(item["selKlient"].ToString()).LookupId : 0; if (klientId > 0 && cmd == WYSLIJ_INFORMACJE_I_ZAKONCZ_ZADANIE && !string.IsNullOrEmpty(notatka)) { string nadawca = new SPFieldUserValue(item.Web, item["Editor"].ToString()).User.Email; string odbiorca = BLL.tabKlienci.Get_EmailById(item.Web, klientId); string kopiaDla = Get_KopiaDlaOperatora(item); bool KopiaDoNadawcy = true; bool KopiaDoBiura = false; string temat = string.Empty; string tresc = string.Empty; string trescHTML = string.Empty; BLL.dicSzablonyKomunikacji.Get_TemplateByKod(item, "EMAIL_DEFAULT_BODY.Include", out temat, out trescHTML, nadawca); if (item["selProcedura"] != null) { temat = string.Format("{0} :{1}", new SPFieldLookupValue(item["selProcedura"].ToString()).LookupValue, item.Title); } else { temat = item.Title; } if (!temat.StartsWith(":")) { temat = ": " + temat.Trim(); } temat = AddSygnatura(temat, item); temat = BLL.Tools.AddCompanyName(temat, item); StringBuilder sb = new StringBuilder(trescHTML); sb.Replace("___BODY___", notatka); trescHTML = sb.ToString(); DateTime planowanaDataNadania = item["colTerminWyslaniaInformacji"] != null ? DateTime.Parse(item["colTerminWyslaniaInformacji"].ToString()) : new DateTime(); BLL.tabWiadomosci.AddNew(item.Web, item, nadawca, odbiorca, kopiaDla, KopiaDoNadawcy, KopiaDoBiura, temat, tresc, trescHTML, planowanaDataNadania, item.ID, klientId, Marker.Ignore); Set_StatusZadania(item, StatusZadania.Wysyłka); } }
/// <summary> /// Function to get user by login account /// </summary> /// <param name="currentURL"></param> /// <param name="userid"></param> /// <returns></returns> public SPFieldUserValue ConvertLoginAccount(string currentURL, string userid) { SPFieldUserValue uservalue; using (SPSite site = new SPSite(currentURL)) { using (SPWeb web = site.OpenWeb()) { SPUser requireduser = web.EnsureUser(userid); uservalue = new SPFieldUserValue(web, requireduser.ID, requireduser.LoginName); } } return(uservalue); }
/// <summary> /// Synchronous Before event that occurs when an existing item is changed, for example, when the user changes data in one or more fields. /// </summary> /// <param name="properties">An <see cref="T:Microsoft.SharePoint.SPItemEventProperties"/> object that represents properties of the event handler.</param> public override void ItemUpdating(SPItemEventProperties properties) { base.ItemUpdating(properties); var currentUser = properties.Web.CurrentUser; SPFieldUserValue authorisor = new SPFieldUserValue(properties.Web, properties.ListItem[SPBuiltInFieldId.AssignedTo].ToString()); bool isCurrentUserAuthorisor = currentUser.LoginName == authorisor.User.LoginName; if (!isCurrentUserAuthorisor) { var afterProperties = properties.AfterProperties[HolidaysFields.Decision.Name]; properties.AfterProperties[HolidaysFields.Decision.Name] = null; afterProperties = properties.AfterProperties[HolidaysFields.Decision.Name]; } }
//切换各个用户 void rblAuthors_SelectedIndexChanged(object sender, EventArgs e) { string item = rblAuthors.SelectedValue;//userID+listID+ratio string[] ids = Regex.Split(item, ";"); ViewState["id"] = ids[1]; //业绩ID ViewState["beforeRatio"] = double.Parse(ids[2]); //业绩修改前的值 SPWeb web = SPContext.Current.Web; SPFieldUserValue user = new SPFieldUserValue(web, int.Parse(ids[0]), rblAuthors.SelectedItem.Text); tbName.CommaSeparatedAccounts = user.User.LoginName; tbRatio.Text = ids[2]; btnSave.Enabled = true; lblMsg.Text = ""; }
/// <summary> /// An item was added. /// </summary> public override void ItemAdded(SPItemEventProperties properties) { Microsoft.Office.Server.Diagnostics.PortalLog.LogString("KeyPeople EventReceiver: Starting ItemAdded on keyPeople for list on {0}", properties.Web.Url); SPSecurity.RunWithElevatedPrivileges(delegate() { if (properties.ListItem["KeyPerson"] != null) { SPFieldUserValue keyPersonValue = new SPFieldUserValue(properties.Web.Site.RootWeb, properties.ListItem["KeyPerson"].ToString()); GiveUserPrivelegesToWorkspace(keyPersonValue.User, properties); } }); base.ItemAdded(properties); Microsoft.Office.Server.Diagnostics.PortalLog.LogString("KeyPeople EventReceiver: Completing ItemAdded on keyPeople for list on {0}", properties.Web.Url); }
private static void AssignRights(SPWeb web, SPFieldUserValue user, SPRoleDefinition roleDefinition, SPFolder folder) { SPPrincipal byId; if (user.User != null) { byId = user.User; } else { byId = web.SiteGroups.GetByID(user.LookupId); } AssignRights(web, byId, roleDefinition, folder); }
/// <summary> /// Returns the login name of an User-Field. /// </summary> public static string GetFieldValueUserLogin(this SPListItem item, string fieldName) { if (item != null) { SPFieldUserValue userValue = new SPFieldUserValue( item.Web, item[fieldName] as string); return(userValue.User.LoginName); } else { return(string.Empty); } }
private List <Aniversariante_VO> getAniversariantes(int mes) { List <Aniversariante_VO> lstAniversariantes = new List <Aniversariante_VO>(); //Todos os usuários using (SPWeb web = SPContext.Current.Site.RootWeb) { foreach (SPListItem usuario in usuarios.Items) { try { // try to get user-name SPUser spUser = new SPFieldUserValue(web, Convert.ToInt32(usuario.ID), null).User; if (spUser == null) { continue; } // web.Users.GetByID(usuario.ID); } catch (Exception) { continue; } if (usuario[COLUNA_NASCIMENTO] != null) { try { DateTime dataAniversario = DateTime.Parse(usuario[COLUNA_NASCIMENTO].ToString()); if (dataAniversario.Month == mes) { Aniversariante_VO aniv = new Aniversariante_VO(); aniv.DataAniversario = dataAniversario; aniv.IdAniversariante = int.Parse(usuario["ID"].ToString()); aniv.NomeResumido = usuario["Nome Resumido"].ToString(); lstAniversariantes.Add(aniv); } } catch (Exception) { throw new Exception("Erro fazendo parse na data de nascimento do usuário " + usuario["Nome"].ToString()); } } } //fim do foreach usuário } //fim do using return(lstAniversariantes); }
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)); }
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 SPFieldUserValueCollection UserValueCollection(SPWeb web, string users) { SPFieldUserValueCollection usercollection = new SPFieldUserValueCollection(); string[] userarray = users.Split(';'); string email = string.Empty; string name = string.Empty; string cpnameori = string.Empty; for (int j = 0; j < userarray.Length - 1; j++) { SPFieldUserValue usertoadd = ConvertLoginName(userarray[j], web); usercollection.Add(usertoadd); } return(usercollection); }
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); }
private DataTable GetSpUsers(DataView dv, SPWeb web) { DataTable spUsers = new DataTable("SPUsers"); spUsers.Columns.Add("Name"); spUsers.Columns.Add("LoginName"); spUsers.Columns.Add("Email"); foreach (DataRowView rowView in dv) { SPFieldUserValue fuv = new SPFieldUserValue(web, rowView["SharePointAccount"].ToString()); spUsers.Rows.Add((fuv.User == null) ? new object[] { rowView["Title"].ToString(), "", "" } : new object[] { fuv.User.Name, fuv.User.LoginName, fuv.User.Email }); } return(spUsers); }
/// <summary> /// Метод возвращает необходимые состояния кнопок для карточки КМ /// </summary> /// <param name="Item">Текущий Item</param> /// <param name="State">Текущий статус карточки</param> /// <returns></returns> private static AccessData GetCMAccessData(SPWeb Web, SPGroup Group, SPListItem Item, CardState State, List<string> Companies) { AccessData result = new AccessData(); bool IsExpert = Group.Name == GlobalConstants.Groups.Expert; bool InCompany = Companies.Any(Company => Item[GlobalConstants.ControlMeasure_Fields.CompanyName].ToString().Contains(Company)); bool Approver = new SPFieldUserValue(Web, Item[GlobalConstants.ControlMeasure_Fields.Approver].ToString()).User.ID == Web.CurrentUser.ID; bool Responsible = new SPFieldUserValue(Web, Item[GlobalConstants.ControlMeasure_Fields.Responsible].ToString()).User.ID == Web.CurrentUser.ID; bool InMailingList = new SPFieldUserValueCollection(Web, Item[GlobalConstants.ControlMeasure_Fields.MailingList].ToString()).Any(User => User.User.ID == Web.CurrentUser.ID); bool AuditorOrAdministrator = Group.Name == GlobalConstants.Groups.Administrator || Group.Name == GlobalConstants.Groups.Auditor; result.Edit.Enabled = ((InCompany || Approver || Responsible || InMailingList) && IsExpert) || (InMailingList && AuditorOrAdministrator); result.Edit.Visible = State; result.Bind.Enabled = ((InCompany || Approver || Responsible || InMailingList) && IsExpert) || (InMailingList && AuditorOrAdministrator); result.Bind.Visible = State; result.CreateNewRequestCM.Enabled = ((InCompany || Approver || Responsible || InMailingList) && IsExpert) && (!AuditorOrAdministrator); result.CreateNewRequestCM.Visible = State; result.ExcelExport.Enabled = ((InCompany || Approver || Responsible || InMailingList) && IsExpert)&& (!AuditorOrAdministrator); result.ExcelExport.Visible = State; result.ToAffirmation.Enabled = ((InCompany || Responsible || InMailingList) && IsExpert) && (!AuditorOrAdministrator); result.ToAffirmation.Visible = State; result.ToWork.Enabled = (Approver && IsExpert) && (!AuditorOrAdministrator); result.ToWork.Visible = State; result.ToRework.Enabled = (Approver && IsExpert) && (!AuditorOrAdministrator); result.ToRework.Visible = State; result.Close.Enabled = ((InCompany || Approver || Responsible || InMailingList) && IsExpert) || (InMailingList && AuditorOrAdministrator); result.Close.Visible = State; // //Нужно доделать доступность кнопок в зависимости от дополнительных параметров, как-то : указана ли компания, какой текущий статус карточки и тд тп // // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! return result; }
/// <summary> /// An item was added. /// </summary> public override void ItemAdded(SPItemEventProperties properties) { base.ItemAdded(properties); try { base.ItemAdded(properties); SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(properties.SiteId)) { using (SPWeb web = site.OpenWeb(properties.Web.ID)) { string itemID = Convert.ToString(properties.ListItemId); bool isBOD = false; var approverString = Convert.ToString(properties.ListItem[StringConstant.NotOvertimeList.DHField]); if (!string.IsNullOrEmpty(approverString)) { SPListItem curItem = properties.ListItem; var bodGroup = web.SiteGroups.GetByName("BOD"); var spUserField = properties.ListItem.Fields.GetField(StringConstant.NotOvertimeList.DHField); SPFieldUserValue spNewUserFieldValue = (SPFieldUserValue)spUserField.GetFieldValue(approverString); SPUser spNewBodUser = web.EnsureUser(spNewUserFieldValue.LookupValue); var bodUser = bodGroup.Users.GetByLoginNoThrow(spNewBodUser.LoginName); if (bodUser != null) { isBOD = true; } } var notOverTimeRequestEmail = string.Format("{0}/_vti_bin/Services/Email/EmailService.svc/SendNotOverTimeRequestEmail/{1}/{2}", properties.WebUrl, itemID, isBOD ? "BOD" : "DH"); var delegationNotOverTimeRequestEmail = string.Format("{0}/_vti_bin/Services/Email/EmailService.svc/SendDelegationNotOverTimeRequestEmail/{1}/{2}", properties.WebUrl, itemID, isBOD ? "BOD" : "DH"); SendEmail(notOverTimeRequestEmail); SendEmail(delegationNotOverTimeRequestEmail); } } }); } catch (Exception ex) { ULSLogging.Log(new SPDiagnosticsCategory("STADA - NotOvertime Event Receiver - ItemAdded fn", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, string.Format(CultureInfo.InvariantCulture, "{0}:{1}", ex.Message, ex.StackTrace)); } }
public object FromSpValue(object value) { if (value == null) return null; if (!Field.AllowMultipleValues) { var fieldValue = new SPFieldUserValue(Field.ParentList.ParentWeb, value.ToString()); return new UserInfo(fieldValue.User); } var fieldValues = new SPFieldUserValueCollection(Field.ParentList.ParentWeb, value.ToString()); var users = fieldValues.Select(fieldValue => fieldValue.User).Select(user => new UserInfo(user)); return PropertyType == typeof (UserInfo[]) ? (object) users.ToArray() : users.ToList(); }
//Sobreescreve a função do TimerJob que será executada public override void Execute(Guid targetInstanceId) { //Data atual DateTime horario = DateTime.Now; //Verifica se a hora atual é igual ás 7 da manhã if (horario.Hour == 7) { //WebApplication referente ao timer Job SPWebApplication webApp = this.Parent as SPWebApplication; SPSite site = webApp.Sites[0].RootWeb.Site; //Site Atendimento que contém a lista de solicitações using (SPWeb webAtendimento = site.OpenWeb("Atendimento")) { //Lista de Solicitações SPList listaSolicitacoes = webAtendimento.Lists["Solicitações de Serviço"]; //Query verifica se a Solicitação está em atendimento e se a data da solicitação é menor que a data atual SPQuery queryAtendimento = new SPQuery(); queryAtendimento.Query = string.Format("<Where><And><Eq><FieldRef Name='Status' /><Value Type='Choice'>Em Atendimento</Value></Eq>" + "<Lt><FieldRef Name='PrazoFimAtendimento' /><Value IncludeTimeValue='FALSE' Type='DateTime'>" + Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy-MM-ddThh:mm:ssZ") + "</Value></Lt>" + "</And></Where>"); //Coleção de itens que realizados com a consulta SPListItemCollection colecaoSolicitacoesAtrasadas = listaSolicitacoes.GetItems(queryAtendimento); foreach (SPListItem itemSolicitacao in colecaoSolicitacoesAtrasadas) { //Verifica se a solicitação possui Responsável if (itemSolicitacao["ResponsavelSolicitacao"] != null) { SPFieldUserValue responsavelEmail = new SPFieldUserValue(webAtendimento, itemSolicitacao["ResponsavelSolicitacao"].ToString()); if (itemSolicitacao["PrazoFimAtendimento"] != null) { DateTime dataPrazoAtendimento = DateTime.Parse(itemSolicitacao["PrazoFimAtendimento"].ToString()); ControllerEmail.emailMensagem(responsavelEmail.User.Email, webAtendimento, itemSolicitacao); } } } } } }
/// <summary> /// Converts the specified value. /// </summary> /// <param name="value">The value.</param> /// <param name="arguments">The arguments.</param> /// <returns> /// The converted value. /// </returns> public override object Convert(object value, SharePointListItemConversionArguments arguments) { UserValue userValue = null; try { var sharepointUserValue = new SPFieldUserValue(arguments.ListItem.Web, value as string); var principal = sharepointUserValue.User; userValue = principal != null ? new UserValue(principal) : null; } catch (ArgumentException) { // failed to read SPUser value, will return null } return userValue; }
public SurveyResponseSummary(SPListItem lsi, string pstrTemplateList) { ID = lsi.UniqueId; Name = lsi.Title; Template = ""; // FTKHandler.GetTemplate(pstrTemplateList, new Guid(lsi["TemplateID"].ToString())).Title; SPFieldUserValue userValue = new SPFieldUserValue(lsi.Web, lsi[SPBuiltInFieldId.Author].ToString()); SPUser user = userValue.User; string email = user.Email; User = user.Name; DateCreated = (DateTime)lsi[SPBuiltInFieldId.Created]; DateModified = (DateTime)lsi[SPBuiltInFieldId.Modified]; DisplayDate = DateModified.ToString("dd/MM/yyyy"); PopulateScoreDisplay(Int32.Parse(lsi["Score"].ToString())); }
/// <summary> /// 新建和保存时进行判断, /// 保存时,业绩点之和不能大于1;新建时,如果业绩点之点等于1,则不能创建新的业绩点 /// </summary> /// <param name="results"></param> /// <param name="btnEvent">Save/New</param> /// <returns></returns> private bool CheckRatio(ref List <string> results, string btnEvent = "Save") { lblMsg.Text = ""; decimal tRatio = 0; SPWeb web = SPContext.Current.Web; List <int> authors = new List <int>(); List <string> result = new List <string>(); for (int i = 0; i < gvGoalSetting.Rows.Count; i++) { TextBox tbRatio = (TextBox)gvGoalSetting.Rows[i].Cells[1].FindControl("tbRatio1");//获取 模板列的值 if (tbRatio.Text != "") { tRatio += decimal.Parse(tbRatio.Text); } PeopleEditor tbName1 = (PeopleEditor)gvGoalSetting.Rows[i].Cells[0].FindControl("tbName1");//获取 模板列的值 if (tbName1.ResolvedEntities.Count > 0) { SPFieldUserValue user = GetUserValue(web, (PickerEntity)tbName1.ResolvedEntities[0]); if (authors.Contains(user.User.ID)) { lblMsg.Text = webObj.ShowMsgAuthor; return(false); } else { authors.Add(user.LookupId); } result.Add(gvGoalSetting.DataKeys[i].Value.ToString() + ";" + user.User.ID + ";" + (tbRatio.Text == "" ? "0" : tbRatio.Text)); } } tRatio = decimal.Round(tRatio, 2); ViewState["TotalRatio"] = tRatio;//所有已经输入的业绩 if (btnEvent == "Save" && tRatio > TotalRatio || btnEvent == "New" && tRatio == TotalRatio) { lblMsg.Text = webObj.ShowMsg.Replace("N", (TotalRatio - tRatio).ToString()); return(false); } results = result; return(true); }
private void GetItems() { SPFieldUserValue currentUser = new SPFieldUserValue(this.Web, this.Web.CurrentUser.ID, this.Web.CurrentUser.Name); ArrayList resultsList = new ArrayList(); SPFarm thisFarm = SPFarm.Local; SPWebService service = thisFarm.Services.GetValue <SPWebService>(""); foreach (SPWebApplication webApp in service.WebApplications) { foreach (SPSite siteCollection in webApp.Sites) { foreach (SPWeb web in siteCollection.AllWebs) { SPListCollection lists = web.Lists; foreach (SPList list in lists) { try { resultsList.Add(list.Title); #region I removed this because it's a very large query //foreach (SPListItem item in list.Items) //{ // if (item[DropDownList1.SelectedValue].ToString() == currentUser.ToString()) // { // resultsList.Add(item); // } //} #endregion } catch (Exception) { // An error with the list. Move onto the next list. } } } } } Label1.Text = "You have " + resultsList.Count + " Lists in this Farm"; //CreateResultsTable(resultsList); }
public static SPFieldUserValue GetSelectedUser(PeopleEditor pEditor) { SPFieldUserValue user = new SPFieldUserValue(); try { string[] userarray = pEditor.CommaSeparatedAccounts.ToString().Split(','); if (userarray.Length > 0 && Convert.ToString(userarray[0]).Length > 0) { return(Convert2Account(userarray[0])); } } catch (Exception ex) { LogMessage(ex, "BusinessLayer.GetSelectedUser"); } 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); }
private void SetItemPermission(SPWeb web, Guid listId, int itemId) { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(web.Site.ID)) { using (SPWeb spWeb = site.OpenWeb(web.ID)) { SPList list = spWeb.Lists[listId]; SPListItem listItem = list.GetItemById(itemId); listItem.RemoveAllPermissions(); SPFieldUserValue userValue = new SPFieldUserValue(spWeb, listItem[SPBuiltInFieldId.Author].ToString()); listItem.SetPermissions(userValue.User, SPRoleType.Contributor); listItem.SetPermissions(spWeb.EnsureUser(Constants.AUTHENTICATED_USERS), SPRoleType.Reader); } } }); }
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); }
public static void SendProcessEndConfirmationMail(string subject, string bodyHtml, SPWeb web, SPItem item) { string from = "*****@*****.**"; string fromName = "STAFix24 Robot"; string to = new SPFieldUserValue(web, item["Author"].ToString()).User.Email; string bodyText = string.Empty; WebClient client = new WebClient(); NameValueCollection values = new NameValueCollection(); values.Add("username", USERNAME); values.Add("api_key", API_KEY); values.Add("from", from); values.Add("from_name", fromName); values.Add("subject", subject); if (bodyHtml != null) values.Add("body_html", bodyHtml); if (bodyText != null) values.Add("body_text", bodyText); values.Add("to", to); byte[] response = client.UploadValues("https://api.elasticemail.com/mailer/send", values); }
/// <summary> /// Converts the specified value. /// </summary> /// <param name="value">The value.</param> /// <param name="arguments">The arguments.</param> /// <returns> /// The converted value. /// </returns> public override object Convert(object value, DataRowConversionArguments arguments) { if (value == DBNull.Value) { return null; } UserValue userValue = null; try { // TODO: this most definitely doesn't work at all. // Once in datarow value, the SPFieldUserValue ctor can't parse the value correctly var sharepointUserValue = new SPFieldUserValue(arguments.Web, value as string); var principal = sharepointUserValue.User; userValue = principal != null ? new UserValue(principal) : null; } catch (ArgumentException) { // failed to read SPUser value, will return null } return userValue; }
public static SPUser GetSPUser(SPListItem listItem, string key) { object obj = null; try { obj = listItem[key]; } catch (Exception) { var index = -1; switch (key) { case "Author": index = GetFieldIndex(listItem, key); obj = listItem[index]; //Ошибка шарепоинта - иногда не ищет поле Author break; case "Editor": index = GetFieldIndex(listItem, key); obj = listItem[index]; //Ошибка шарепоинта - иногда не ищет поле Editor break; } } if (obj == null) return null; try { var value = new SPFieldUserValue(listItem.Web, obj.ToString()); return value.User; } catch (Exception) { return null; } }
/// <summary> /// This method handle create task event /// </summary> /// <param name="sender">object</param> /// <param name="e">EventArgs</param> private void logTaskCreated(object sender, EventArgs e) { //Add Task Refs in the root site. using (DocumentApprovalTasks tasks = new DocumentApprovalTasks()) { using (SPWeb ObjRootWeb = SPHelper.GetRootWeb(SPHelper.GetRootUrl(workflowProperties.SiteUrl))) { //Getting Created By - Login Name SPFieldUserValue val = new SPFieldUserValue(workflowProperties.Item.Web, workflowProperties.Item["Created By"] as string); SPUser usr = val.User; string _documentAuthor = usr.LoginName; string initiationData = workflowProperties.InitiationData; // Getting Publishbale Location ID var Publish_Location_ID = from _value in XElement.Load(new StringReader(EscapeXml(initiationData))).Elements("Publish_Location_ID") select _value; string _locationID = string.Empty; foreach (var ID in Publish_Location_ID) { _locationID = ID.Value; } // Getting Publishbale Location Name var Publish_Location_Name = from _value in XElement.Load(new StringReader(EscapeXml(initiationData))).Elements("Publish_Location_Name") select _value; string _locationName = string.Empty; foreach (var Name in Publish_Location_Name) { _locationName = Name.Value; } SPFieldLookupValue _publishableLocation = new SPFieldLookupValue(Convert.ToInt32(_locationID), _locationName); ; //_publishableLocation=new SPFieldLookupValue(location //Getting Approver - Login Name string _taskUrl = workflowProperties.Item.Web.Url + "/Lists/DocumentApprovalTasks/DispForm.aspx?ID=" + CreateAppovalTask.ListItemId.ToString(); //Add Task Ref in the root site _documentApprovalTaskId = tasks.AddTask(CreateAppovalTask.TaskProperties.Title, CreateAppovalTask.TaskProperties.DueDate, CreateAppovalTask.TaskProperties.AssignedTo, _documentAuthor, _taskUrl, ObjRootWeb, _publishableLocation); //int _groupID = Convert.ToInt32(CreateAppovalTask.TaskProperties.AssignedTo.ToString().Split(';')[0]); SPGroup _approverGroup = ObjRootWeb.Groups[CreateAppovalTask.TaskProperties.AssignedTo]; //Send Email notification to the approver SendApproverEmail(_approverGroup, "CLIF"); } } LogToHistoryListActivity log = (LogToHistoryListActivity)sender; if (log != null) { log.HistoryDescription = "Document approval task created."; } }
/// <summary> /// Gets User of People Picker field (Single choice) /// </summary> /// <param name="item">Current item</param> /// <param name="fieldName">Field Name</param> /// <returns>Return SPUser</returns> public static SPUser GetUserByField(SPListItem item, string fieldName) { var value = Convert.ToString(item[fieldName], CultureInfo.InvariantCulture); if (string.IsNullOrEmpty(value)) return null; var userFieldValue = new SPFieldUserValue(item.Web, value); if (userFieldValue.User != null) return userFieldValue.User; return null; }
/** * 将一组用户帐号添加到字段中,如果字段中已包含该帐号则不用重复添加 * 添加字段为People Group类型,返回类型同样为People Group类型 */ protected SPFieldUserValueCollection ReturnAllApproversSP(string approverCol, params string[] accounts) { var web = SPContext.Current.Web; SPUser user = null; SPFieldUserValue spUser = null; SPFieldUserValueCollection approvers = WorkflowContext.Current.DataFields[approverCol] as SPFieldUserValueCollection; foreach (var account in accounts) { user = web.AllUsers[account]; spUser = new SPFieldUserValue(web, user.ID, user.Name); if (approvers == null) { approvers = new SPFieldUserValueCollection(); } if (!approvers.Contains(spUser)) { approvers.Add(spUser); } } return approvers; }