public static SPFieldLookupValueCollection GetLookFieldIDS(string lookupValues, SPList lookupSourceList) { SPFieldLookupValueCollection lookupIds = new SPFieldLookupValueCollection(); string[] lookups = lookupValues.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string lookupValue in lookups) { SPQuery query = new Microsoft.SharePoint.SPQuery(); query.Query = String.Format("<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>{0}</Value></Eq></Where>", lookupValue); SPListItemCollection listItems = lookupSourceList.GetItems(query); foreach (Microsoft.SharePoint.SPListItem item in listItems) { SPFieldLookupValue value = new SPFieldLookupValue(item.ID.ToString()); lookupIds.Add(value); break; } } return lookupIds; }
protected override void OnInit(EventArgs e) { CustomDropDownList field = base.Field as CustomDropDownList; if (field.AllowMultipleValues) { if (ControlMode == SPControlMode.Edit || ControlMode == SPControlMode.Display) { if (base.ListItemFieldValue != null) { _fieldVals = base.ListItemFieldValue as SPFieldLookupValueCollection; } else { _fieldVals = new SPFieldLookupValueCollection(); } } if (ControlMode == SPControlMode.New) { _fieldVals = new SPFieldLookupValueCollection(); } base.OnInit(e); Initialize_multi_value((CustomDropDownList)this.Field); } else { if (ControlMode == SPControlMode.Edit || ControlMode == SPControlMode.Display) { if (base.ListItemFieldValue != null) { _fieldVal = base.ListItemFieldValue as SPFieldLookupValue; } else { _fieldVal = new SPFieldLookupValue(); } } if (ControlMode == SPControlMode.New) { _fieldVal = new SPFieldLookupValue(); } base.OnInit(e); Initialize((CustomDropDownList)base.Field); } }
private int GetTaskIDByAction(int actionID, DateTime currDate) { SPListItemCollection items = GetAllActions; SPListItem item = items.GetItemById(actionID); string typeName = ""; if (item["TypeID"] != null) { SPFieldLookupValueCollection types = (SPFieldLookupValueCollection)item["TypeID"]; foreach (SPFieldLookupValue type in types) { if (type.LookupValue != "项目") { if (type.LookupValue != "工作" && type.LookupValue != "学习") { typeName = "生活类"; } else { typeName = type.LookupValue; } } } } if (typeName == "") { typeName = "生活类"; } string taskCurr = GetRoutineDocName(txtName.Text, typeName, currDate); int taskID = GetTaskID(taskCurr); return(taskID); }
private void InsertLookupValueByQueryString() { if (mode == SPControlMode.New || (this.list.BaseTemplate == SPListTemplateType.DocumentLibrary && !string.IsNullOrEmpty(Page.Request[ModeParam]) && Page.Request[ModeParam] == Upload && mode == SPControlMode.Edit)) { // assume single lookup bool valIsMulti = false; List <int> ids = new List <int>(); if (!string.IsNullOrEmpty(this.lookupValue)) { valIsMulti = (this.lookupValue.IndexOf(',') != -1); if (valIsMulti) { string[] sIds = this.lookupValue.Split(','); foreach (string s in sIds) { if (!string.IsNullOrEmpty(s.Trim())) { ids.Add(int.Parse(s)); } } } } List <FormField> formFields = this.GetFormFieldByType(typeof(SPFieldLookup)); List <FormField> modCandidates = new List <FormField>(); foreach (FormField fld in formFields) { if (!string.IsNullOrEmpty(lookupField) && fld.Field.InternalName.Equals(lookupField)) { modCandidates.Add(fld); } } for (int index = 0; index < modCandidates.Count; index++) { SPField spFld = modCandidates[index].Field; SPFieldLookup lookupFld = modCandidates[index].Field as SPFieldLookup; bool isMulti = lookupFld.AllowMultipleValues; // insert single value to single lookup field if (!isMulti && !valIsMulti) { int itemID = int.Parse(lookupValue.Trim()); SPFieldLookupValue lookupVal = new SPFieldLookupValue(itemID, GetLookupItemValue(lookupFld, itemID)); this.ListItem[spFld.Id] = lookupVal; } // insert multi lookup value to multi lookup field else if (isMulti && valIsMulti) { SPFieldLookupValueCollection lookupValCol = new SPFieldLookupValueCollection(); foreach (int itemID in ids) { SPFieldLookupValue lookupVal = new SPFieldLookupValue(itemID, GetLookupItemValue(lookupFld, itemID)); lookupValCol.Add(lookupVal); } this.ListItem[spFld.Id] = lookupValCol; } } } }
public override void UpdateFieldValueInItem() { var values = new SPFieldLookupValueCollection(); values.AddRange(SelectedItems.Select(item => new SPFieldLookupValue(item, string.Empty))); ItemFieldValue = values; }
public static SPFieldLookupValueCollection GetLookFieldIDS(ClientContext context, string lookupValues, List lookupSourceList) { SPFieldLookupValueCollection lookupIds = new SPFieldLookupValueCollection(); string[] lookups = lookupValues.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string lookupValue in lookups) { CamlQuery query = new CamlQuery(); query.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>{0}</Value></Eq></Where></Query></View>", lookupValue); ListItemCollection listItems = lookupSourceList.GetItems(query); context.Load(lookupSourceList); context.Load(listItems); context.ExecuteQuery(); foreach (ListItem item in listItems) { SPFieldLookupValue value = new SPFieldLookupValue(Convert.ToInt32(item["ID"]), item["Title"].ToString()); lookupIds.Add(value); break; } } return(lookupIds); }
public override string GetValidatedString(object value) { if (this.Required) { string _s = string.Format(CultureInfo.InvariantCulture, "{0} is required.", this.Title); if (value == null) { throw new SPFieldValidationException(_s); } else { if (this.AllowMultipleValues) { SPFieldLookupValueCollection c = value as SPFieldLookupValueCollection; if (c.Count < 0) { throw new SPFieldValidationException(_s); } } else { SPFieldLookupValue v = value as SPFieldLookupValue; if (v.LookupId < 1 && (string.IsNullOrEmpty(v.LookupValue) || v.LookupValue == "(None)")) { throw new SPFieldValidationException(_s); } } } } return(base.GetValidatedString(value)); }
public static void Create(SPWeb web, int klientId, int okresId, bool createKK) { Debug.WriteLine("Create RBR Form"); SPListItem item = tabKlienci.Get_KlientById(web, klientId); SPFieldLookupValueCollection kody; switch (item.ContentType.Name) { case "Osoba fizyczna": case "Firma": kody = new SPFieldLookupValueCollection(item["selSerwisyWspolnicy"].ToString()); break; default: kody = new SPFieldLookupValueCollection(item["selSewisy"].ToString()); break; } foreach (SPFieldLookupValue kod in kody) { switch (kod.LookupValue) { case @"RBR": if (createKK) BLL.tabKartyKontrolne.Create_KartaKontrolna(web, item.ID, okresId); Create_BR_Form(web, item.ID, okresId); break; default: break; } } }
public override string GetValidatedString(object value) { if (this.Required) { string _s = string.Format(CultureInfo.InvariantCulture, "Você deve especificar um valor para este campo obrigatório.", this.Title); if (value == null) { throw new SPFieldValidationException(_s); } else { if (this.AllowMultipleValues) { SPFieldLookupValueCollection c = value as SPFieldLookupValueCollection; if (c.Count < 0) { throw new SPFieldValidationException(_s); } } else { SPFieldLookupValue v = value as SPFieldLookupValue; if (v.LookupId < 1 && (string.IsNullOrEmpty(v.LookupValue) || v.LookupValue == "(Nenhum)")) { throw new SPFieldValidationException(_s); } } } } return(base.GetValidatedString(value)); }
public static void CreateNew(SPWeb web, SPListItem item, int okresId) { Debug.WriteLine("Create PD Form"); if (item != null) { SPFieldLookupValueCollection kody; kody = new SPFieldLookupValueCollection(item["selSewisy"].ToString()); foreach (SPFieldLookupValue kod in kody) { switch (kod.LookupValue) { case @"PD-M": Create_PD_M_Form(web, item.ID, okresId); break; case @"PD-KW": Create_PD_KW_Form(web, item.ID, okresId); break; default: break; } } } }
}//End jobTitles /******************************************************************************************************************************************/ public static SPListItem createCourses(SPWeb qmwWeb, SPWeb web, int count) { int maxTitles = random.Next(5, 11); SPList list = web.Lists["Training Matrix"]; var bus = GetLookupValues(qmwWeb, "Business Units", "Business_x0020_Unit", ""); var bu = bus.GetRandom(); String[] buString = (bu.ToString()).Split('#'); var depts = GetLookupValues(qmwWeb, "Departments", "Department_x0020_Name", buString[1]); var jobRoles = GetLookupValues(qmwWeb, "Job Roles", "Job_x0020_Role", ""); SPFieldLookupValueCollection jobRoleList = new SPFieldLookupValueCollection { }; for (int i = 0; i < maxTitles; i++) { jobRoleList.Add(jobRoles.GetRandom()); } var item = new Dictionary <string, object>() { { "Course ID", ("ID-" + (count + 1)) }, { "Course Name", String.Concat("Course-", nameGenerator()) }, { "Course Description", nameGenerator() }, { "Owning Business Unit", bu }, { "Owning Department", depts.GetRandom() }, { "Required Job Roles", jobRoleList }, { "Course Status", "Available" }, { "Course Type", "Read and acknowledge" }, { "Course Level", "Beginner" }, { "Autonomous Training", "Yes" }, }; addListItem(list, item); return(null); }//End courses
internal static bool HasServiceAssigned(SPWeb web, int klientId, string serwisKod) { bool result = false; SPList targetList = web.Lists.TryGetList(listName); //if (targetList != null) //{ SPListItem item = targetList.GetItemById(klientId); if (item != null) { SPFieldLookupValueCollection kody = new SPFieldLookupValueCollection(item["selSewisy"].ToString()); foreach (SPFieldLookupValue kod in kody) { if (kod.LookupValue == serwisKod) { result = true; break; } } kody = new SPFieldLookupValueCollection(item["selSerwisyWspolnicy"].ToString()); foreach (SPFieldLookupValue kod in kody) { if (kod.LookupValue == serwisKod) { result = true; break; } } } //} return(result); }
internal static void Create(SPWeb web, int klientId, int okresId) { SPListItem item = tabKlienci.Get_KlientById(web, klientId); if (item != null) { SPFieldLookupValueCollection kody; switch (item.ContentType.Name) { case "Osoba fizyczna": case "Firma": kody = new SPFieldLookupValueCollection(item["selSerwisyWspolnicy"].ToString()); break; default: kody = new SPFieldLookupValueCollection(item["selSewisy"].ToString()); break; } foreach (SPFieldLookupValue kod in kody) { switch (kod.LookupValue) { case @"PD-M": Create_PD_M_Form(web, item.ID, okresId); break; case @"PD-KW": Create_PD_KW_Form(web, item.ID, okresId); break; default: break; } } } }
/// <summary> /// An item was added. /// </summary> public override void ItemAdded(SPItemEventProperties properties) { base.ItemAdded(properties); using (SPSite site = new SPSite("http://devlab.billennium.pl/sites/serwis-prasowy")) { using (SPWeb web = site.OpenWeb()) { SPListItem oItem = properties.ListItem; SPList picturesLib = web.Lists["Pictures"]; SPFieldLookupValue fieldLookupValue = new SPFieldLookupValue(oItem["Image"].ToString()); int imgId = fieldLookupValue.LookupId; var img = picturesLib.Items.GetItemById(imgId); oItem["Picture"] = img["URL Path"]; oItem.Update(); SPFieldLookupValueCollection categories = new SPFieldLookupValueCollection(oItem["Category"].ToString()); string selectedCategories = ""; foreach (SPFieldLookupValue cat in categories) { selectedCategories += cat.LookupValue + ", "; } selectedCategories = selectedCategories.Remove(selectedCategories.Length - 2); string title = oItem["Title"].ToString(); string body = "Witaj BLABLA, <br><br>" + "W naszym serwisie właśnie pojawił się news z kategorii \"" + selectedCategories + "\", pod tytułem: " + "\"" + oItem["Title"] + "\".<br><br>Aby zapoznać się z treścią newsa przejdź do: http://devlab.billennium.pl/sites/serwis-prasowy/Lists/News/DispForm.aspx?ID=" + oItem.ID; SendMail(web, "*****@*****.**", "*****@*****.**", title, body); } } }
/// <summary> /// Wywołuje procedurę generowania kart kontrolnych PDS dla pojedyńczego klienta /// </summary> public static void CreateNew(SPWeb web, SPListItem item, int okresId, Array zadania) { if (item != null) { SPFieldLookupValueCollection kody; kody = new SPFieldLookupValueCollection(item["selSewisy"].ToString()); foreach (SPFieldLookupValue kod in kody) { switch (kod.LookupValue) { case @"PDS-M": Create_PDS_M_Form(web, item.ID, okresId, zadania); break; case @"PDS-KW": Create_PDS_KW_Form(web, item.ID, okresId, zadania); break; default: break; } } } }
protected override IList <Term> GetTaxonomyMultiInternal(string fieldName, TermStore termStore) { if (this.ListItemAdapater != null) { return(this.ListItemAdapater.GetTaxonomyMulti(fieldName, termStore)); } Collection <Term> collection = new Collection <Term>(); object value = this[fieldName]; if (value != null) { try { SPFieldLookupValueCollection values = new SPFieldLookupValueCollection(value.ToString()); foreach (SPFieldLookupValue u in values) { Term term = termStore.GetTermByWssId(this.Site, u.LookupId); if (term != null) { collection.Add(term); } } } catch { } } return(collection); }
public static void Remove_Services(ref SPListItem item, string col, string mask) { SPFieldLookupValueCollection newOptions = new SPFieldLookupValueCollection(); SPFieldLookupValueCollection options = new SPFieldLookupValueCollection(item[col].ToString()); foreach (SPFieldLookupValue option in options) { if (mask.EndsWith("*")) { mask = mask.Substring(0, mask.Length - 1); if (!option.LookupValue.StartsWith(mask)) { newOptions.Add(option); } } else { if (!option.LookupValue.Equals(mask)) { newOptions.Add(option); } } } item[col] = newOptions; }
public void Create(ChatMessage message) { IContactRepository repo = new ContactRepository(); var id = SPContext.Current.Web.CurrentUser.ID; SPList list = Config.GetList(SPContext.Current.Web); List <int> ids = message.Receivers.Select(r => r.ID).ToList(); ids.Add(id); SPListItem conversation = Config.GetConversationFolder(list, ids.ToArray()); if (conversation == null) { conversation = Config.CreateConversationFolder(SPContext.Current.Web, Guid.NewGuid().ToString().Replace("-", ""), ids.Select(i => repo.CreateRoleAssignment(Language.SMUGroupName, i)).ToArray()); } SPItem item = list.Items.Add(conversation.Folder.ServerRelativeUrl, SPFileSystemObjectType.File, message.Title); item[ChatMessageFields.Title] = message.Title; item[ChatMessageFields.Message] = message.Message; item[ChatMessageFields.IsRead] = false; SPFieldLookupValueCollection receivers = new SPFieldLookupValueCollection(); foreach (Contact c in message.Receivers) { receivers.Add(new SPFieldLookupValue(c.ID, null)); } item[ChatMessageFields.Receivers] = receivers; item.Update(); }
internal static bool HasServiceAssigned(SPWeb web, int klientId, string serwisKod) { bool result = false; SPList targetList = web.Lists.TryGetList(listName); //if (targetList != null) //{ SPListItem item = targetList.GetItemById(klientId); if (item != null) { SPFieldLookupValueCollection kody = new SPFieldLookupValueCollection(item["selSewisy"].ToString()); foreach (SPFieldLookupValue kod in kody) { if (kod.LookupValue == serwisKod) { result = true; break; } } kody = new SPFieldLookupValueCollection(item["selSerwisyWspolnicy"].ToString()); foreach (SPFieldLookupValue kod in kody) { if (kod.LookupValue == serwisKod) { result = true; break; } } } //} return result; }
public SPFieldLookupValueCollectionInstance(ScriptEngine engine, SPFieldLookupValueCollection fieldLookupValueCollection) : base(new ListInstance <SPFieldLookupValueCollectionInstance, SPFieldUserValue>(engine)) { this.m_fieldLookupValueCollection = fieldLookupValueCollection; this.List = fieldLookupValueCollection; this.PopulateFunctions(this.GetType(), BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy); }
public static string GetStringValue(this SPListItem item, string fieldname) { if (item[fieldname] == null || string.IsNullOrEmpty(item[fieldname].ToString().Trim())) { return(string.Empty); } SPField field = item.Fields.GetField(fieldname); string ReturnValue; switch (field.Type) { case SPFieldType.Lookup: if (((SPFieldLookup)field).AllowMultipleValues == false) { SPFieldLookupValue lookup = new SPFieldLookupValue(item[fieldname].ToString()); ReturnValue = lookup.LookupValue; } else { SPFieldLookupValueCollection lookup = new SPFieldLookupValueCollection(item[fieldname].ToString()); ReturnValue = ""; foreach (SPFieldLookupValue v in lookup) { ReturnValue += v.LookupValue + ";"; } ReturnValue.TrimEnd(';'); } break; case SPFieldType.User: if (((SPFieldUser)field).AllowMultipleValues == false) { SPFieldUserValue users = new SPFieldUserValue(item.Web, item[fieldname].ToString()); ReturnValue = users.User.Name; } else { SPFieldUserValueCollection users = new SPFieldUserValueCollection(item.Web, item[fieldname].ToString()); ReturnValue = users[0].User.Name; } break; case SPFieldType.MultiChoice: SPFieldMultiChoiceValue values = new SPFieldMultiChoiceValue(item[fieldname].ToString()); ReturnValue = ""; for (int i = 0; i < values.Count; i++) { ReturnValue += values[i].ToString() + ";"; } ReturnValue.TrimEnd(';'); break; default: ReturnValue = item[fieldname].ToString().Trim(); break; } return(ReturnValue); }
private void MatchSPFieldTextOrChoice(SPListItem targetSPListItem, SPField targetSPField, SPWeb sourceSPWeb, SPField sourceSPField, string sourceValue) { // get just the term label if (sourceSPField is TaxonomyField) { targetSPListItem[targetSPField.Id] = this.SubstringBefore(sourceValue, TaxonomyField.TaxonomyGuidLabelDelimiter.ToString(CultureInfo.InvariantCulture)); } // for lookup and custom fields, convert RAW values into plain text else if (sourceSPField.Type == SPFieldType.Lookup || sourceSPField.Type == SPFieldType.Invalid) { SPFieldLookup spFieldLookupField = sourceSPField as SPFieldLookup; if (spFieldLookupField == null) { // TODO: multi-valued source fields should be deconstructed properly! targetSPListItem[targetSPField.Id] = this.SubstringAfter(sourceValue, ";#"); } else { if (spFieldLookupField.AllowMultipleValues) { string formatted = string.Empty; SPFieldLookupValueCollection spFieldLookupValues = new SPFieldLookupValueCollection(sourceValue); foreach (SPFieldLookupValue spFieldLookupValue in spFieldLookupValues) { formatted = formatted + ";" + spFieldLookupValue.LookupValue; } targetSPListItem[targetSPField.Id] = formatted.TrimStart(';'); } else { SPFieldLookupValue spFieldLookupValue = new SPFieldLookupValue(sourceValue); targetSPListItem[targetSPField.Id] = spFieldLookupValue.LookupValue; } } } else if (sourceSPField.Type == SPFieldType.User) { // TODO: TEST THIS !!!!!!!! string formatted = string.Empty; SPFieldUserValueCollection spFieldUserValues = new SPFieldUserValueCollection(sourceSPWeb, sourceValue); foreach (SPFieldLookupValue spFieldLookupValue in spFieldUserValues) { formatted = formatted + ";" + spFieldLookupValue.LookupValue; } targetSPListItem[targetSPField.Id] = formatted.TrimStart(';'); } else { targetSPListItem[targetSPField.Id] = this.SubstringAfter(sourceValue, ";#"); } }
//private void CreateMailRequest(Customer cust, SPItemEventProperties properties) //{ // SPList tList = properties.Web.Lists["Powiadomienia"]; // SPListItem item = tList.AddItem(); // try // { // item["_Klient"] = cust.Id; // item["_Kontakt"] = cust.Email; // item["_Temat"] = ":: " + properties.ListItem.Title; // item["Operator"] = properties.UserLoginName; // if (properties.ListItem["Body"] != null) // { // item["_Tre_x015b__x0107_"] = properties.ListItem["Body"].ToString(); // } // item["_Typ_x0020_powiadomienia"] = @"E-Mail Grupowy"; // if (properties.ListItem["colPlanowanyTerminWysylki"] != null) // { // item["Data_x0020_wysy_x0142_ki"] = properties.ListItem["colPlanowanyTerminWysylki"].ToString(); // } // item["_OgloszenieId"] = properties.ListItemId; // item.Update(); // } // catch (Exception ex) // { // throw; // } //} private void GetTargetList(SPFieldLookupValueCollection searchCriteriaCollection, SPItemEventProperties properties) { /// StringBuilder sb = new StringBuilder(@"<OrderBy><FieldRef Name='ID' Ascending='FALSE' /></OrderBy><Where><IsNotNull><FieldRef Name='_Serwisy' /></IsNotNull></Where>"); string camlQuery = sb.ToString(); using (SPSite site = new SPSite(properties.SiteId)) { using (SPWeb web = site.OpenWeb(properties.Web.ID)) { /// SPList list = web.Lists["Klienci"]; SPQuery query = new SPQuery(); query.Query = camlQuery; SPListItemCollection items = list.GetItems(query); if (items.Count > 0) { foreach (SPListItem item in items) { //sprawdź czy spełnia kryteria wyboru bool isMatched = false; SPFieldLookupValueCollection itemCriteriaCollection = (SPFieldLookupValueCollection)item["_Serwisy"]; foreach (SPFieldLookupValue itemCurrent in itemCriteriaCollection) { foreach (SPFieldLookupValue itemSearched in searchCriteriaCollection) { if (itemCurrent.LookupId == itemSearched.LookupId) { //dodaj klienta do listy wynikowej Customer cust = new Customer(item.ID, item["_Adres_x0020_e_x002d_mail"].ToString(), item["_Nazwa"].ToString()); MatchedCustomers.Add(cust); isMatched = true; } if (isMatched) { break; } } if (isMatched) { break; } } } } } } }
public void SP() { var s1 = "91;#asd;#577;#asd;#"; var s2 = "91;#;#577;#"; var mlv = new SPFieldLookupValueCollection(s1); var mlv2 = new SPFieldLookupValueCollection(s2); }
private void OnMultiLookupValueChanged(object sender, string fieldName) { SPFieldLookupValueCollection collection = new SPFieldLookupValueCollection(); foreach (string item in (IEnumerable)sender) { collection.Add(new SPFieldLookupValue(GetLookupIdByValue(fieldName, item), item)); } this[fieldName] = collection.ToString(); }
public static List <LookupItem> ToLookupItemsModel(this SPListItem item, string fieldName) { var objLookupFieldValueCol = new SPFieldLookupValueCollection(item[fieldName].ToString()); return (objLookupFieldValueCol.Select( singleValue => new LookupItem { LookupId = singleValue.LookupId, LookupValue = singleValue.LookupValue }).ToList()); }
private static SPFieldLookupValueCollection CreateSharePointLookupCollection(LookupValueCollection lookupCollection) { SPFieldLookupValueCollection returnCollection = new SPFieldLookupValueCollection(); foreach (LookupValue lookup in lookupCollection) { returnCollection.Add(new SPFieldLookupValue(lookup.Id, lookup.Value)); } return(returnCollection); }
private void OnModelCollectionChanged(object sender, string fieldName) { SPFieldLookup field = this.ObjectCache.GetField(this.WebId, this.ListId, fieldName) as SPFieldLookup; SPFieldLookupValueCollection collection = new SPFieldLookupValueCollection(); foreach (SPModel item in (IEnumerable)sender) { collection.Add(new SPFieldLookupValue(item.Adapter.ListItemId, item.Adapter.GetString(field.LookupField))); } this[fieldName] = collection.ToString(); }
static void Main(string[] args) { string personListName = "Person"; string[] jobs = { "Developer", "Admin", "Organization" }; string[] skills = { "C#", "TypeScript", "React" }; SPSite col = new SPSite("http://SP2016"); SPWeb web = col.RootWeb; SPList list = web.Lists.TryGetList(personListName); if (list == null) { var skillslist = addListWithItems(web, "Skills", "A skills List", skills); var joblist = addListWithItems(web, "Jobs", "A job List", jobs); Guid id = web.Lists.Add(personListName, "A Person List", SPListTemplateType.GenericList); list = web.Lists.TryGetList(personListName); var jobCol = list.Fields.AddLookup("Jobs", joblist.ID, true); SPFieldLookup jobLookup = (SPFieldLookup)list.Fields[jobCol]; jobLookup.LookupField = joblist.Fields["Title"].InternalName; jobLookup.Title = "Job"; jobLookup.Update(); list.Update(); var skillCol = list.Fields.AddLookup("Skills", skillslist.ID, true); SPFieldLookup skillLookup = (SPFieldLookup)list.Fields[skillCol]; skillLookup.LookupField = skillslist.Fields["Title"].InternalName; skillLookup.Title = "Skills"; skillLookup.AllowMultipleValues = true; skillLookup.Update(); list.Update(); var person = list.Items.Add(); person["Title"] = "Bob der Baumeister"; person["Job"] = new SPFieldLookupValue(1, jobs[0]); var sks = new SPFieldLookupValueCollection { new SPFieldLookupValue(1, skills[0]), new SPFieldLookupValue(3, skills[2]) }; person["Skills"] = sks; person.Update(); } foreach (SPListItem item in list.Items) { SPFieldLookupValue job = new SPFieldLookupValue(item["Job"].ToString()); string skillsString = GetSkills(item); Console.WriteLine("{0} works as a {1} with skills {2}", item["Title"], job.LookupValue, skillsString); } }
public static void Assign_Service(ref SPListItem item, string col, string serwisName) { int serwisId = BLL.dicSerwisy.Get_IdByKod(item.Web, serwisName); if (serwisId > 0) { SPFieldLookupValue option = new SPFieldLookupValue(serwisId, serwisName); SPFieldLookupValueCollection options = new SPFieldLookupValueCollection(item[col].ToString()); options.Add(option); item[col] = options; } }
/// <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 LookupValueCollection ReadValueFromListItemVersion(SPListItemVersion itemVersion, string fieldInternalName) { var fieldValue = itemVersion[fieldInternalName]; if (fieldValue != null) { var lookupFieldVal = new SPFieldLookupValueCollection(fieldValue.ToString()); return(new LookupValueCollection(lookupFieldVal)); } return(null); }
static string GetSkills(SPListItem Item) { string result = string.Empty; SPFieldLookupValueCollection skills = new SPFieldLookupValueCollection(Item["Skills"].ToString()); for (int i = 0; i < skills.Count; i++) { SPFieldLookupValue skill = skills[i]; result += skill.LookupValue + ";"; } return(result); }
private void InsertEPMLiveGenericPickerControl(FormField formField, LookupConfigData lookupData, string fieldType) { if (formField == null) { throw new ArgumentNullException(nameof(formField)); } picker = new GenericEntityEditor(); var fieldLookup = GetFieldLookup(formField); picker.MultiSelect = fieldLookup.AllowMultipleValues; var customValue = GetCustomValue(formField, lookupData, fieldLookup, fieldType); SPFieldLookupValueCollection lookupValCol = null; if (mode == SPControlMode.New) { lookupValCol = GetQueryStringLookupVal(formField); } else { try { lookupValCol = new SPFieldLookupValueCollection(ListItem[fieldLookup.Id].ToString()); } catch (Exception ex) { Trace.WriteLine(ex.ToString()); } } if (lookupValCol?.Count > 0) { var alItems = new ArrayList(); foreach (var field in lookupValCol) { var entity = new PickerEntity { Key = field.LookupId.ToString(), DisplayText = field.LookupValue, IsResolved = true }; alItems.Add(entity); } picker.UpdateEntities(alItems); } picker.CustomProperty = customValue; formField.Controls.Add(picker); }
protected override void OnInit(EventArgs e) { if (ControlMode == SPControlMode.Edit || ControlMode == SPControlMode.Display) { if (base.ListItemFieldValue != null) { _fieldVals = base.ListItemFieldValue as SPFieldLookupValueCollection; } else { _fieldVals = new SPFieldLookupValueCollection(); } } if (ControlMode == SPControlMode.New) { _fieldVals = new SPFieldLookupValueCollection(); } base.OnInit(e); Initialize((CustomDropDownList)this.Field); }
private SPFieldLookupValueCollection GetQueryStringLookupVal(SPField fld) { if (string.IsNullOrEmpty(lookupField) || !fld.InternalName.Equals(lookupField)) { return(null); } SPFieldLookupValueCollection result = new SPFieldLookupValueCollection(); // assume single lookup bool valIsMulti = false; List <int> ids = new List <int>(); if (!string.IsNullOrEmpty(this.lookupValue)) { valIsMulti = this.lookupValue.Contains(','); if (valIsMulti) { string[] sIds = this.lookupValue.Split(','); foreach (string s in sIds) { if (!string.IsNullOrEmpty(s.Trim())) { ids.Add(int.Parse(s)); } } } } SPFieldLookup lookupFld = fld as SPFieldLookup; bool isMulti = lookupFld.AllowMultipleValues; // insert single value to single lookup field if (!isMulti && !valIsMulti) { int itemId; if (int.TryParse(lookupValue.Trim(), out itemId)) { result.Add(new SPFieldLookupValue(itemId, GetLookupItemValue(lookupFld, itemId))); } } // insert multi lookup value to multi lookup field else if (isMulti && valIsMulti) { foreach (int id in ids) { result.Add(new SPFieldLookupValue(id, GetLookupItemValue(lookupFld, id))); } } return(result); }
public static SPFieldLookupValueCollection GetMultipleItemSelectionValues(GroupedItemPicker groupItemPicker) { SPFieldLookupValueCollection lookupValues = new SPFieldLookupValueCollection(); if (groupItemPicker.SelectedIds.Count > 0) { lookupValues.AddRange(from KeyValuePair<int, string> kvp in itemDetails where (from gip in groupItemPicker.SelectedIds.Cast<string>() where Convert.ToInt32(gip) == kvp.Key select gip).Contains(kvp.Key.ToString()) select new SPFieldLookupValue(kvp.Key, kvp.Value)); } return lookupValues; }
public static void Create(SPWeb web, int klientId, int okresId, bool createKK) { Debug.WriteLine("Create PD Form"); SPListItem item = tabKlienci.Get_KlientById(web, klientId); if (item != null) { SPFieldLookupValueCollection kody; switch (item.ContentType.Name) { case "Osoba fizyczna": case "Firma": kody = new SPFieldLookupValueCollection(item["selSerwisyWspolnicy"].ToString()); break; default: kody = new SPFieldLookupValueCollection(item["selSewisy"].ToString()); break; } foreach (SPFieldLookupValue kod in kody) { switch (kod.LookupValue) { case @"PD-M": if (createKK) { BLL.tabKartyKontrolne.Create_KartaKontrolna(web, item.ID, okresId); } Create_PD_M_Form(web, item.ID, okresId); break; case @"PD-KW": if (createKK) { BLL.tabKartyKontrolne.Create_KartaKontrolna(web, item.ID, okresId); } Create_PD_KW_Form(web, item.ID, okresId); break; default: break; } } } }
public object FromSpValue(object value) { if (value == null||string.IsNullOrEmpty(Field.LookupList)) return null; if (!Field.AllowMultipleValues) { var fieldValue = new SPFieldLookupValue(value.ToString()); return new ObjectReference(new Guid(Field.LookupList), fieldValue.LookupId, fieldValue.LookupValue); } var fieldValues = new SPFieldLookupValueCollection(value.ToString()); return fieldValues.Select(fieldValue => new ObjectReference(new Guid(Field.LookupList), fieldValue.LookupId, fieldValue.LookupValue)).ToList(); }
private void getApprovalEntryNames(SPList currentList) { SPListItem currentItem = currentList.GetItemById(__ListItem); if (currentItem[EntriesColumn] != null) { SPFieldLookupValueCollection entries = new SPFieldLookupValueCollection(currentItem[EntriesColumn].ToString()); if (entries != null && entries.Count > 0) { foreach (SPFieldLookupValue entry in entries) { _approvalEntries.Add(entry.LookupValue); } return; } } __ActivationProperties.LogToWorkflowHistory(SPWorkflowHistoryEventType.None, __ActivationProperties.Web.CurrentUser, "Skipped: There is no Approval Entry defined.", string.Empty); }
private void AddPurchase() { SPFieldLookupValueCollection RequestDetails = new SPFieldLookupValueCollection(); var RequestDetailList = Utility.GetListFromURL(Constants.REQUEST_DETAIL_LIST_URL, SPContext.Current.Web); foreach (RepeaterItem RequestDetail in repeaterRequestDetail.Items) { TextBox txtProductName = RequestDetail.FindControl("txtProductName") as TextBox; TextBox txtQuantity = RequestDetail.FindControl("txtQuantity") as TextBox; TextBox txtPrice = RequestDetail.FindControl("txtPrice") as TextBox; TextBox txtDescription = RequestDetail.FindControl("txtDescription") as TextBox; if (!string.IsNullOrEmpty(txtProductName.Text)) { SPListItem RequestDetailItem = RequestDetailList.AddItem(); RequestDetailItem[SPBuiltInFieldId.Title] = txtProductName.Text; RequestDetailItem["Quantity"] = txtQuantity.Text.Replace(",", string.Empty); RequestDetailItem["Price"] = txtPrice.Text.Replace(",", string.Empty); RequestDetailItem["Description"] = txtDescription.Text; RequestDetailItem.Update(); SPFieldLookupValue spFieldLookupValue = new SPFieldLookupValue(RequestDetailItem.ID, RequestDetailItem.Title); RequestDetails.Add(spFieldLookupValue); } } var purchaseList = Utility.GetListFromURL(Constants.REQUEST_LIST_URL, SPContext.Current.Web); SPListItem purchaseItem = SPContext.Current.ListItem; purchaseItem[SPBuiltInFieldId.Title] = ffTitle.Value;//Constants.PURCHASE_TITLE_PREFIX + literalUserRequestValue.Text; purchaseItem["DateRequest"] = DateTime.Now; purchaseItem["UserRequest"] = SPContext.Current.Web.CurrentUser; purchaseItem["DepartmentRequest"] = literalDepartmentRequestValue.Text; purchaseItem["TypeOfApproval"] = hiddenTypeOfApproval.Value; purchaseItem["RequestDetail"] = RequestDetails; purchaseItem["References"] = ffReferences.Value; //PurchaseHelper.GetMultipleItemSelectionValues(purchaseReferences); if(peChief.IsValid && peChief.ResolvedEntities.Count > 0) purchaseItem["Chief"] = SPContext.Current.Web.EnsureUser(((PickerEntity)peChief.ResolvedEntities[0]).Key); //ffChief.Value; // if (peBuyer.IsValid && peBuyer.ResolvedEntities.Count > 0) purchaseItem["Buyer"] = SPContext.Current.Web.EnsureUser(((PickerEntity)peBuyer.ResolvedEntities[0]).Key); //ffBuyer.Value; // if (peApprover.IsValid && peApprover.ResolvedEntities.Count > 0) purchaseItem["Approver"] = SPContext.Current.Web.EnsureUser(((PickerEntity)peApprover.ResolvedEntities[0]).Key); //ffApprover.Value; // if (peAccountant.IsValid && peAccountant.ResolvedEntities.Count > 0) purchaseItem["Accountant"] = SPContext.Current.Web.EnsureUser(((PickerEntity)peAccountant.ResolvedEntities[0]).Key); //ffAccountant.Value; // if (peConfirmer.IsValid && peConfirmer.ResolvedEntities.Count > 0) purchaseItem["Confirmer"] = SPContext.Current.Web.EnsureUser(((PickerEntity)peConfirmer.ResolvedEntities[0]).Key); //ffConfirmer.Value; // SaveButton.SaveItem(SPContext.Current, false, ""); }
internal static void Create(SPWeb web, Array klienci, int okresId) { foreach (SPListItem item in klienci) { SPFieldLookupValueCollection kody = new SPFieldLookupValueCollection(item["selSewisy"].ToString()); foreach (SPFieldLookupValue kod in kody) { if (kod.LookupValue == "POW-Dok") { Create_POW_DOK_Form(web, item.ID, okresId); } if (kod.LookupValue == "POW-WBank") { Create_POW_WBANK_Form(web, item.ID, okresId); } } } }
internal static void Create(Microsoft.SharePoint.SPWeb web, Array aKlienci, int okresId) { foreach (SPListItem item in aKlienci) { SPFieldLookupValueCollection kody = new SPFieldLookupValueCollection(item["selSewisy"].ToString()); foreach (SPFieldLookupValue kod in kody) { switch (kod.LookupValue) { case @"RBR": Create_BR_Form(web, item.ID, okresId); break; default: break; } } } }
public object ToSpValue(object value) { if (value == null) return null; if (!Field.AllowMultipleValues) { var reference = (ObjectReference)value; return new SPFieldLookupValue(reference.Id, reference.Value); } var references = (IEnumerable<ObjectReference>)value; var fieldValues = new SPFieldLookupValueCollection(); fieldValues.AddRange(references.Select(referenceInfo => new SPFieldLookupValue(referenceInfo.Id, referenceInfo.Value))); return fieldValues; }
internal static void Create(Microsoft.SharePoint.SPWeb web, int klientId, int okresId) { SPListItem item = tabKlienci.Get_KlientById(web, klientId); if (item != null) { SPFieldLookupValueCollection kody = new SPFieldLookupValueCollection(item["selSewisy"].ToString()); foreach (SPFieldLookupValue kod in kody) { switch (kod.LookupValue) { case @"RBR": Create_BR_Form(web, item.ID, okresId); break; default: break; } } } }
internal static void Create(SPWeb web, int klientId, int okresId) { SPListItem item = tabKlienci.Get_KlientById(web, klientId); if (item != null) { SPFieldLookupValueCollection kody = new SPFieldLookupValueCollection(item["selSewisy"].ToString()); foreach (SPFieldLookupValue kod in kody) { if (kod.LookupValue == "POW-Dok") { Create_POW_DOK_Form(web, item.ID, okresId); } if (kod.LookupValue == "POW-WBank") { Create_POW_WBANK_Form(web, item.ID, okresId); } } } }
public static void CreateAll(SPWeb web, Array aKlienci, int okresId, bool createKK) { foreach (SPListItem item in aKlienci) { Debug.WriteLine("klientId=" + item.ID.ToString()); SPFieldLookupValueCollection kody; switch (item.ContentType.Name) { case "Osoba fizyczna": case "Firma": kody = new SPFieldLookupValueCollection(item["selSerwisyWspolnicy"].ToString()); break; default: kody = new SPFieldLookupValueCollection(item["selSewisy"].ToString()); break; } foreach (SPFieldLookupValue kod in kody) { switch (kod.LookupValue) { case @"PD-M": if (createKK) BLL.tabKartyKontrolne.Create_KartaKontrolna(web, item.ID, okresId); Create_PD_M_Form(web, item.ID, okresId); break; case @"PD-KW": if (createKK) BLL.tabKartyKontrolne.Create_KartaKontrolna(web, item.ID, okresId); Create_PD_KW_Form(web, item.ID, okresId); break; default: break; } } } }
public static void CreateNew(SPWeb web, SPListItem item, int okresId) { if (item != null) { SPFieldLookupValueCollection kody; kody = new SPFieldLookupValueCollection(item["selSewisy"].ToString()); foreach (SPFieldLookupValue kod in kody) { switch (kod.LookupValue) { case @"PDW-M": Create_PDW_M_Form(web, item.ID, okresId); break; case @"PDW-KW": Create_PDW_KW_Form(web, item.ID, okresId); break; default: break; } } } }
public static SPFieldLookupValueCollection GetCatsByNewsID(string newsID) { var result = new SPFieldLookupValueCollection(); SPSecurity.RunWithElevatedPrivileges(() => { using (var site = new SPSite(SPContext.Current.Web.Site.ID)) { using (var web = site.OpenWeb(SPContext.Current.Web.ID)) { try { SPQuery spQuery = new SPQuery { Query = string.Format(@"<Where> <And> <Eq> <FieldRef Name='ID' /> <Value Type='Counter'>{0}</Value> </Eq> <And> <Lt> <FieldRef Name='{1}' /> <Value IncludeTimeValue='TRUE' Type='DateTime'>{2}</Value> </Lt> <And> <Neq> <FieldRef Name='Status' /> <Value Type='Boolean'>1</Value> </Neq> <Eq> <FieldRef Name='{3}' /> <Value Type='Number'>{4}</Value> </Eq> </And> </And> </And> </Where><OrderBy> <FieldRef Name='{5}' Ascending='False' /> </OrderBy>", newsID, FieldsName.ArticleStartDates, SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now), FieldsName.ModerationStatus, ModerationStatusValue, FieldsName.ArticleStartDates), RowLimit = 1 }; SPList list = GetListFromUrl(web, ListsName.English.NewsRecord); if (list != null) { SPListItemCollection items = list.GetItems(spQuery); if (items != null && items.Count > 0) { result = new SPFieldLookupValueCollection(Convert.ToString(items[0][FieldsName.NewsRecord.English.CategoryName])); } } } catch (Exception ex) { } } } }); return result; }
public static bool ValidateItemProperty(SPListItem item, Guid fieldId, Criteria criteria, string itemValueString) { switch (item.Fields[fieldId].Type) { case SPFieldType.Boolean: return Boolean.Parse(itemValueString).EnhancedCompareTo(criteria); case SPFieldType.User: SPFieldUser userField = (SPFieldUser)item.Fields[fieldId]; SPPrincipal spPrincipal = item.ParentList.ParentWeb.Site.FindUserOrSiteGroup(itemValueString); if (userField.AllowMultipleValues) { //SPFieldLookupValueCollection userValues = new SPFieldLookupValueCollection(itemValueString); //return userValues.EnhancedCompareTo(criteria); return false; } SPFieldLookupValue userValue = new SPFieldLookupValue(spPrincipal.ID, spPrincipal.Name); return userValue.EnhancedCompareTo(criteria); case SPFieldType.Lookup: SPFieldLookup lookupField = (SPFieldLookup)item.Fields[fieldId]; if (lookupField.AllowMultipleValues) { SPFieldLookupValueCollection itemValueCol = new SPFieldLookupValueCollection(itemValueString); return itemValueCol.EnhancedCompareTo(criteria); } SPFieldLookupValue itemFieldValue = (SPFieldLookupValue)lookupField.GetFieldValue(itemValueString); return itemFieldValue.EnhancedCompareTo(criteria); case SPFieldType.Computed: case SPFieldType.Note: case SPFieldType.Text: return itemValueString.EnhancedCompareTo(criteria); case SPFieldType.Currency: case SPFieldType.Integer: case SPFieldType.Number: long itemValue; if (long.TryParse(itemValueString, out itemValue)) { return itemValue.EnhancedCompareTo(criteria); } break; case SPFieldType.DateTime: DateTime itemDateTimeValue; if (DateTime.TryParse(itemValueString, out itemDateTimeValue)) { return itemDateTimeValue.EnhancedCompareTo(criteria); } break; default: return itemValueString.EnhancedCompareTo(criteria); } return false; }
public static bool EnhancedCompareTo(this List<SPFieldLookupValue> itemValueCol, Criteria criteria) { SPFieldLookupValueCollection criteriaValueCol = new SPFieldLookupValueCollection(criteria.Value); var query1 = from criteriaLookup in criteriaValueCol join itemLookup in itemValueCol on criteriaLookup.LookupId equals itemLookup.LookupId select new { criteriaLookup.LookupId }; switch (criteria.Operator) { case Operators.Equal: return (itemValueCol.Count == criteriaValueCol.Count && query1.Count() == criteriaValueCol.Count); case Operators.NotEqual: return (itemValueCol.Count != criteriaValueCol.Count || query1.Count() != criteriaValueCol.Count); case Operators.Contains: var query2 = from itemLookup in itemValueCol join criteriaLookup in criteriaValueCol on itemLookup.LookupId equals criteriaLookup.LookupId select new { criteriaLookup.LookupId }; return (query2.Count() == criteriaValueCol.Count); } return false; }
public static void Assign_Service(ref SPListItem item, string col, string serwisName) { int serwisId = BLL.dicSerwisy.Get_IdByKod(item.Web, serwisName); if (serwisId > 0) { SPFieldLookupValue option = new SPFieldLookupValue(serwisId, serwisName); SPFieldLookupValueCollection options = new SPFieldLookupValueCollection(item[col].ToString()); options.Add(option); item[col] = options; } }
public static void Remove_Services(ref SPListItem item, string col, string mask) { SPFieldLookupValueCollection newOptions = new SPFieldLookupValueCollection(); SPFieldLookupValueCollection options = new SPFieldLookupValueCollection(item[col].ToString()); foreach (SPFieldLookupValue option in options) { if (mask.EndsWith("*")) { mask = mask.Substring(0, mask.Length - 1); if (!option.LookupValue.StartsWith(mask)) { newOptions.Add(option); } } else { if (!option.LookupValue.Equals(mask)) { newOptions.Add(option); } } } item[col] = newOptions; }
/// <summary> /// Page on Load /// </summary> /// <param name="sender">Object sender</param> /// <param name="e">EventArgs e</param> protected void Page_Load(object sender, EventArgs e) { if (SPContext.Current.FormContext.FormMode.Equals(SPControlMode.New)) { txtRichImageField.Visible = false; afAttach.Visible = false; } if (SPContext.Current.FormContext.FormMode.Equals(SPControlMode.Edit)) { txtRichImageField.ControlMode = SPControlMode.Display; } if (SPContext.Current.FormContext.FormMode.Equals(SPControlMode.Display)) { ddlCat.Visible = false; lblCat.Visible = true; if (!IsPostBack) { } } else { ddlCat.Visible = true; lblCat.Visible = false; } if (!IsPostBack) { BindCat(); BindAttach(); if (SPContext.Current.FormContext.FormMode.Equals(SPControlMode.Edit)) { var item = SPContext.Current.Item; if (!string.IsNullOrEmpty(Convert.ToString(item[FieldsName.NewsRecord.English.CategoryName]))) { SPFieldLookupValueCollection returnVal = new SPFieldLookupValueCollection(Convert.ToString(item[FieldsName.NewsRecord.English.CategoryName])); foreach (SPFieldLookupValue lookupValue in returnVal) { ListItem bitem = ddlCat.Items.FindByValue(lookupValue.LookupId.ToString()); if (bitem != null) { bitem.Selected = true; } } } } } else { if ("deleteattach".Equals(Convert.ToString(Request.Form["__EVENTTARGET"]), StringComparison.InvariantCultureIgnoreCase)) { #region Delete var list = SPContext.Current.List; var item = SPContext.Current.ListItem; SPFileCollection files = null; SPFolder itemFolder = null; //Get tha Attachment Folder string strAttchmentFolderURL = item.Attachments.UrlPrefix; if (list.RootFolder.SubFolders.Count > 0) { if (list.RootFolder.SubFolders["Attachments"] != null) { itemFolder = list.RootFolder.SubFolders["Attachments"]; } } string strTempID = Convert.ToString(Request.Form["__EVENTARGUMENT"]); //I know there is better way to remove characters strTempID = strTempID.Replace("{", ""); strTempID = strTempID.Replace("}", ""); //Get all the files in Attachment Folder that matches the GUID #region getFiles if (itemFolder.SubFolders[strAttchmentFolderURL] != null) { files = itemFolder.SubFolders[strAttchmentFolderURL].Files; } #endregion foreach (SPFile file in files) { if (strTempID.ToLower().Equals(file.UniqueId.ToString().ToLower())) { //Delete the file finally file.Delete(); break; } } #endregion Response.Redirect(Request.RawUrl); } } }
public static void CreateNew(SPWeb web, SPListItem item, int okresId) { Debug.WriteLine("Create RBR Form"); SPFieldLookupValueCollection kody; kody = new SPFieldLookupValueCollection(item["selSewisy"].ToString()); foreach (SPFieldLookupValue kod in kody) { switch (kod.LookupValue) { case @"RBR": Create_BR_Form(web, item.ID, okresId); break; default: break; } } }
public void ToEntity_WhenMappingFromListItem_AndItemPropertiesAreFilledWithValues_ShouldMapEntityWithAllItemValues() { using (var testScope = SiteTestScope.BlankSite()) { // Arrange IntegerFieldInfo integerFieldInfo = new IntegerFieldInfo( "TestInternalNameInteger", new Guid("{12E262D0-C7C4-4671-A266-064CDBD3905A}"), "NameKeyInt", "DescriptionKeyInt", "GroupKey"); NumberFieldInfo numberFieldInfo = new NumberFieldInfo( "TestInternalNameNumber", new Guid("{5DD4EE0F-8498-4033-97D0-317A24988786}"), "NameKeyNumber", "DescriptionKeyNumber", "GroupKey"); CurrencyFieldInfo currencyFieldInfo = new CurrencyFieldInfo( "TestInternalNameCurrency", new Guid("{9E9963F6-1EE6-46FB-9599-783BBF4D6249}"), "NameKeyCurrency", "DescriptionKeyCurrency", "GroupKey"); BooleanFieldInfo boolFieldInfoBasic = new BooleanFieldInfo( "TestInternalNameBool", new Guid("{F556AB6B-9E51-43E2-99C9-4A4E551A4BEF}"), "NameKeyBool", "DescriptionKeyBool", "GroupKey"); BooleanFieldInfo boolFieldInfoDefaultTrue = new BooleanFieldInfo( "TestInternalNameBoolTrue", new Guid("{0D0289AD-C5FB-495B-96C6-48CC46737D08}"), "NameKeyBoolTrue", "DescriptionKeyBoolTrue", "GroupKey") { DefaultValue = true }; BooleanFieldInfo boolFieldInfoDefaultFalse = new BooleanFieldInfo( "TestInternalNameBoolFalse", new Guid("{628181BD-9B0B-4B7E-934F-1CF1796EA4E4}"), "NameKeyBoolFalse", "DescriptionKeyBoolFalse", "GroupKey") { DefaultValue = false }; DateTimeFieldInfo dateTimeFieldInfoFormula = new DateTimeFieldInfo( "TestInternalNameDateFormula", new Guid("{D23EAD73-9E18-46DB-A426-41B2D47F696C}"), "NameKeyDateTimeFormula", "DescriptionKeyDateTimeFormula", "GroupKey") { DefaultFormula = "=[Today]" }; DateTimeFieldInfo dateTimeFieldInfoDefault = new DateTimeFieldInfo( "TestInternalNameDateDefault", new Guid("{016BF8D9-CEDC-4BF4-BA21-AC6A8F174AD5}"), "NameKeyDateTimeDefault", "DescriptionKeyDateTimeDefault", "GroupKey"); TextFieldInfo textFieldInfo = new TextFieldInfo( "TestInternalNameText", new Guid("{0C58B4A1-B360-47FE-84F7-4D8F58AE80F6}"), "NameKey", "DescriptionKey", "GroupKey"); NoteFieldInfo noteFieldInfo = new NoteFieldInfo( "TestInternalNameNote", new Guid("{E315BB24-19C3-4F2E-AABC-9DE5EFC3D5C2}"), "NameKeyAlt", "DescriptionKeyAlt", "GroupKey"); HtmlFieldInfo htmlFieldInfo = new HtmlFieldInfo( "TestInternalNameHtml", new Guid("{D16958E7-CF9A-4C38-A8BB-99FC03BFD913}"), "NameKeyAlt", "DescriptionKeyAlt", "GroupKey"); ImageFieldInfo imageFieldInfo = new ImageFieldInfo( "TestInternalNameImage", new Guid("{6C5B9E77-B621-43AA-BFBF-B333093EFCAE}"), "NameKeyImage", "DescriptionKeyImage", "GroupKey"); UrlFieldInfo urlFieldInfo = new UrlFieldInfo( "TestInternalNameUrl", new Guid("{208F904C-5A1C-4E22-9A79-70B294FABFDA}"), "NameKeyUrl", "DescriptionKeyUrl", "GroupKey"); UrlFieldInfo urlFieldInfoImage = new UrlFieldInfo( "TestInternalNameUrlImg", new Guid("{96D22CFF-5B40-4675-B632-28567792E11B}"), "NameKeyUrlImg", "DescriptionKeyUrlImg", "GroupKey") { Format = UrlFieldFormat.Image }; LookupFieldInfo lookupFieldInfo = new LookupFieldInfo( "TestInternalNameLookup", new Guid("{62F8127C-4A8C-4217-8BD8-C6712753AFCE}"), "NameKey", "DescriptionKey", "GroupKey"); LookupFieldInfo lookupFieldInfoAlt = new LookupFieldInfo( "TestInternalNameLookupAlt", new Guid("{1F05DFFA-6396-4AEF-AD23-72217206D35E}"), "NameKey", "DescriptionKey", "GroupKey") { ShowField = "ID" }; LookupMultiFieldInfo lookupMultiFieldInfo = new LookupMultiFieldInfo( "TestInternalNameLookupM", new Guid("{2C9D4C0E-21EB-4742-8C6C-4C30DCD08A05}"), "NameKeyMulti", "DescriptionKeyMulti", "GroupKey"); var ensuredUser1 = testScope.SiteCollection.RootWeb.EnsureUser(Environment.UserDomainName + "\\" + Environment.UserName); var ensuredUser2 = testScope.SiteCollection.RootWeb.EnsureUser("OFFICE\\maxime.boissonneault"); UserFieldInfo userFieldInfo = new UserFieldInfo( "TestInternalNameUser", new Guid("{5B74DD50-0D2D-4D24-95AF-0C4B8AA3F68A}"), "NameKeyUser", "DescriptionKeyUser", "GroupKey"); UserMultiFieldInfo userMultiFieldInfo = new UserMultiFieldInfo( "TestInternalNameUserMulti", new Guid("{8C662588-D54E-4905-B232-856C2239B036}"), "NameKeyUserMulti", "DescriptionKeyUserMulti", "GroupKey"); MediaFieldInfo mediaFieldInfo = new MediaFieldInfo( "TestInternalNameMedia", new Guid("{A2F070FE-FE33-44FC-9FDF-D18E74ED4D67}"), "NameKeyMedia", "DescriptionKeyMEdia", "GroupKey"); var testTermSet = new TermSetInfo(Guid.NewGuid(), "Test Term Set"); // keep Ids random because, if this test fails midway, the term // set will not be cleaned up and upon next test run we will // run into a term set and term ID conflicts. var levelOneTermA = new TermInfo(Guid.NewGuid(), "Term A", testTermSet); var levelOneTermB = new TermInfo(Guid.NewGuid(), "Term B", testTermSet); var levelTwoTermAA = new TermInfo(Guid.NewGuid(), "Term A-A", testTermSet); var levelTwoTermAB = new TermInfo(Guid.NewGuid(), "Term A-B", testTermSet); TaxonomySession session = new TaxonomySession(testScope.SiteCollection); TermStore defaultSiteCollectionTermStore = session.DefaultSiteCollectionTermStore; Group defaultSiteCollectionGroup = defaultSiteCollectionTermStore.GetSiteCollectionGroup(testScope.SiteCollection); TermSet newTermSet = defaultSiteCollectionGroup.CreateTermSet(testTermSet.Label, testTermSet.Id); Term createdTermA = newTermSet.CreateTerm(levelOneTermA.Label, Language.English.Culture.LCID, levelOneTermA.Id); Term createdTermB = newTermSet.CreateTerm(levelOneTermB.Label, Language.English.Culture.LCID, levelOneTermB.Id); Term createdTermAA = createdTermA.CreateTerm(levelTwoTermAA.Label, Language.English.Culture.LCID, levelTwoTermAA.Id); Term createdTermAB = createdTermA.CreateTerm(levelTwoTermAB.Label, Language.English.Culture.LCID, levelTwoTermAB.Id); defaultSiteCollectionTermStore.CommitAll(); TaxonomyFieldInfo taxoFieldInfo = new TaxonomyFieldInfo( "TestInternalNameTaxo", new Guid("{18CC105F-16C9-43E2-9933-37F98452C038}"), "NameKey", "DescriptionKey", "GroupKey") { TermStoreMapping = new TaxonomyContext(testTermSet) // choices limited to all terms in test term set }; TaxonomyMultiFieldInfo taxoMultiFieldInfo = new TaxonomyMultiFieldInfo( "TestInternalNameTaxoMulti", new Guid("{2F49D362-B014-41BB-9959-1000C9A7FFA0}"), "NameKeyMulti", "DescriptionKey", "GroupKey") { TermStoreMapping = new TaxonomyContext(levelOneTermA) // choices limited to children of a specific term, instead of having full term set choices }; var fieldsToEnsure = new List<BaseFieldInfo>() { integerFieldInfo, numberFieldInfo, currencyFieldInfo, boolFieldInfoBasic, boolFieldInfoDefaultTrue, boolFieldInfoDefaultFalse, dateTimeFieldInfoFormula, dateTimeFieldInfoDefault, textFieldInfo, noteFieldInfo, htmlFieldInfo, imageFieldInfo, urlFieldInfo, urlFieldInfoImage, lookupFieldInfo, lookupFieldInfoAlt, lookupMultiFieldInfo, userFieldInfo, userMultiFieldInfo, mediaFieldInfo, taxoFieldInfo, taxoMultiFieldInfo }; ListInfo lookupListInfo = new ListInfo("sometestlistpathlookup", "DynamiteTestListNameKeyLookup", "DynamiteTestListDescriptionKeyLookup"); ListInfo listInfo = new ListInfo("sometestlistpath", "DynamiteTestListNameKey", "DynamiteTestListDescriptionKey") { FieldDefinitions = fieldsToEnsure }; // Note how we need to specify SPSite for injection context - ISharePointEntityBinder's implementation // is lifetime-scoped to InstancePerSite. using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope(testScope.SiteCollection)) { var listHelper = injectionScope.Resolve<IListHelper>(); // Lookup field ListId setup SPList lookupList = listHelper.EnsureList(testScope.SiteCollection.RootWeb, lookupListInfo); lookupFieldInfo.ListId = lookupList.ID; lookupFieldInfoAlt.ListId = lookupList.ID; lookupMultiFieldInfo.ListId = lookupList.ID; // Create the looked-up items var lookupItem1 = lookupList.Items.Add(); lookupItem1["Title"] = "Test Item 1"; lookupItem1.Update(); var lookupItem2 = lookupList.Items.Add(); lookupItem2["Title"] = "Test Item 2"; lookupItem2.Update(); // Create the first test list SPList list = listHelper.EnsureList(testScope.SiteCollection.RootWeb, listInfo); list.EnableVersioning = true; list.Update(); // Create item on list var itemOnList = list.AddItem(); // Update with the field values through the SharePoint API itemOnList["Title"] = "Item under test"; itemOnList["TestInternalNameInteger"] = 555; itemOnList["TestInternalNameNumber"] = 5.5; itemOnList["TestInternalNameCurrency"] = 500.95; itemOnList["TestInternalNameBool"] = true; itemOnList["TestInternalNameBoolTrue"] = false; itemOnList["TestInternalNameBoolFalse"] = true; itemOnList["TestInternalNameDateFormula"] = new DateTime(1977, 7, 7); itemOnList["TestInternalNameDateDefault"] = new DateTime(1977, 7, 7); itemOnList["TestInternalNameText"] = "Text value"; itemOnList["TestInternalNameNote"] = "Note value"; itemOnList["TestInternalNameHtml"] = "<p class=\"some-css-class\">HTML value</p>"; itemOnList["TestInternalNameImage"] = new ImageFieldValue() { Hyperlink = "http://github.com/GSoft-SharePoint/", ImageUrl = "/_layouts/15/MyFolder/MyImage.png" }; itemOnList["TestInternalNameUrl"] = new SPFieldUrlValue() { Url = "http://github.com/GSoft-SharePoint/", Description = "patate!" }; itemOnList["TestInternalNameUrlImg"] = new SPFieldUrlValue() { Url = "http://github.com/GSoft-SharePoint/", Description = "patate!" }; itemOnList["TestInternalNameLookup"] = new SPFieldLookupValue(1, "Test Item 1"); itemOnList["TestInternalNameLookupAlt"] = new SPFieldLookupValue(2, "2"); itemOnList["TestInternalNameLookupM"] = new SPFieldLookupValueCollection() { new SPFieldLookupValue(1, "Test Item 1"), new SPFieldLookupValue(2, "Test Item 2") }; itemOnList["TestInternalNameUser"] = new SPFieldUserValue(testScope.SiteCollection.RootWeb, ensuredUser1.ID, ensuredUser1.Name); itemOnList["TestInternalNameUserMulti"] = new SPFieldUserValueCollection() { new SPFieldUserValue(testScope.SiteCollection.RootWeb, ensuredUser1.ID, ensuredUser1.Name), new SPFieldUserValue(testScope.SiteCollection.RootWeb, ensuredUser2.ID, ensuredUser2.Name) }; itemOnList["TestInternalNameMedia"] = new MediaFieldValue() { Title = "Some media file title", MediaSource = "/sites/test/SiteAssets/01_01_ASP.NET%20MVC%203%20Fundamentals%20Intro%20-%20Overview.asf", AutoPlay = true, Loop = true, PreviewImageSource = "/_layouts/15/Images/logo.png" }; var taxonomyField = (TaxonomyField)itemOnList.Fields.GetFieldByInternalName("TestInternalNameTaxo"); taxonomyField.SetFieldValue(itemOnList, createdTermB); var taxonomyMultiField = (TaxonomyField)itemOnList.Fields.GetFieldByInternalName("TestInternalNameTaxoMulti"); taxonomyMultiField.SetFieldValue(itemOnList, new[] { createdTermAA, createdTermAB }); itemOnList.Update(); var entityBinder = injectionScope.Resolve<ISharePointEntityBinder>(); var entityMappedFromSingleItem = new TestItemEntityWithLookups(); var entityMappedFromItemVersion = new TestItemEntityWithLookups(); // Act // Map from SPListItem entityBinder.ToEntity<TestItemEntityWithLookups>(entityMappedFromSingleItem, itemOnList); // Map from SPListItemVersion entityBinder.ToEntity<TestItemEntityWithLookups>(entityMappedFromItemVersion, itemOnList.Versions[0]); // Map from DataRow/SPListItemCollection var entitiesMappedFromItemCollection = entityBinder.Get<TestItemEntity>(list.Items); // Assert // #1 Validate straight single list item to entity mappings Assert.AreEqual(555, entityMappedFromSingleItem.IntegerProperty); Assert.AreEqual(5.5, entityMappedFromSingleItem.DoubleProperty); Assert.AreEqual(500.95, entityMappedFromSingleItem.CurrencyProperty); Assert.IsTrue(entityMappedFromSingleItem.BoolProperty.Value); Assert.IsFalse(entityMappedFromSingleItem.BoolDefaultTrueProperty); Assert.IsTrue(entityMappedFromSingleItem.BoolDefaultFalseProperty); Assert.AreEqual(new DateTime(1977, 7, 7), entityMappedFromSingleItem.DateTimeFormulaProperty); Assert.AreEqual(new DateTime(1977, 7, 7), entityMappedFromSingleItem.DateTimeProperty); Assert.AreEqual("Text value", entityMappedFromSingleItem.TextProperty); Assert.AreEqual("Note value", entityMappedFromSingleItem.NoteProperty); Assert.AreEqual("<p class=\"some-css-class\">HTML value</p>", entityMappedFromSingleItem.HtmlProperty); Assert.IsNotNull(entityMappedFromSingleItem.ImageProperty); Assert.AreEqual("http://github.com/GSoft-SharePoint/", entityMappedFromSingleItem.ImageProperty.Hyperlink); Assert.AreEqual("/_layouts/15/MyFolder/MyImage.png", entityMappedFromSingleItem.ImageProperty.ImageUrl); Assert.AreEqual("http://github.com/GSoft-SharePoint/", entityMappedFromSingleItem.UrlProperty.Url); Assert.AreEqual("patate!", entityMappedFromSingleItem.UrlProperty.Description); Assert.AreEqual("http://github.com/GSoft-SharePoint/", entityMappedFromSingleItem.UrlImageProperty.Url); Assert.AreEqual("patate!", entityMappedFromSingleItem.UrlProperty.Description); Assert.AreEqual(1, entityMappedFromSingleItem.LookupProperty.Id); Assert.AreEqual("Test Item 1", entityMappedFromSingleItem.LookupProperty.Value); Assert.AreEqual(2, entityMappedFromSingleItem.LookupAltProperty.Id); Assert.AreEqual("2", entityMappedFromSingleItem.LookupAltProperty.Value); // ShowField/LookupField is ID Assert.AreEqual(1, entityMappedFromSingleItem.LookupMultiProperty[0].Id); Assert.AreEqual("Test Item 1", entityMappedFromSingleItem.LookupMultiProperty[0].Value); Assert.AreEqual(2, entityMappedFromSingleItem.LookupMultiProperty[1].Id); Assert.AreEqual("Test Item 2", entityMappedFromSingleItem.LookupMultiProperty[1].Value); Assert.AreEqual(ensuredUser1.Name, entityMappedFromSingleItem.UserProperty.DisplayName); Assert.AreEqual(ensuredUser1.Name, entityMappedFromSingleItem.UserMultiProperty[0].DisplayName); Assert.AreEqual("Maxime Boissonneault", entityMappedFromSingleItem.UserMultiProperty[1].DisplayName); Assert.AreEqual("Some media file title", entityMappedFromSingleItem.MediaProperty.Title); Assert.AreEqual(HttpUtility.UrlDecode("/sites/test/SiteAssets/01_01_ASP.NET%20MVC%203%20Fundamentals%20Intro%20-%20Overview.asf"), entityMappedFromSingleItem.MediaProperty.Url); Assert.IsTrue(entityMappedFromSingleItem.MediaProperty.IsAutoPlay); Assert.IsTrue(entityMappedFromSingleItem.MediaProperty.IsLoop); Assert.AreEqual("/_layouts/15/Images/logo.png", entityMappedFromSingleItem.MediaProperty.PreviewImageUrl); Assert.AreEqual(levelOneTermB.Id, entityMappedFromSingleItem.TaxonomyProperty.Id); Assert.AreEqual(levelOneTermB.Label, entityMappedFromSingleItem.TaxonomyProperty.Label); Assert.AreEqual(levelTwoTermAA.Id, entityMappedFromSingleItem.TaxonomyMultiProperty[0].Id); Assert.AreEqual(levelTwoTermAA.Label, entityMappedFromSingleItem.TaxonomyMultiProperty[0].Label); Assert.AreEqual(levelTwoTermAB.Id, entityMappedFromSingleItem.TaxonomyMultiProperty[1].Id); Assert.AreEqual(levelTwoTermAB.Label, entityMappedFromSingleItem.TaxonomyMultiProperty[1].Label); // #2 Validate list item version mappings Assert.AreEqual(555, entityMappedFromItemVersion.IntegerProperty); Assert.AreEqual(5.5, entityMappedFromItemVersion.DoubleProperty); Assert.AreEqual(500.95, entityMappedFromItemVersion.CurrencyProperty); Assert.IsTrue(entityMappedFromItemVersion.BoolProperty.Value); Assert.IsFalse(entityMappedFromItemVersion.BoolDefaultTrueProperty); Assert.IsTrue(entityMappedFromItemVersion.BoolDefaultFalseProperty); Assert.AreEqual(new DateTime(1977, 7, 7), entityMappedFromItemVersion.DateTimeFormulaProperty); Assert.AreEqual(new DateTime(1977, 7, 7), entityMappedFromItemVersion.DateTimeProperty); Assert.AreEqual("Text value", entityMappedFromItemVersion.TextProperty); Assert.AreEqual("Note value", entityMappedFromItemVersion.NoteProperty); Assert.AreEqual("<p class=\"some-css-class\">HTML value</p>", entityMappedFromItemVersion.HtmlProperty); Assert.IsNotNull(entityMappedFromItemVersion.ImageProperty); Assert.AreEqual("http://github.com/GSoft-SharePoint/", entityMappedFromItemVersion.ImageProperty.Hyperlink); Assert.AreEqual("/_layouts/15/MyFolder/MyImage.png", entityMappedFromItemVersion.ImageProperty.ImageUrl); Assert.AreEqual("http://github.com/GSoft-SharePoint/", entityMappedFromItemVersion.UrlProperty.Url); Assert.AreEqual("patate!", entityMappedFromItemVersion.UrlProperty.Description); Assert.AreEqual("http://github.com/GSoft-SharePoint/", entityMappedFromItemVersion.UrlImageProperty.Url); Assert.AreEqual("patate!", entityMappedFromItemVersion.UrlProperty.Description); Assert.AreEqual(1, entityMappedFromItemVersion.LookupProperty.Id); Assert.AreEqual("Test Item 1", entityMappedFromItemVersion.LookupProperty.Value); Assert.AreEqual(2, entityMappedFromItemVersion.LookupAltProperty.Id); Assert.AreEqual("2", entityMappedFromItemVersion.LookupAltProperty.Value); // ShowField/LookupField is ID Assert.AreEqual(1, entityMappedFromItemVersion.LookupMultiProperty[0].Id); Assert.AreEqual("Test Item 1", entityMappedFromItemVersion.LookupMultiProperty[0].Value); Assert.AreEqual(2, entityMappedFromItemVersion.LookupMultiProperty[1].Id); Assert.AreEqual("Test Item 2", entityMappedFromItemVersion.LookupMultiProperty[1].Value); Assert.AreEqual(ensuredUser1.Name, entityMappedFromItemVersion.UserProperty.DisplayName); Assert.AreEqual(ensuredUser1.Name, entityMappedFromItemVersion.UserMultiProperty[0].DisplayName); Assert.AreEqual("Maxime Boissonneault", entityMappedFromItemVersion.UserMultiProperty[1].DisplayName); Assert.AreEqual("Some media file title", entityMappedFromItemVersion.MediaProperty.Title); Assert.AreEqual(HttpUtility.UrlDecode("/sites/test/SiteAssets/01_01_ASP.NET%20MVC%203%20Fundamentals%20Intro%20-%20Overview.asf"), entityMappedFromItemVersion.MediaProperty.Url); Assert.IsTrue(entityMappedFromItemVersion.MediaProperty.IsAutoPlay); Assert.IsTrue(entityMappedFromItemVersion.MediaProperty.IsLoop); Assert.AreEqual("/_layouts/15/Images/logo.png", entityMappedFromItemVersion.MediaProperty.PreviewImageUrl); Assert.AreEqual(levelOneTermB.Id, entityMappedFromItemVersion.TaxonomyProperty.Id); Assert.AreEqual(levelOneTermB.Label, entityMappedFromItemVersion.TaxonomyProperty.Label); Assert.AreEqual(levelTwoTermAA.Id, entityMappedFromItemVersion.TaxonomyMultiProperty[0].Id); Assert.AreEqual(levelTwoTermAA.Label, entityMappedFromItemVersion.TaxonomyMultiProperty[0].Label); Assert.AreEqual(levelTwoTermAB.Id, entityMappedFromItemVersion.TaxonomyMultiProperty[1].Id); Assert.AreEqual(levelTwoTermAB.Label, entityMappedFromItemVersion.TaxonomyMultiProperty[1].Label); // #3 Validate straight list item collection to entity mappings Assert.AreEqual(555, entitiesMappedFromItemCollection[0].IntegerProperty); Assert.AreEqual(5.5, entitiesMappedFromItemCollection[0].DoubleProperty); Assert.AreEqual(500.95, entitiesMappedFromItemCollection[0].CurrencyProperty); Assert.IsTrue(entitiesMappedFromItemCollection[0].BoolProperty.Value); Assert.IsFalse(entitiesMappedFromItemCollection[0].BoolDefaultTrueProperty); Assert.IsTrue(entitiesMappedFromItemCollection[0].BoolDefaultFalseProperty); Assert.AreEqual(new DateTime(1977, 7, 7), entitiesMappedFromItemCollection[0].DateTimeFormulaProperty); Assert.AreEqual(new DateTime(1977, 7, 7), entitiesMappedFromItemCollection[0].DateTimeProperty); Assert.AreEqual("Text value", entitiesMappedFromItemCollection[0].TextProperty); Assert.AreEqual("Note value", entitiesMappedFromItemCollection[0].NoteProperty); Assert.AreEqual("<p class=\"some-css-class\">HTML value</p>", entitiesMappedFromItemCollection[0].HtmlProperty); Assert.IsNotNull(entitiesMappedFromItemCollection[0].ImageProperty); Assert.AreEqual("http://github.com/GSoft-SharePoint/", entitiesMappedFromItemCollection[0].ImageProperty.Hyperlink); Assert.AreEqual("/_layouts/15/MyFolder/MyImage.png", entitiesMappedFromItemCollection[0].ImageProperty.ImageUrl); Assert.AreEqual("http://github.com/GSoft-SharePoint/", entitiesMappedFromItemCollection[0].UrlProperty.Url); Assert.AreEqual("patate!", entitiesMappedFromItemCollection[0].UrlProperty.Description); Assert.AreEqual("http://github.com/GSoft-SharePoint/", entitiesMappedFromItemCollection[0].UrlImageProperty.Url); Assert.AreEqual("patate!", entitiesMappedFromItemCollection[0].UrlImageProperty.Description); // No lookups or User fields because DataRow formatting screws up lookup values (we lose the lookup IDs) Assert.AreEqual("Some media file title", entitiesMappedFromItemCollection[0].MediaProperty.Title); Assert.AreEqual(HttpUtility.UrlDecode("/sites/test/SiteAssets/01_01_ASP.NET%20MVC%203%20Fundamentals%20Intro%20-%20Overview.asf"), entitiesMappedFromItemCollection[0].MediaProperty.Url); Assert.IsTrue(entitiesMappedFromItemCollection[0].MediaProperty.IsAutoPlay); Assert.IsTrue(entitiesMappedFromItemCollection[0].MediaProperty.IsLoop); Assert.AreEqual("/_layouts/15/Images/logo.png", entitiesMappedFromItemCollection[0].MediaProperty.PreviewImageUrl); Assert.AreEqual(levelOneTermB.Id, entitiesMappedFromItemCollection[0].TaxonomyProperty.Id); Assert.AreEqual(levelOneTermB.Label, entitiesMappedFromItemCollection[0].TaxonomyProperty.Label); Assert.AreEqual(levelTwoTermAA.Id, entitiesMappedFromItemCollection[0].TaxonomyMultiProperty[0].Id); Assert.AreEqual(levelTwoTermAA.Label, entitiesMappedFromItemCollection[0].TaxonomyMultiProperty[0].Label); Assert.AreEqual(levelTwoTermAB.Id, entitiesMappedFromItemCollection[0].TaxonomyMultiProperty[1].Id); Assert.AreEqual(levelTwoTermAB.Label, entitiesMappedFromItemCollection[0].TaxonomyMultiProperty[1].Label); } // Cleanup term set so that we don't pollute the metadata store newTermSet.Delete(); defaultSiteCollectionTermStore.CommitAll(); } }
public void FromEntity_WhenMappingToNewListItem_ShouldInitializeListItemFieldValues() { using (var testScope = SiteTestScope.BlankSite()) { // Arrange IntegerFieldInfo integerFieldInfo = new IntegerFieldInfo( "TestInternalNameInteger", new Guid("{12E262D0-C7C4-4671-A266-064CDBD3905A}"), "NameKeyInt", "DescriptionKeyInt", "GroupKey"); NumberFieldInfo numberFieldInfo = new NumberFieldInfo( "TestInternalNameNumber", new Guid("{5DD4EE0F-8498-4033-97D0-317A24988786}"), "NameKeyNumber", "DescriptionKeyNumber", "GroupKey"); CurrencyFieldInfo currencyFieldInfo = new CurrencyFieldInfo( "TestInternalNameCurrency", new Guid("{9E9963F6-1EE6-46FB-9599-783BBF4D6249}"), "NameKeyCurrency", "DescriptionKeyCurrency", "GroupKey"); BooleanFieldInfo boolFieldInfoBasic = new BooleanFieldInfo( "TestInternalNameBool", new Guid("{F556AB6B-9E51-43E2-99C9-4A4E551A4BEF}"), "NameKeyBool", "DescriptionKeyBool", "GroupKey"); BooleanFieldInfo boolFieldInfoDefaultTrue = new BooleanFieldInfo( "TestInternalNameBoolTrue", new Guid("{0D0289AD-C5FB-495B-96C6-48CC46737D08}"), "NameKeyBoolTrue", "DescriptionKeyBoolTrue", "GroupKey") { DefaultValue = true }; BooleanFieldInfo boolFieldInfoDefaultFalse = new BooleanFieldInfo( "TestInternalNameBoolFalse", new Guid("{628181BD-9B0B-4B7E-934F-1CF1796EA4E4}"), "NameKeyBoolFalse", "DescriptionKeyBoolFalse", "GroupKey") { DefaultValue = false }; DateTimeFieldInfo dateTimeFieldInfoFormula = new DateTimeFieldInfo( "TestInternalNameDateFormula", new Guid("{D23EAD73-9E18-46DB-A426-41B2D47F696C}"), "NameKeyDateTimeFormula", "DescriptionKeyDateTimeFormula", "GroupKey") { DefaultFormula = "=[Today]" }; DateTimeFieldInfo dateTimeFieldInfo = new DateTimeFieldInfo( "TestInternalNameDateDefault", new Guid("{016BF8D9-CEDC-4BF4-BA21-AC6A8F174AD5}"), "NameKeyDateTimeDefault", "DescriptionKeyDateTimeDefault", "GroupKey"); TextFieldInfo textFieldInfo = new TextFieldInfo( "TestInternalNameText", new Guid("{0C58B4A1-B360-47FE-84F7-4D8F58AE80F6}"), "NameKey", "DescriptionKey", "GroupKey"); NoteFieldInfo noteFieldInfo = new NoteFieldInfo( "TestInternalNameNote", new Guid("{E315BB24-19C3-4F2E-AABC-9DE5EFC3D5C2}"), "NameKeyAlt", "DescriptionKeyAlt", "GroupKey"); HtmlFieldInfo htmlFieldInfo = new HtmlFieldInfo( "TestInternalNameHtml", new Guid("{D16958E7-CF9A-4C38-A8BB-99FC03BFD913}"), "NameKeyAlt", "DescriptionKeyAlt", "GroupKey"); ImageFieldInfo imageFieldInfo = new ImageFieldInfo( "TestInternalNameImage", new Guid("{6C5B9E77-B621-43AA-BFBF-B333093EFCAE}"), "NameKeyImage", "DescriptionKeyImage", "GroupKey"); UrlFieldInfo urlFieldInfo = new UrlFieldInfo( "TestInternalNameUrl", new Guid("{208F904C-5A1C-4E22-9A79-70B294FABFDA}"), "NameKeyUrl", "DescriptionKeyUrl", "GroupKey"); UrlFieldInfo urlFieldInfoImage = new UrlFieldInfo( "TestInternalNameUrlImg", new Guid("{96D22CFF-5B40-4675-B632-28567792E11B}"), "NameKeyUrlImg", "DescriptionKeyUrlImg", "GroupKey") { Format = UrlFieldFormat.Image }; LookupFieldInfo lookupFieldInfo = new LookupFieldInfo( "TestInternalNameLookup", new Guid("{62F8127C-4A8C-4217-8BD8-C6712753AFCE}"), "NameKey", "DescriptionKey", "GroupKey"); LookupFieldInfo lookupFieldInfoAlt = new LookupFieldInfo( "TestInternalNameLookupAlt", new Guid("{1F05DFFA-6396-4AEF-AD23-72217206D35E}"), "NameKey", "DescriptionKey", "GroupKey") { ShowField = "ID" }; LookupMultiFieldInfo lookupMultiFieldInfo = new LookupMultiFieldInfo( "TestInternalNameLookupM", new Guid("{2C9D4C0E-21EB-4742-8C6C-4C30DCD08A05}"), "NameKeyMulti", "DescriptionKeyMulti", "GroupKey"); var ensuredUser1 = testScope.SiteCollection.RootWeb.EnsureUser(Environment.UserDomainName + "\\" + Environment.UserName); var ensuredUser2 = testScope.SiteCollection.RootWeb.EnsureUser("OFFICE\\maxime.boissonneault"); UserFieldInfo userFieldInfo = new UserFieldInfo( "TestInternalNameUser", new Guid("{5B74DD50-0D2D-4D24-95AF-0C4B8AA3F68A}"), "NameKeyUser", "DescriptionKeyUser", "GroupKey"); UserMultiFieldInfo userMultiFieldInfo = new UserMultiFieldInfo( "TestInternalNameUserMulti", new Guid("{8C662588-D54E-4905-B232-856C2239B036}"), "NameKeyUserMulti", "DescriptionKeyUserMulti", "GroupKey"); MediaFieldInfo mediaFieldInfo = new MediaFieldInfo( "TestInternalNameMedia", new Guid("{A2F070FE-FE33-44FC-9FDF-D18E74ED4D67}"), "NameKeyMedia", "DescriptionKeyMEdia", "GroupKey"); var testTermSet = new TermSetInfo(Guid.NewGuid(), "Test Term Set"); // keep Ids random because, if this test fails midway, the term // set will not be cleaned up and upon next test run we will // run into a term set and term ID conflicts. var levelOneTermA = new TermInfo(Guid.NewGuid(), "Term A", testTermSet); var levelOneTermB = new TermInfo(Guid.NewGuid(), "Term B", testTermSet); var levelTwoTermAA = new TermInfo(Guid.NewGuid(), "Term A-A", testTermSet); var levelTwoTermAB = new TermInfo(Guid.NewGuid(), "Term A-B", testTermSet); TaxonomySession session = new TaxonomySession(testScope.SiteCollection); TermStore defaultSiteCollectionTermStore = session.DefaultSiteCollectionTermStore; Group defaultSiteCollectionGroup = defaultSiteCollectionTermStore.GetSiteCollectionGroup(testScope.SiteCollection); TermSet newTermSet = defaultSiteCollectionGroup.CreateTermSet(testTermSet.Label, testTermSet.Id); Term createdTermA = newTermSet.CreateTerm(levelOneTermA.Label, Language.English.Culture.LCID, levelOneTermA.Id); Term createdTermB = newTermSet.CreateTerm(levelOneTermB.Label, Language.English.Culture.LCID, levelOneTermB.Id); Term createdTermAA = createdTermA.CreateTerm(levelTwoTermAA.Label, Language.English.Culture.LCID, levelTwoTermAA.Id); Term createdTermAB = createdTermA.CreateTerm(levelTwoTermAB.Label, Language.English.Culture.LCID, levelTwoTermAB.Id); defaultSiteCollectionTermStore.CommitAll(); TaxonomyFieldInfo taxoFieldInfo = new TaxonomyFieldInfo( "TestInternalNameTaxo", new Guid("{18CC105F-16C9-43E2-9933-37F98452C038}"), "NameKey", "DescriptionKey", "GroupKey") { TermStoreMapping = new TaxonomyContext(testTermSet) // choices limited to all terms in test term set }; TaxonomyMultiFieldInfo taxoMultiFieldInfo = new TaxonomyMultiFieldInfo( "TestInternalNameTaxoMulti", new Guid("{2F49D362-B014-41BB-9959-1000C9A7FFA0}"), "NameKeyMulti", "DescriptionKey", "GroupKey") { TermStoreMapping = new TaxonomyContext(levelOneTermA) // choices limited to children of a specific term, instead of having full term set choices }; var fieldsToEnsure = new List<BaseFieldInfo>() { integerFieldInfo, numberFieldInfo, currencyFieldInfo, boolFieldInfoBasic, boolFieldInfoDefaultTrue, boolFieldInfoDefaultFalse, dateTimeFieldInfoFormula, dateTimeFieldInfo, textFieldInfo, noteFieldInfo, htmlFieldInfo, imageFieldInfo, urlFieldInfo, urlFieldInfoImage, lookupFieldInfo, lookupFieldInfoAlt, lookupMultiFieldInfo, userFieldInfo, userMultiFieldInfo, mediaFieldInfo, taxoFieldInfo, taxoMultiFieldInfo }; ListInfo lookupListInfo = new ListInfo("sometestlistpathlookup", "DynamiteTestListNameKeyLookup", "DynamiteTestListDescriptionKeyLookup"); ListInfo listInfo = new ListInfo("sometestlistpath", "DynamiteTestListNameKey", "DynamiteTestListDescriptionKey") { FieldDefinitions = fieldsToEnsure }; // Note how we need to specify SPSite for injection context - ISharePointEntityBinder's implementation // is lifetime-scoped to InstancePerSite. using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope(testScope.SiteCollection)) { var listHelper = injectionScope.Resolve<IListHelper>(); // Lookup field ListId setup SPList lookupList = listHelper.EnsureList(testScope.SiteCollection.RootWeb, lookupListInfo); lookupFieldInfo.ListId = lookupList.ID; lookupFieldInfoAlt.ListId = lookupList.ID; lookupMultiFieldInfo.ListId = lookupList.ID; // Create the looked-up items var lookupItem1 = lookupList.Items.Add(); lookupItem1["Title"] = "Test Item 1"; lookupItem1.Update(); var lookupItem2 = lookupList.Items.Add(); lookupItem2["Title"] = "Test Item 2"; lookupItem2.Update(); // Create the first test list SPList list = listHelper.EnsureList(testScope.SiteCollection.RootWeb, listInfo); // Initialize the entity object with all the property values we want to apply on the new list item var entityBinder = injectionScope.Resolve<ISharePointEntityBinder>(); var entity = new TestItemEntityWithLookups() { IntegerProperty = 555, DoubleProperty = 5.5, CurrencyProperty = 500.95, BoolProperty = true, BoolDefaultTrueProperty = false, BoolDefaultFalseProperty = true, DateTimeFormulaProperty = new DateTime(2005, 10, 21), DateTimeProperty = new DateTime(2005, 10, 21), TextProperty = "Text value", NoteProperty = "Note value", HtmlProperty = "<p class=\"some-css-class\">HTML value</p>", ImageProperty = new ImageValue() { Hyperlink = "http://github.com/GSoft-SharePoint/", ImageUrl = "/_layouts/15/MyFolder/MyImage.png" }, UrlProperty = new UrlValue() { Url = "http://github.com/GSoft-SharePoint/", Description = "patate!" }, UrlImageProperty = new UrlValue() { Url = "http://github.com/GSoft-SharePoint/", Description = "patate!" }, LookupProperty = new LookupValue(1, "Test Item 1"), LookupAltProperty = new LookupValue(2, "2"), LookupMultiProperty = new LookupValueCollection() { new LookupValue(1, "Test Item 1"), new LookupValue(2, "Test Item 2") }, UserProperty = new UserValue(ensuredUser1), UserMultiProperty = new UserValueCollection() { new UserValue(ensuredUser1), new UserValue(ensuredUser2) }, MediaProperty = new MediaValue() { Title = "Some media file title", Url = "/sites/test/SiteAssets/01_01_ASP.NET%20MVC%203%20Fundamentals%20Intro%20-%20Overview.asf", IsAutoPlay = true, IsLoop = true, PreviewImageUrl = "/_layouts/15/Images/logo.png" }, TaxonomyProperty = new TaxonomyValue(createdTermB), TaxonomyMultiProperty = new TaxonomyValueCollection( new List<TaxonomyValue>() { new TaxonomyValue(createdTermAA), new TaxonomyValue(createdTermAB) }) }; // Act (create the list item and bind the Entity's values to it) var itemOnList = list.AddItem(); entityBinder.FromEntity<TestItemEntityWithLookups>(entity, itemOnList); itemOnList.Update(); // Assert // #1: validate ListItem field values on the mapped item object Assert.AreEqual(555, itemOnList["TestInternalNameInteger"]); Assert.AreEqual(5.5, itemOnList["TestInternalNameNumber"]); Assert.AreEqual(500.95, itemOnList["TestInternalNameCurrency"]); Assert.IsTrue((bool)itemOnList["TestInternalNameBool"]); Assert.IsFalse((bool)itemOnList["TestInternalNameBoolTrue"]); Assert.IsTrue((bool)itemOnList["TestInternalNameBoolFalse"]); Assert.AreEqual(new DateTime(2005, 10, 21), itemOnList["TestInternalNameDateFormula"]); Assert.AreEqual(new DateTime(2005, 10, 21), itemOnList["TestInternalNameDateDefault"]); Assert.AreEqual("Text value", itemOnList["TestInternalNameText"]); Assert.AreEqual("Note value", itemOnList["TestInternalNameNote"]); Assert.AreEqual("<p class=\"some-css-class\">HTML value</p>", itemOnList["TestInternalNameHtml"]); var imageFieldVal = (ImageFieldValue)itemOnList["TestInternalNameImage"]; Assert.IsNotNull(imageFieldVal); Assert.AreEqual("http://github.com/GSoft-SharePoint/", imageFieldVal.Hyperlink); Assert.AreEqual("/_layouts/15/MyFolder/MyImage.png", imageFieldVal.ImageUrl); var urlFieldVal = new SPFieldUrlValue(itemOnList["TestInternalNameUrl"].ToString()); Assert.AreEqual("http://github.com/GSoft-SharePoint/", urlFieldVal.Url); Assert.AreEqual("patate!", urlFieldVal.Description); var urlImageFieldVal = new SPFieldUrlValue(itemOnList["TestInternalNameUrlImg"].ToString()); Assert.AreEqual("http://github.com/GSoft-SharePoint/", urlImageFieldVal.Url); Assert.AreEqual("patate!", urlImageFieldVal.Description); var lookupFieldVal = new SPFieldLookupValue(itemOnList["TestInternalNameLookup"].ToString()); Assert.AreEqual(1, lookupFieldVal.LookupId); Assert.AreEqual("Test Item 1", lookupFieldVal.LookupValue); var lookupAltFieldVal = new SPFieldLookupValue(itemOnList["TestInternalNameLookupAlt"].ToString()); Assert.AreEqual(2, lookupAltFieldVal.LookupId); Assert.AreEqual("2", lookupAltFieldVal.LookupValue); // ShowField/LookupField is ID var lookupMultiFieldVal = new SPFieldLookupValueCollection(itemOnList["TestInternalNameLookupM"].ToString()); Assert.AreEqual(1, lookupMultiFieldVal[0].LookupId); Assert.AreEqual("Test Item 1", lookupMultiFieldVal[0].LookupValue); Assert.AreEqual(2, lookupMultiFieldVal[1].LookupId); Assert.AreEqual("Test Item 2", lookupMultiFieldVal[1].LookupValue); var userFieldVal = new SPFieldUserValue(testScope.SiteCollection.RootWeb, itemOnList["TestInternalNameUser"].ToString()); Assert.AreEqual(ensuredUser1.Name, userFieldVal.User.Name); // TODO: Make this work with ListItem converters var userMultiFieldVal = new SPFieldUserValueCollection(testScope.SiteCollection.RootWeb, itemOnList["TestInternalNameUserMulti"].ToString()); Assert.AreEqual(ensuredUser1.Name, userMultiFieldVal[0].User.Name); Assert.AreEqual("Maxime Boissonneault", userMultiFieldVal[1].User.Name); var mediaFieldVal = MediaFieldValue.FromString(itemOnList["TestInternalNameMedia"].ToString()); Assert.AreEqual("Some media file title", mediaFieldVal.Title); Assert.AreEqual(HttpUtility.UrlDecode("/sites/test/SiteAssets/01_01_ASP.NET%20MVC%203%20Fundamentals%20Intro%20-%20Overview.asf"), mediaFieldVal.MediaSource); Assert.IsTrue(mediaFieldVal.AutoPlay); Assert.IsTrue(mediaFieldVal.Loop); Assert.AreEqual("/_layouts/15/Images/logo.png", mediaFieldVal.PreviewImageSource); var taxoFieldValue = (TaxonomyFieldValue)itemOnList["TestInternalNameTaxo"]; Assert.AreNotEqual(-1, taxoFieldValue.WssId); Assert.AreEqual(levelOneTermB.Id, new Guid(taxoFieldValue.TermGuid)); Assert.AreEqual(levelOneTermB.Label, taxoFieldValue.Label); var taxoFieldValueMulti = (TaxonomyFieldValueCollection)itemOnList["TestInternalNameTaxoMulti"]; Assert.AreNotEqual(-1, taxoFieldValueMulti[0].WssId); Assert.AreEqual(levelTwoTermAA.Id, new Guid(taxoFieldValueMulti[0].TermGuid)); Assert.AreEqual(levelTwoTermAA.Label, taxoFieldValueMulti[0].Label); Assert.AreNotEqual(-1, taxoFieldValueMulti[1].WssId); Assert.AreEqual(levelTwoTermAB.Id, new Guid(taxoFieldValueMulti[1].TermGuid)); Assert.AreEqual(levelTwoTermAB.Label, taxoFieldValueMulti[1].Label); // #2: validate ListItem field values on the re-fetched list item var refetchedItemOnList = list.GetItemById(itemOnList.ID); Assert.AreEqual(555, refetchedItemOnList["TestInternalNameInteger"]); Assert.AreEqual(5.5, refetchedItemOnList["TestInternalNameNumber"]); Assert.AreEqual(500.95, refetchedItemOnList["TestInternalNameCurrency"]); Assert.IsTrue((bool)refetchedItemOnList["TestInternalNameBool"]); Assert.IsFalse((bool)refetchedItemOnList["TestInternalNameBoolTrue"]); Assert.IsTrue((bool)refetchedItemOnList["TestInternalNameBoolFalse"]); Assert.AreEqual(new DateTime(2005, 10, 21), refetchedItemOnList["TestInternalNameDateFormula"]); Assert.AreEqual(new DateTime(2005, 10, 21), refetchedItemOnList["TestInternalNameDateDefault"]); Assert.AreEqual("Text value", refetchedItemOnList["TestInternalNameText"]); Assert.AreEqual("Note value", refetchedItemOnList["TestInternalNameNote"]); Assert.AreEqual("<p class=\"some-css-class\">HTML value</p>", refetchedItemOnList["TestInternalNameHtml"]); imageFieldVal = (ImageFieldValue)refetchedItemOnList["TestInternalNameImage"]; Assert.IsNotNull(imageFieldVal); Assert.AreEqual("http://github.com/GSoft-SharePoint/", imageFieldVal.Hyperlink); Assert.AreEqual("/_layouts/15/MyFolder/MyImage.png", imageFieldVal.ImageUrl); urlFieldVal = new SPFieldUrlValue(refetchedItemOnList["TestInternalNameUrl"].ToString()); Assert.AreEqual("http://github.com/GSoft-SharePoint/", urlFieldVal.Url); Assert.AreEqual("patate!", urlFieldVal.Description); // proper Url description will never be set for Format=Hyperlink urlImageFieldVal = new SPFieldUrlValue(refetchedItemOnList["TestInternalNameUrlImg"].ToString()); Assert.AreEqual("http://github.com/GSoft-SharePoint/", urlImageFieldVal.Url); Assert.AreEqual("patate!", urlImageFieldVal.Description); // proper Url description will never be set for Format=Image either lookupFieldVal = new SPFieldLookupValue(refetchedItemOnList["TestInternalNameLookup"].ToString()); Assert.AreEqual(1, lookupFieldVal.LookupId); Assert.AreEqual("Test Item 1", lookupFieldVal.LookupValue); lookupAltFieldVal = new SPFieldLookupValue(refetchedItemOnList["TestInternalNameLookupAlt"].ToString()); Assert.AreEqual(2, lookupAltFieldVal.LookupId); Assert.AreEqual("2", lookupAltFieldVal.LookupValue); // ShowField/LookupField is ID lookupMultiFieldVal = new SPFieldLookupValueCollection(refetchedItemOnList["TestInternalNameLookupM"].ToString()); Assert.AreEqual(1, lookupMultiFieldVal[0].LookupId); Assert.AreEqual("Test Item 1", lookupMultiFieldVal[0].LookupValue); Assert.AreEqual(2, lookupMultiFieldVal[1].LookupId); Assert.AreEqual("Test Item 2", lookupMultiFieldVal[1].LookupValue); userFieldVal = new SPFieldUserValue(testScope.SiteCollection.RootWeb, refetchedItemOnList["TestInternalNameUser"].ToString()); Assert.AreEqual(ensuredUser1.Name, userFieldVal.User.Name); userMultiFieldVal = new SPFieldUserValueCollection(testScope.SiteCollection.RootWeb, refetchedItemOnList["TestInternalNameUserMulti"].ToString()); Assert.AreEqual(ensuredUser1.Name, userMultiFieldVal[0].User.Name); Assert.AreEqual("Maxime Boissonneault", userMultiFieldVal[1].User.Name); mediaFieldVal = MediaFieldValue.FromString(refetchedItemOnList["TestInternalNameMedia"].ToString()); Assert.AreEqual("Some media file title", mediaFieldVal.Title); Assert.AreEqual(HttpUtility.UrlDecode("/sites/test/SiteAssets/01_01_ASP.NET%20MVC%203%20Fundamentals%20Intro%20-%20Overview.asf"), mediaFieldVal.MediaSource); Assert.IsTrue(mediaFieldVal.AutoPlay); Assert.IsTrue(mediaFieldVal.Loop); Assert.AreEqual("/_layouts/15/Images/logo.png", mediaFieldVal.PreviewImageSource); taxoFieldValue = (TaxonomyFieldValue)refetchedItemOnList["TestInternalNameTaxo"]; Assert.AreNotEqual(-1, taxoFieldValue.WssId); Assert.AreEqual(levelOneTermB.Id, new Guid(taxoFieldValue.TermGuid)); Assert.AreEqual(levelOneTermB.Label, taxoFieldValue.Label); taxoFieldValueMulti = (TaxonomyFieldValueCollection)refetchedItemOnList["TestInternalNameTaxoMulti"]; Assert.AreNotEqual(-1, taxoFieldValueMulti[0].WssId); Assert.AreEqual(levelTwoTermAA.Id, new Guid(taxoFieldValueMulti[0].TermGuid)); Assert.AreEqual(levelTwoTermAA.Label, taxoFieldValueMulti[0].Label); Assert.AreNotEqual(-1, taxoFieldValueMulti[1].WssId); Assert.AreEqual(levelTwoTermAB.Id, new Guid(taxoFieldValueMulti[1].TermGuid)); Assert.AreEqual(levelTwoTermAB.Label, taxoFieldValueMulti[1].Label); } // Cleanup term set so that we don't pollute the metadata store newTermSet.Delete(); defaultSiteCollectionTermStore.CommitAll(); } }
private void UpdatePurchase() { SPFieldLookupValueCollection RequestDetails = new SPFieldLookupValueCollection(); var RequestDetailList = Utility.GetListFromURL(Constants.REQUEST_DETAIL_LIST_URL, SPContext.Current.Web); foreach (RepeaterItem RequestDetail in repeaterRequestDetail.Items) { HiddenField hiddenFieldId = RequestDetail.FindControl("hiddenFieldId") as HiddenField; TextBox txtProductName = RequestDetail.FindControl("txtProductName") as TextBox; TextBox txtQuantity = RequestDetail.FindControl("txtQuantity") as TextBox; TextBox txtPrice = RequestDetail.FindControl("txtPrice") as TextBox; TextBox txtDescription = RequestDetail.FindControl("txtDescription") as TextBox; if (!string.IsNullOrEmpty(hiddenFieldId.Value)) { if (!string.IsNullOrEmpty(txtProductName.Text)) { var spFieldLookupValue = UpdateRequestDetail(RequestDetailList, int.Parse(hiddenFieldId.Value), txtProductName.Text, txtQuantity.Text, txtPrice.Text, txtDescription.Text); RequestDetails.Add(spFieldLookupValue); } else { SPListItem RequestDetailItem = RequestDetailList.GetItemById(int.Parse(hiddenFieldId.Value)); RequestDetailItem.Delete(); } } else { if (!string.IsNullOrEmpty(txtProductName.Text)) { SPListItem RequestDetailItem = RequestDetailList.AddItem(); RequestDetailItem[SPBuiltInFieldId.Title] = txtProductName.Text; RequestDetailItem["Quantity"] = txtQuantity.Text; RequestDetailItem["Price"] = txtPrice.Text; RequestDetailItem["Description"] = txtDescription.Text; RequestDetailItem.Update(); SPFieldLookupValue spFieldLookupValue = new SPFieldLookupValue(RequestDetailItem.ID, RequestDetailItem.Title); RequestDetails.Add(spFieldLookupValue); } } } SPContext.Current.ListItem[SPBuiltInFieldId.Title] = ffTitle.Value; SPContext.Current.ListItem["TypeOfApproval"] = hiddenTypeOfApproval.Value; SPContext.Current.ListItem["RequestDetail"] = RequestDetails; SPContext.Current.ListItem["References"] = ffReferences.Value;//PurchaseHelper.GetMultipleItemSelectionValues(purchaseReferences); if (peChief.IsValid && peChief.ResolvedEntities.Count > 0) SPContext.Current.ListItem["Chief"] = SPContext.Current.Web.EnsureUser(((PickerEntity)peChief.ResolvedEntities[0]).Key); //ffChief.Value; // if (peBuyer.IsValid && peBuyer.ResolvedEntities.Count > 0) SPContext.Current.ListItem["Buyer"] = SPContext.Current.Web.EnsureUser(((PickerEntity)peBuyer.ResolvedEntities[0]).Key); //ffBuyer.Value; // if (peApprover.IsValid && peApprover.ResolvedEntities.Count > 0) SPContext.Current.ListItem["Approver"] = SPContext.Current.Web.EnsureUser(((PickerEntity)peApprover.ResolvedEntities[0]).Key); //ffApprover.Value; // if (peAccountant.IsValid && peAccountant.ResolvedEntities.Count > 0) SPContext.Current.ListItem["Accountant"] = SPContext.Current.Web.EnsureUser(((PickerEntity)peAccountant.ResolvedEntities[0]).Key); //ffAccountant.Value; // if (peConfirmer.IsValid && peConfirmer.ResolvedEntities.Count > 0) SPContext.Current.ListItem["Confirmer"] = SPContext.Current.Web.EnsureUser(((PickerEntity)peConfirmer.ResolvedEntities[0]).Key); //ffConfirmer.Value; // SPContext.Current.ListItem.Update(); }
/// <summary> /// CustomSaveHandler /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void CustomSaveHandler(object sender, EventArgs e) { SPContext.Current.Web.AllowUnsafeUpdates = true; var item = SPContext.Current.ListItem; SPFieldLookupValueCollection returnVal = new SPFieldLookupValueCollection(); foreach (ListItem lItem in ddlCat.Items) { if (lItem.Selected) { if (lItem.Value != "0" && lItem.Text != "(None)") { returnVal.Add((new SPFieldLookupValue( int.Parse(lItem.Value), lItem.Text))); } } } if (returnVal.Count > 0) { item[FieldsName.NewsRecord.English.CategoryName] = returnVal; } if (fuNewsImage.HasFile) { var webUrl = SPContext.Current.Web.ServerRelativeUrl; if (webUrl.Equals("/")) { webUrl = ""; } var fuThumbName = string.Format(CultureInfo.InvariantCulture, "{0}_{1}", Utilities.GetPreByTime(DateTime.Now), fuNewsImage.FileName); SPFile file = Utilities.UploadFileToDocumentLibrary(SPContext.Current.Web, fuNewsImage.PostedFile.InputStream, string.Format(CultureInfo.InvariantCulture, "{0}/{1}/{2}", webUrl, ListsName.English.ImagesList, fuThumbName)); //CurrentItem[FieldsName.NewsList.InternalName.ImageThumb] = file.Url; RichImageField rifImage = new RichImageField(); ImageFieldValue imageField = rifImage.Value as ImageFieldValue; if (imageField != null) { imageField.ImageUrl = webUrl + "/" + file.Url; item["PublishingPageImage"] = imageField; } } //Save item to list SaveButton.SaveItem(SPContext.Current, false, string.Empty); try { if (fuNewsImage.HasFile) { SPContext.Current.Web.AllowUnsafeUpdates = true; item.Attachments.Delete(fuNewsImage.FileName); SPContext.Current.Web.AllowUnsafeUpdates = true; item.SystemUpdate(false); } } catch (Exception ex) { Utilities.LogToUls(ex); } }
/// <summary> /// Update SPListItem with correcsponding data parse from actions. /// </summary> /// <param name="item"></param> /// <param name="updatedField"></param> /// <param name="data"></param> private void DoUpdateItem(SPListItem item, SPField updatedField, string data) { switch (updatedField.Type) { case SPFieldType.Boolean: item[updatedField.Id] = Convert.ToBoolean(data); break; case SPFieldType.File: case SPFieldType.Calculated: case SPFieldType.Computed: case SPFieldType.Currency: case SPFieldType.Integer: case SPFieldType.Note: case SPFieldType.Number: case SPFieldType.Text: item[updatedField.Id] = data; break; case SPFieldType.Choice: SPFieldChoice fieldChoice = (SPFieldChoice)updatedField; item[updatedField.Id] = data; break; case SPFieldType.DateTime: SPFieldDateTime fieldDate = (SPFieldDateTime)updatedField; item[updatedField.Id] = Convert.ToDateTime(data); break; case SPFieldType.Lookup: SPFieldLookup fieldLookup = (SPFieldLookup)updatedField; if (fieldLookup.AllowMultipleValues) { SPFieldLookupValueCollection multiValues = new SPFieldLookupValueCollection(); foreach (var s in data.Split("|".ToCharArray())) { multiValues.Add(new SPFieldLookupValue(s)); } item[updatedField.Id] = multiValues; } else { //int id = fieldLookup.GetLookupIdFromValue(data); SPFieldLookupValue singleLookupValue = new SPFieldLookupValue(data); item[updatedField.Id] = singleLookupValue; } break; case SPFieldType.MultiChoice: SPFieldMultiChoice fieldMultichoice = (SPFieldMultiChoice)updatedField; string [] items = data.Split("|".ToCharArray()); SPFieldMultiChoiceValue values = new SPFieldMultiChoiceValue(); foreach (string choice in items) { values.Add(choice); } item[updatedField.Id] = values; break; case SPFieldType.User: SPFieldUser fieldUser = (SPFieldUser)updatedField; SPFieldUserValueCollection fieldValues = new SPFieldUserValueCollection(); string[] entities = data.Split("|".ToCharArray()); foreach (string entity in entities) { SPUser user = item.Web.EnsureUser(entity.Split(";#".ToCharArray())[2]); if(user!= null) fieldValues.Add(new SPFieldUserValue(item.Web, user.ID, user.Name)); } item[updatedField.Id] = fieldValues; break; case SPFieldType.Invalid: if (string.Compare(updatedField.TypeAsString, Constants.LOOKUP_WITH_PICKER_TYPE_NAME, true) == 0) { item[updatedField.Id] = data; } break; } }
private static void ClearOld(LinkedLookupSettings config, int listItemId, List<int> removeItems, SPField remoteLookup, SPList remoteList) { foreach (int id in removeItems) { SPListItem remoteItem; try { remoteItem = remoteList.GetItemById(id); } catch { continue; } // pokusit se z lookupu v remoteItemu smazat polozku, na ktere aktualne bezi receiver // pokud je to multilookup, chceme si zachovat zbytek hodnot if (( (SPFieldLookup) remoteLookup ).AllowMultipleValues && ( remoteItem[remoteLookup.InternalName] ?? "" ).ToString().Trim() != "") { // stavajici obsah lookupu SPFieldLookupValueCollection existingCollection = new SPFieldLookupValueCollection(( remoteItem[remoteLookup.InternalName] ?? "" ).ToString()); SPFieldLookupValue toRemove = existingCollection.FirstOrDefault(lookup => lookup.LookupId == listItemId); // ze stavajiciho obsahu odstranime polozku, na ktere bezi receiver if (toRemove != null) existingCollection.Remove(toRemove); // upraveny obsah vratime zpatky remoteItem[remoteLookup.InternalName] = existingCollection; } // pokud je to jednoduchy lookup, a neni prazdny, proste tam nastavime aktualni polozku else if (( remoteItem[remoteLookup.InternalName] ?? "" ).ToString().Trim() != "") { SPFieldLookupValue existingVal = new SPFieldLookupValue(( remoteItem[remoteLookup.InternalName] ?? "" ).ToString()); if (existingVal.LookupId == listItemId) { remoteItem[remoteLookup.InternalName] = null; } } if (config.RegularUpdate) { remoteItem.Update(false); } else { // pokud jsou receivery na obou stranach, nechceme se dostat do smycky remoteItem.SystemUpdate(config.UpdateVersion, false); } } }