/// <summary> /// Event Receiver Info (List) /// </summary> /// <param name="list">The list</param> /// <param name="type">The event receiver type</param> /// <param name="syncType">The synchronization type</param> public EventReceiverInfo(ListInfo list, SPEventReceiverType type, SPEventReceiverSynchronization syncType) { this.List = list; this.EventOwner = EventReceiverOwner.List; this.ReceiverType = type; this.SynchronizationType = syncType; }
public void EnsureList_WhenNotAlreadyExists_ShouldCreateANewOneNOTListsPath() { // Arrange using (var testScope = SiteTestScope.BlankSite()) { var listInfo = new ListInfo("testUrl", "nameKey", "descriptionKey"); using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope()) { var listHelper = injectionScope.Resolve<IListHelper>(); var testRootWeb = testScope.SiteCollection.RootWeb; var numberOfListsBefore = testRootWeb.Lists.Count; // Act var list = listHelper.EnsureList(testRootWeb, listInfo); // Assert Assert.AreEqual(numberOfListsBefore + 1, testRootWeb.Lists.Count); Assert.IsNotNull(list); Assert.AreEqual(listInfo.DisplayNameResourceKey, list.TitleResource.Value); Assert.AreEqual(listInfo.DescriptionResourceKey, list.DescriptionResource.Value); // Fetch the list on the root web to make sure it was created and that it persists at the right location var newlyCreatedList = testRootWeb.GetList("testUrl"); Assert.IsNotNull(newlyCreatedList); Assert.AreEqual(listInfo.DisplayNameResourceKey, newlyCreatedList.TitleResource.Value); } } }
/// <summary> /// Sync a SPList for multiple target labels /// </summary> /// <param name="web">The web</param> /// <param name="listInfo">The source list metadata</param> /// <param name="labels">The destination labels</param> public void SyncList(SPWeb web, ListInfo listInfo, IList<VariationLabelInfo> labels) { var list = this._listHelper.EnsureList(web, listInfo); foreach (VariationLabelInfo label in labels) { // Synchronize only target labels if (!label.IsSource) { this.SyncList(list, label.Title); } } }
/// <summary> /// Creates a new instance of MetadataNavigationSettingsInfo. Use this constructor if you don't have any custom configurations /// </summary> /// <param name="list">The associated list</param> /// <param name="addFolderDefaultHierarchy">True to view the folder hierachy in the treeview. False otherwise</param> /// <param name="addContentTypeDefaultHierarchy">True to view the content type hierachy in the treeview. False otherwise</param> /// <param name="addContentTypeDefaultKeyFilter">True to view the content type key filter. False otherwise</param> public MetadataNavigationSettingsInfo( ListInfo list, bool addFolderDefaultHierarchy, bool addContentTypeDefaultHierarchy, bool addContentTypeDefaultKeyFilter) : this( list, addFolderDefaultHierarchy, addContentTypeDefaultHierarchy, addContentTypeDefaultKeyFilter, null, null) { }
public void EnsureList_AListWithSameNameExistsOnDifferentWeb_ShouldCreateListAtSpecifiedWebAndURL() { // Arrange const string Url = "testUrl"; const string NameKey = "NameKey"; const string DescKey = "DescriptionKey"; using (var testScope = SiteTestScope.BlankSite()) { // Let's first create a list on the root web var listInfo = new ListInfo(Url, NameKey, DescKey); using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope()) { var listHelper = injectionScope.Resolve<IListHelper>(); var rootWeb = testScope.SiteCollection.RootWeb; var numberOfListsOnRootWebBefore = rootWeb.Lists.Count; var listRootWeb = listHelper.EnsureList(rootWeb, listInfo); Assert.AreEqual(numberOfListsOnRootWebBefore + 1, rootWeb.Lists.Count); Assert.IsNotNull(listRootWeb); Assert.AreEqual(listInfo.DisplayNameResourceKey, listRootWeb.TitleResource.Value); // Now let's create a sub web under root, and try to ensure the "same" list there. It should create a new one. var subWeb = rootWeb.Webs.Add("subweb"); var numberOfListsOnSubWebBefore = subWeb.Lists.Count; // Act var listSubWeb = listHelper.EnsureList(subWeb, listInfo); // Assert Assert.AreEqual(numberOfListsOnSubWebBefore + 1, subWeb.Lists.Count); Assert.IsNotNull(listSubWeb); Assert.AreEqual(listInfo.DisplayNameResourceKey, listSubWeb.TitleResource.Value); // Finally, try to get both lists to make sure everything is right var firstList = rootWeb.GetList(Url); Assert.IsNotNull(firstList); Assert.AreEqual(listInfo.DisplayNameResourceKey, firstList.TitleResource.Value); var secondList = subWeb.GetList(SPUtility.ConcatUrls(subWeb.ServerRelativeUrl, Url)); Assert.IsNotNull(secondList); Assert.AreEqual(listInfo.DisplayNameResourceKey, secondList.TitleResource.Value); } } }
/// <summary> /// Creates a new instance of MetadataNavigationSettingsInfo. Use this constructor if you have custom configurations /// </summary> /// <param name="list">The associated list</param> /// <param name="addFolderDefaultHierarchy">True to view the folder hierachy in the treeview. False otherwise</param> /// <param name="addContentTypeDefaultHierarchy">True to view the content type hierachy in the treeview. False otherwise</param> /// <param name="addContentTypeDefaultKeyFilter">True to view the content type key filter. False otherwise</param> /// <param name="hierachies">Treeview hierachies to add based on fields internal names</param> /// <param name="keyFilters">Fields internal names act as key filters</param> public MetadataNavigationSettingsInfo( ListInfo list, bool addFolderDefaultHierarchy, bool addContentTypeDefaultHierarchy, bool addContentTypeDefaultKeyFilter, IList <string> hierachies, IList <string> keyFilters) { this.List = list; this.AddContentTypeDefaultKeyFilter = addContentTypeDefaultKeyFilter; this.AddContentTypeDefaultHierarchy = addContentTypeDefaultHierarchy; this.AddFolderDefaultHierarchy = addFolderDefaultHierarchy; this.Hierarchies = hierachies; this.KeyFilters = keyFilters; }
/// <summary> /// Creates a new instance of MetadataNavigationSettingsInfo. Use this constructor if you have custom configurations /// </summary> /// <param name="list">The associated list</param> /// <param name="addFolderDefaultHierarchy">True to view the folder hierachy in the treeview. False otherwise</param> /// <param name="addContentTypeDefaultHierarchy">True to view the content type hierachy in the treeview. False otherwise</param> /// <param name="addContentTypeDefaultKeyFilter">True to view the content type key filter. False otherwise</param> /// <param name="hierachies">Treeview hierachies to add based on fields internal names</param> /// <param name="keyFilters">Fields internal names act as key filters</param> public MetadataNavigationSettingsInfo( ListInfo list, bool addFolderDefaultHierarchy, bool addContentTypeDefaultHierarchy, bool addContentTypeDefaultKeyFilter, IList<string> hierachies, IList<string> keyFilters) { this.List = list; this.AddContentTypeDefaultKeyFilter = addContentTypeDefaultKeyFilter; this.AddContentTypeDefaultHierarchy = addContentTypeDefaultHierarchy; this.AddFolderDefaultHierarchy = addFolderDefaultHierarchy; this.Hierarchies = hierachies; this.KeyFilters = keyFilters; }
private static bool ListContainsAttachments(SPWeb web, ListInfo listInfo) { SPFolder listFolder = null; // Get the list folder in the web var folders = listInfo.WebRelativeUrl.ToString().Split('/'); for (var i = 0; i < folders.Count(); i++) { // If the first list folder segment, get it in the web folders collection. // Else, get the folder in the subfolders collection. if (i == 0) { listFolder = web.Folders[folders[i]]; } else if (listFolder != null) { listFolder = listFolder.SubFolders[folders[i]]; } } // If the list folder exists if (listFolder != null) { try { // If the attachments folder exists var attachmentsFolder = listFolder.SubFolders["Attachments"]; if (attachmentsFolder != null) { // Return true if any attachments folder contains a subfolder with files. return(attachmentsFolder.SubFolders.Cast <SPFolder>().Any(folder => folder.Files.Count > 0)); } } catch (ArgumentException) { return(false); } } return(false); }
private void SetTitleAndDescriptionValues(SPWeb web, ListInfo listInfo, SPList list) { // end with the main language var availableLanguages = web.SupportedUICultures.Reverse(); foreach (var availableLanguage in availableLanguages) { if (!string.IsNullOrEmpty(listInfo.DisplayNameResourceKey)) { var title = this.resourceLocator.Find(listInfo.ResourceFileName, listInfo.DisplayNameResourceKey, availableLanguage.LCID); list.TitleResource.SetValueForUICulture(availableLanguage, title); list.TitleResource.Update(); } if (!string.IsNullOrEmpty(listInfo.DescriptionResourceKey)) { var description = this.resourceLocator.Find(listInfo.ResourceFileName, listInfo.DescriptionResourceKey, availableLanguage.LCID); list.DescriptionResource.SetValueForUICulture(availableLanguage, description); list.DescriptionResource.Update(); } } }
public void EnsureField_WhenTaxonomySingleOrMultiAndListField_AndSiteCollectionSpecificTermSet_ShouldApplyTermSetMappingToListColumn() { using (var testScope = SiteTestScope.BlankSite()) { // Arrange 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("{0C58B4A1-B360-47FE-84F7-4D8F58AE80F6}"), "NameKey", "DescriptionKey", "GroupKey") { TermStoreMapping = new TaxonomyContext(testTermSet) // choices limited to all terms in test term set }; TaxonomyMultiFieldInfo taxoMultiFieldInfo = new TaxonomyMultiFieldInfo( "TestInternalNameTaxoMulti", new Guid("{B2517ECF-819E-4F75-88AF-18E926AD30BD}"), "NameKeyMulti", "DescriptionKey", "GroupKey") { TermStoreMapping = new TaxonomyContext(levelOneTermA) // choices limited to children of a specific term, instead of having full term set choices }; ListInfo listInfo = new ListInfo("sometestlistpath", "DynamiteTestListNameKey", "DynamiteTestListDescriptionKey"); using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope()) { IListHelper listHelper = injectionScope.Resolve<IListHelper>(); var list = listHelper.EnsureList(testScope.SiteCollection.RootWeb, listInfo); IFieldHelper fieldHelper = injectionScope.Resolve<IFieldHelper>(); var fieldsCollection = list.Fields; // Ensure one of the two on the root web (tweak the definition a little bit on the list def) fieldHelper.EnsureField(testScope.SiteCollection.RootWeb.Fields, taxoMultiFieldInfo); taxoMultiFieldInfo.Required = RequiredType.Required; taxoMultiFieldInfo.TermStoreMapping = new TaxonomyContext(levelTwoTermAB); // Act TaxonomyField fieldSingle = (TaxonomyField)fieldHelper.EnsureField(fieldsCollection, taxoFieldInfo); TaxonomyField fieldMulti = (TaxonomyField)fieldHelper.EnsureField(fieldsCollection, taxoMultiFieldInfo); // Assert Assert.AreEqual(testTermSet.Id, fieldSingle.TermSetId); Assert.AreEqual(defaultSiteCollectionTermStore.Id, fieldSingle.SspId); Assert.AreEqual(Guid.Empty, fieldSingle.AnchorId); // choices should not be constrained to a child term Assert.IsTrue(fieldSingle.IsTermSetValid); Assert.AreEqual(testTermSet.Id, fieldMulti.TermSetId); Assert.AreEqual(defaultSiteCollectionTermStore.Id, fieldMulti.SspId); Assert.AreEqual(levelTwoTermAB.Id, fieldMulti.AnchorId); // choices should be constrained to a 2nd level child term Assert.IsTrue(fieldMulti.IsTermSetValid); Assert.IsTrue(fieldMulti.IsAnchorValid); Assert.IsTrue(fieldMulti.Required); // Gotta also make sure (by fetching the fields again) that the field properties were all persisted TaxonomyField fieldSingleFetchedAgain = (TaxonomyField)testScope.SiteCollection.RootWeb.Lists[list.ID].Fields[taxoFieldInfo.Id]; TaxonomyField fieldMultiFetchedAgain = (TaxonomyField)testScope.SiteCollection.RootWeb.Lists[list.ID].Fields[taxoMultiFieldInfo.Id]; Assert.AreEqual(testTermSet.Id, fieldSingleFetchedAgain.TermSetId); Assert.AreEqual(defaultSiteCollectionTermStore.Id, fieldSingleFetchedAgain.SspId); Assert.AreEqual(Guid.Empty, fieldSingleFetchedAgain.AnchorId); // choices should not be constrained to a child term Assert.IsTrue(fieldSingleFetchedAgain.IsTermSetValid); Assert.AreEqual(testTermSet.Id, fieldMultiFetchedAgain.TermSetId); Assert.AreEqual(defaultSiteCollectionTermStore.Id, fieldMultiFetchedAgain.SspId); Assert.AreEqual(levelTwoTermAB.Id, fieldMultiFetchedAgain.AnchorId); // choices should be constrained to a 2nd level child term Assert.IsTrue(fieldMultiFetchedAgain.IsTermSetValid); Assert.IsTrue(fieldMultiFetchedAgain.IsAnchorValid); Assert.IsTrue(fieldMultiFetchedAgain.Required); } // Cleanup term set so that we don't pollute the metadata store newTermSet.Delete(); defaultSiteCollectionTermStore.CommitAll(); } }
public void EnsureField_WhenTaxonomySingleOrMultiAndListField_AndSiteCollectionSpecificTermSet_ShouldApplyDefaultValue() { using (var testScope = SiteTestScope.BlankSite()) { // Arrange 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("{0C58B4A1-B360-47FE-84F7-4D8F58AE80F6}"), "NameKey", "DescriptionKey", "GroupKey") { DefaultValue = new TaxonomyValue(levelOneTermA), TermStoreMapping = new TaxonomyContext(testTermSet) // choices limited to all terms in test term set }; TaxonomyMultiFieldInfo taxoMultiFieldInfo = new TaxonomyMultiFieldInfo( "TestInternalNameTaxoMulti", new Guid("{B2517ECF-819E-4F75-88AF-18E926AD30BD}"), "NameKeyMulti", "DescriptionKey", "GroupKey") { DefaultValue = new TaxonomyValueCollection( new List<TaxonomyValue>() { new TaxonomyValue(levelTwoTermAA), new TaxonomyValue(levelTwoTermAB) }), TermStoreMapping = new TaxonomyContext(levelOneTermA) // choices limited to children of a specific term, instead of having full term set choices }; ListInfo listInfo = new ListInfo("sometestlistpath", "DynamiteTestListNameKey", "DynamiteTestListDescriptionKey"); using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope()) { IListHelper listHelper = injectionScope.Resolve<IListHelper>(); var list = listHelper.EnsureList(testScope.SiteCollection.RootWeb, listInfo); IFieldHelper fieldHelper = injectionScope.Resolve<IFieldHelper>(); var fieldsCollection = list.Fields; // Ensure one of the two on the root web (tweak the definition a little bit on the list def) fieldHelper.EnsureField(testScope.SiteCollection.RootWeb.Fields, taxoMultiFieldInfo); taxoMultiFieldInfo.Required = RequiredType.Required; // Act SPField fieldSingle = fieldHelper.EnsureField(fieldsCollection, taxoFieldInfo); SPField fieldMulti = fieldHelper.EnsureField(fieldsCollection, taxoMultiFieldInfo); var fieldValue = new TaxonomyFieldValue(fieldSingle.DefaultValue); var fieldMultiValueCollection = new TaxonomyFieldValueCollection(fieldMulti.DefaultValue); // Assert Assert.AreNotEqual(-1, fieldValue.WssId); // a lookup ID to the TaxonomyHiddenList should be properly initialized at all times (lookup ID == -1 means you're depending on too much magic) Assert.AreEqual("Term A", fieldValue.Label); Assert.AreEqual(levelOneTermA.Id, new Guid(fieldValue.TermGuid)); Assert.AreNotEqual(-1, fieldMultiValueCollection[0].WssId); // lookup ID to TaxoHiddenList should also be initialized on multi-values Assert.AreEqual("Term A-A", fieldMultiValueCollection[0].Label); Assert.AreEqual(levelTwoTermAA.Id, new Guid(fieldMultiValueCollection[0].TermGuid)); Assert.AreNotEqual(-1, fieldMultiValueCollection[1].WssId); Assert.AreEqual("Term A-B", fieldMultiValueCollection[1].Label); Assert.AreEqual(levelTwoTermAB.Id, new Guid(fieldMultiValueCollection[1].TermGuid)); Assert.IsTrue(fieldMulti.Required); // Same asserts, but on re-fetched field (to make sure DefaultValue was persisted properly) SPField fieldSingleRefetched = testScope.SiteCollection.RootWeb.Lists[list.ID].Fields[taxoFieldInfo.Id]; SPField fieldMultiRefetched = testScope.SiteCollection.RootWeb.Lists[list.ID].Fields[taxoMultiFieldInfo.Id]; fieldValue = new TaxonomyFieldValue(fieldSingle.DefaultValue); fieldMultiValueCollection = new TaxonomyFieldValueCollection(fieldMulti.DefaultValue); Assert.AreNotEqual(-1, fieldValue.WssId); // a lookup ID to the TaxonomyHiddenList should be properly initialized at all times (lookup ID == -1 means you're depending on too much magic) Assert.AreEqual("Term A", fieldValue.Label); Assert.AreEqual(levelOneTermA.Id, new Guid(fieldValue.TermGuid)); Assert.AreNotEqual(-1, fieldMultiValueCollection[0].WssId); // lookup ID to TaxoHiddenList should also be initialized on multi-values Assert.AreEqual("Term A-A", fieldMultiValueCollection[0].Label); Assert.AreEqual(levelTwoTermAA.Id, new Guid(fieldMultiValueCollection[0].TermGuid)); Assert.AreNotEqual(-1, fieldMultiValueCollection[1].WssId); Assert.AreEqual("Term A-B", fieldMultiValueCollection[1].Label); Assert.AreEqual(levelTwoTermAB.Id, new Guid(fieldMultiValueCollection[1].TermGuid)); Assert.IsTrue(fieldMultiRefetched.Required); } // Cleanup term set so that we don't pollute the metadata store newTermSet.Delete(); defaultSiteCollectionTermStore.CommitAll(); } }
public void EnsureField_WhenTaxonomySingleOrMultiAndListField_AndGlobalFarmWideTermSet_ShouldApplyTermSetMappingToListColumn() { using (var testScope = SiteTestScope.BlankSite()) { // Arrange Guid testGroupId = new Guid("{B7B56932-E191-46C7-956F-4C6E5E4F6020}"); var testTermSet = new TermSetInfo(Guid.NewGuid(), "Test Term Set") // keep Ids random because, if this test fails midway, the term { // must specify group, otherwise we would be describing a term set belonging to a site-specific group Group = new TermGroupInfo(testGroupId, "Dynamite Test Group") }; // 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; // Cleanup group (maybe the test failed last time and the old group ended up polluting the term store this.DeleteGroupIfExists(defaultSiteCollectionTermStore, testGroupId); Group testGroup = defaultSiteCollectionTermStore.CreateGroup("Dynamite Test Group", testGroupId); TermSet newTermSet = testGroup.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("{0C58B4A1-B360-47FE-84F7-4D8F58AE80F6}"), "NameKey", "DescriptionKey", "GroupKey") { TermStoreMapping = new TaxonomyContext(testTermSet) // choices limited to all terms in test term set }; TaxonomyMultiFieldInfo taxoMultiFieldInfo = new TaxonomyMultiFieldInfo( "TestInternalNameTaxoMulti", new Guid("{B2517ECF-819E-4F75-88AF-18E926AD30BD}"), "NameKeyMulti", "DescriptionKey", "GroupKey") { TermStoreMapping = new TaxonomyContext(levelOneTermA) // choices limited to children of a specific term, instead of having full term set choices }; ListInfo listInfo = new ListInfo("sometestlistpath", "DynamiteTestListNameKey", "DynamiteTestListDescriptionKey"); using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope()) { IListHelper listHelper = injectionScope.Resolve<IListHelper>(); var list = listHelper.EnsureList(testScope.SiteCollection.RootWeb, listInfo); IFieldHelper fieldHelper = injectionScope.Resolve<IFieldHelper>(); var fieldsCollection = list.Fields; // Ensure one of the two on the root web (tweak the definition a little bit on the list def) fieldHelper.EnsureField(testScope.SiteCollection.RootWeb.Fields, taxoMultiFieldInfo); taxoMultiFieldInfo.Required = RequiredType.Required; taxoMultiFieldInfo.TermStoreMapping = new TaxonomyContext(levelTwoTermAB); // Act SPField fieldSingle = fieldHelper.EnsureField(fieldsCollection, taxoFieldInfo); SPField fieldMulti = fieldHelper.EnsureField(fieldsCollection, taxoMultiFieldInfo); // Assert TaxonomyField fieldSingleFetchedAgain = (TaxonomyField)testScope.SiteCollection.RootWeb.Lists[list.ID].Fields[taxoFieldInfo.Id]; TaxonomyField fieldMultiFetchedAgain = (TaxonomyField)testScope.SiteCollection.RootWeb.Lists[list.ID].Fields[taxoMultiFieldInfo.Id]; Assert.IsNotNull(fieldSingleFetchedAgain); Assert.AreEqual(testTermSet.Id, fieldSingleFetchedAgain.TermSetId); Assert.AreEqual(defaultSiteCollectionTermStore.Id, fieldSingleFetchedAgain.SspId); Assert.AreEqual(Guid.Empty, fieldSingleFetchedAgain.AnchorId); // choices should not be constrained to a child term Assert.IsTrue(fieldSingleFetchedAgain.IsTermSetValid); Assert.IsNotNull(fieldMultiFetchedAgain); Assert.AreEqual(testTermSet.Id, fieldMultiFetchedAgain.TermSetId); Assert.AreEqual(defaultSiteCollectionTermStore.Id, fieldMultiFetchedAgain.SspId); Assert.AreEqual(levelTwoTermAB.Id, fieldMultiFetchedAgain.AnchorId); // choices should be constrained to a child term Assert.IsTrue(fieldSingleFetchedAgain.IsTermSetValid); Assert.IsTrue(fieldSingleFetchedAgain.IsAnchorValid); } // Cleanup term group so that we don't pollute the metadata store this.DeleteGroupIfExists(defaultSiteCollectionTermStore, testGroupId); } }
/// <summary> /// Creates the list or returns the existing one. /// </summary> /// <remarks>The list name and description will not be translated</remarks> /// <exception cref="SPException">If the list already exists but doesn't have the specified list template.</exception> /// <param name="web">The current web</param> /// <param name="listInfo">The list to create</param> /// <returns>The new list or the existing list</returns> public SPList EnsureList(SPWeb web, ListInfo listInfo) { // First, try to find an already existing list with the same name but at a different Web-relative URL var list = this.listLocator.GetByNameResourceKey(web, listInfo.DisplayNameResourceKey); if (list != null) { if (!list.RootFolder.Url.Equals(listInfo.WebRelativeUrl.ToString(), StringComparison.OrdinalIgnoreCase)) { // A list with the same name already exists on a different web relative URL, throwing exception throw new ArgumentException( string.Format(CultureInfo.InvariantCulture, "A list with the name {0} already exists on a different web relative URL. Try using a different name.", listInfo.DisplayNameResourceKey)); } } // Validate draft visibility setting if (listInfo.HasDraftVisibilityType && listInfo.DraftVisibilityType == DraftVisibilityType.Approver) { // Moderation is required when the draft visibility is set to approver. if (!listInfo.IsModerationEnabled) { this.logger.Warn("When ensuring a list with draft visibility type of Approver, moderation needs to be enabled. Setting moderation enabled to true automatically."); listInfo.IsModerationEnabled = true; } } else if (listInfo.HasDraftVisibilityType && listInfo.DraftVisibilityType == DraftVisibilityType.Author) { // Moderation or minor versions need to be enabled for draft visibility to be set to author. if (!listInfo.IsModerationEnabled && !(listInfo.AreMinorVersionsEnabled && listInfo.IsVersioningEnabled)) { this.logger.Warn("When ensuring a list with draft visibility type of Author, moderation or minor versions needs to be enabled. Setting moderation enabled to true automatically."); listInfo.IsModerationEnabled = true; } } list = this.listLocator.TryGetList(web, listInfo.WebRelativeUrl.ToString()); // Ensure the list if (list == null) { list = this.CreateList(web, listInfo); } else { // If it isn't the pages library if (string.CompareOrdinal(list.RootFolder.Name, PagesLibraryRootFolder) != 0) { this.logger.Info("List " + listInfo.WebRelativeUrl.ToString() + " already exists"); // If the Overwrite parameter is set to true, delete and recreate the catalog if (listInfo.Overwrite) { this.logger.Info("Overwrite is set to true, recreating the list " + listInfo.WebRelativeUrl.ToString()); web.Lists.Delete(list.ID); // gotta force a re-fetch on the parent SPWeb, otherwise the // the new list will be create with the same ID as the old one (don't ask, weird SP API behavior). using (var freshWebToMakeSureNewListGuidIsGiven = web.Site.OpenWeb(web.ID)) { list = this.CreateList(freshWebToMakeSureNewListGuidIsGiven, listInfo); } } } } // Update the display name and description, if need be this.SetTitleAndDescriptionValues(web, listInfo, list); // Remove Item Content Type if (listInfo.RemoveDefaultContentType) { this.logger.Info("Removing the default Item Content Type"); // If content type is direct child of item, remove it this.RemoveItemContentType(list); } // Add All Content Types if (listInfo.ContentTypes != null && listInfo.ContentTypes.Count >= 1) { this.contentTypeBuilder.EnsureContentType(list.ContentTypes, listInfo.ContentTypes); // Re-fetch, list was updated through another object instance, so we gotta refresh our object instance list = web.Lists[list.ID]; // Set the unique content type order on the root folder. IList <SPContentType> contentTypeOrder = new List <SPContentType>(); foreach (var contentTypeInfo in listInfo.ContentTypes) { var listContentType = GetListContentType(list, contentTypeInfo); if (listContentType != null) { // If we find a content type on the list that matches the content type info in the list info we add it to the collection. contentTypeOrder.Add(listContentType); } } if (contentTypeOrder.Count >= 1) { // If we have content types in our new list, we set the new list. list.RootFolder.UniqueContentTypeOrder = contentTypeOrder; list.RootFolder.Update(); } list.Update(); } // Write the list ID in a property bag key-value pair if (!string.IsNullOrEmpty(listInfo.PropertyBagKeyForListId)) { this.SetPropertyBagKeyForListId(web, listInfo.PropertyBagKeyForListId, list.ID.ToString()); } list = web.Lists[list.ID]; // Update the moderation setting list.EnableModeration = listInfo.IsModerationEnabled; // Versioning settings this.SetVersioning( list, listInfo.IsVersioningEnabled, listInfo.AreMinorVersionsEnabled, listInfo.MajorVersionLimit, listInfo.MinorVersionLimit); // Draft VisibilityType if (listInfo.HasDraftVisibilityType) { list.DraftVersionVisibility = listInfo.DraftVisibilityType; } // Ratings this.SetRatings(list, listInfo.RatingType, listInfo.EnableRatings); // Set list Write Security this.SetWriteSecurity(list, listInfo.WriteSecurity); // Quick Launch Navigation if (listInfo.AddToQuickLaunch) { this.AddtoQuickLaunch(list); } // Attachements (only possible if not a DocLib or Survey list) if (listInfo.EnableAttachements) { if (list.BaseType != SPBaseType.Survey && list.BaseType != SPBaseType.DocumentLibrary) { list.EnableAttachments = listInfo.EnableAttachements; } else { this.logger.Warn( "EnsureList - Skipped setting EnableAttachment=TRUE on list (url={0}) because list is a Document Library or a Survey list, which don't support attachements." + " Provide a ListInfo without EnableAttachment=TRUE to avoid this warning.", listInfo.WebRelativeUrl); } } else if (!ListContainsAttachments(web, listInfo)) { // Want to disable attachments on a list with no attachments already created list.EnableAttachments = listInfo.EnableAttachements; } else { // Case where you would like to disable attachments on a list which contains attachments. It is not allowed // because it could delete all attachments. throw new ArgumentException( string.Format( CultureInfo.InvariantCulture, "Not allowed to disable attachments on list '{0}' because it contains attachement(s). Attachments on it would be lost.", list.TitleResource.Value)); } list.Update(); // Get the updated list object because we have to reference previous added fields that the old list object didn't have (cause NullReferenceException). list = this.listLocator.TryGetList(web, listInfo.WebRelativeUrl.ToString()); // Ensure the field definitions to make sure that all fields are present and to override/apply column default Values this.fieldHelper.EnsureField(list.Fields, listInfo.FieldDefinitions); // List Validation Settings if (listInfo.ValidationSettings.Any()) { ListValidationInfo currentLocaleSettings; if (listInfo.ValidationSettings.TryGetValue(web.Locale.Name, out currentLocaleSettings)) { this.ConfigureValidationSettings(list, currentLocaleSettings.ValidationFormula, currentLocaleSettings.ValidationMessage); } else { this.logger.Warn("No validation settings found in the dictionnary corresponding to the current web locale {0}. Skipping this step.", web.Locale.Name); } } // Default View Fields this.AddFieldsToDefaultView(list, listInfo.DefaultViewFields); // Save changes. list.Update(); return(list); }
/// <summary> /// Creates the list or returns the existing one. /// </summary> /// <remarks>The list name and description will not be translated</remarks> /// <exception cref="SPException">If the list already exists but doesn't have the specified list template.</exception> /// <param name="web">The current web</param> /// <param name="listInfo">The list to create</param> /// <returns>The new list or the existing list</returns> public SPList EnsureList(SPWeb web, ListInfo listInfo) { // First, try to find an already existing list with the same name but at a different Web-relative URL var list = this.listLocator.GetByNameResourceKey(web, listInfo.DisplayNameResourceKey); if (list != null) { if (!list.RootFolder.Url.Equals(listInfo.WebRelativeUrl.ToString(), StringComparison.OrdinalIgnoreCase)) { // A list with the same name already exists on a different web relative URL, throwing exception throw new ArgumentException( string.Format(CultureInfo.InvariantCulture, "A list with the name {0} already exists on a different web relative URL. Try using a different name.", listInfo.DisplayNameResourceKey)); } } list = this.listLocator.TryGetList(web, listInfo.WebRelativeUrl.ToString()); // Ensure the list if (list == null) { list = this.CreateList(web, listInfo); } else { // If it isn't the pages library if (string.CompareOrdinal(list.RootFolder.Name, PagesLibraryRootFolder) != 0) { this.logger.Info("List " + listInfo.WebRelativeUrl.ToString() + " already exists"); // If the Overwrite parameter is set to true, delete and recreate the catalog if (listInfo.Overwrite) { this.logger.Info("Overwrite is set to true, recreating the list " + listInfo.WebRelativeUrl.ToString()); web.Lists.Delete(list.ID); // gotta force a re-fetch on the parent SPWeb, otherwise the // the new list will be create with the same ID as the old one (don't ask, weird SP API behavior). using (var freshWebToMakeSureNewListGuidIsGiven = web.Site.OpenWeb(web.ID)) { list = this.CreateList(freshWebToMakeSureNewListGuidIsGiven, listInfo); } } } } // Update the display name and description, if need be this.SetTitleAndDescriptionValues(web, listInfo, list); // Remove Item Content Type if (listInfo.RemoveDefaultContentType) { this.logger.Info("Removing the default Item Content Type"); // If content type is direct child of item, remove it this.RemoveItemContentType(list); } // Add All Content Types if (listInfo.ContentTypes != null && listInfo.ContentTypes.Count >= 1) { this.contentTypeBuilder.EnsureContentType(list.ContentTypes, listInfo.ContentTypes); // Re-fetch, list was updated through another object instance, so we gotta refresh our object instance list = web.Lists[list.ID]; // Set the unique content type order on the root folder. IList<SPContentType> contentTypeOrder = new List<SPContentType>(); foreach (var contentTypeInfo in listInfo.ContentTypes) { var listContentType = GetListContentType(list, contentTypeInfo); if (listContentType != null) { // If we find a content type on the list that matches the content type info in the list info we add it to the collection. contentTypeOrder.Add(listContentType); } } if (contentTypeOrder.Count >= 1) { // If we have content types in our new list, we set the new list. list.RootFolder.UniqueContentTypeOrder = contentTypeOrder; list.RootFolder.Update(); } list.Update(); } list = web.Lists[list.ID]; // Draft VisibilityType if (listInfo.HasDraftVisibilityType) { list.EnableModeration = true; list.DraftVersionVisibility = listInfo.DraftVisibilityType; } // Ratings this.SetRatings(list, listInfo.RatingType, listInfo.EnableRatings); // Set list Write Security this.SetWriteSecurity(list, listInfo.WriteSecurity); // Quick Launch Navigation if (listInfo.AddToQuickLaunch) { this.AddtoQuickLaunch(list); } // Attachements (only possible if not a DocLib or Survey list) if (listInfo.EnableAttachements) { if (list.BaseType != SPBaseType.Survey && list.BaseType != SPBaseType.DocumentLibrary) { list.EnableAttachments = listInfo.EnableAttachements; } else { this.logger.Warn( "EnsureList - Skipped setting EnableAttachment=TRUE on list (url={0}) because list is a Document Library or a Survey list, which don't support attachements." + " Provide a ListInfo without EnableAttachment=TRUE to avoid this warning.", listInfo.WebRelativeUrl); } } else if (list.ItemCount == 0) { // Want to disable attachments on an empty list. list.EnableAttachments = listInfo.EnableAttachements; } else { // Case where you would like to disable attachments on a list with one or more items. It is not allowed // because it could delete all attachments. throw new ArgumentException( string.Format( CultureInfo.InvariantCulture, "Not allowed to disable attachments on list '{0}' because it contains item(s). Attachments on it would be lost.", list.TitleResource.Value)); } list.Update(); // Get the updated list object because we have to reference previous added fields that the old list object didn't have (cause NullReferenceException). list = this.listLocator.TryGetList(web, listInfo.WebRelativeUrl.ToString()); // Ensure the field definitions to make sure that all fields are present and to override/apply column default Values this.fieldHelper.EnsureField(list.Fields, listInfo.FieldDefinitions); // Default View Fields this.AddFieldsToDefaultView(list, listInfo.DefaultViewFields); // Save changes. list.Update(); return list; }
public void FromEntityToEntityRoundTrip_ShouldEndUpWithIdenticalEntities() { 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() { Title = "Test entity", 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(); // Then use the list item as data source for a brand new entity var copyEntity = entityBinder.Get<TestItemEntityWithLookups>(itemOnList); // Assert // #1: validate ListItem field values on the mapped item object Assert.AreEqual(entity.Title, copyEntity.Title); Assert.AreEqual(entity.IntegerProperty, copyEntity.IntegerProperty); Assert.AreEqual(entity.DoubleProperty, copyEntity.DoubleProperty); Assert.AreEqual(entity.CurrencyProperty, copyEntity.CurrencyProperty); Assert.AreEqual(entity.BoolProperty, copyEntity.BoolProperty); Assert.AreEqual(entity.BoolDefaultTrueProperty, copyEntity.BoolDefaultTrueProperty); Assert.AreEqual(entity.BoolDefaultFalseProperty, copyEntity.BoolDefaultFalseProperty); Assert.AreEqual(entity.DateTimeFormulaProperty, copyEntity.DateTimeFormulaProperty); Assert.AreEqual(entity.DateTimeProperty, copyEntity.DateTimeProperty); Assert.AreEqual(entity.TextProperty, copyEntity.TextProperty); Assert.AreEqual(entity.NoteProperty, copyEntity.NoteProperty); Assert.AreEqual(entity.HtmlProperty, copyEntity.HtmlProperty); Assert.AreEqual(entity.ImageProperty.ImageUrl, copyEntity.ImageProperty.ImageUrl); Assert.AreEqual(entity.ImageProperty.Hyperlink, copyEntity.ImageProperty.Hyperlink); Assert.AreEqual(entity.UrlProperty.Url, copyEntity.UrlProperty.Url); Assert.AreEqual(entity.UrlProperty.Description, copyEntity.UrlProperty.Description); Assert.AreEqual(entity.UrlImageProperty.Url, copyEntity.UrlImageProperty.Url); Assert.AreEqual(entity.UrlImageProperty.Description, copyEntity.UrlImageProperty.Description); Assert.AreEqual(entity.LookupProperty.Id, copyEntity.LookupProperty.Id); Assert.AreEqual(entity.LookupProperty.Value, copyEntity.LookupProperty.Value); Assert.AreEqual(entity.LookupAltProperty.Id, copyEntity.LookupAltProperty.Id); Assert.AreEqual(entity.LookupAltProperty.Value, copyEntity.LookupAltProperty.Value); Assert.AreEqual(entity.LookupMultiProperty[0].Id, copyEntity.LookupMultiProperty[0].Id); Assert.AreEqual(entity.LookupMultiProperty[0].Value, copyEntity.LookupMultiProperty[0].Value); Assert.AreEqual(entity.LookupMultiProperty[1].Id, copyEntity.LookupMultiProperty[1].Id); Assert.AreEqual(entity.LookupMultiProperty[1].Value, copyEntity.LookupMultiProperty[1].Value); Assert.AreEqual(entity.UserProperty.Id, copyEntity.UserProperty.Id); Assert.AreEqual(entity.UserProperty.DisplayName, copyEntity.UserProperty.DisplayName); Assert.AreEqual(entity.UserMultiProperty[0].Id, copyEntity.UserMultiProperty[0].Id); Assert.AreEqual(entity.UserMultiProperty[0].DisplayName, copyEntity.UserMultiProperty[0].DisplayName); Assert.AreEqual(entity.UserMultiProperty[1].Id, copyEntity.UserMultiProperty[1].Id); Assert.AreEqual(entity.UserMultiProperty[1].DisplayName, copyEntity.UserMultiProperty[1].DisplayName); Assert.AreEqual(entity.MediaProperty.Title, copyEntity.MediaProperty.Title); Assert.AreEqual(entity.MediaProperty.Url, copyEntity.MediaProperty.Url); Assert.AreEqual(entity.TaxonomyProperty.Id, copyEntity.TaxonomyProperty.Id); Assert.AreEqual(entity.TaxonomyProperty.Label, copyEntity.TaxonomyProperty.Label); Assert.AreEqual(entity.TaxonomyMultiProperty[0].Id, copyEntity.TaxonomyMultiProperty[0].Id); Assert.AreEqual(entity.TaxonomyMultiProperty[0].Label, copyEntity.TaxonomyMultiProperty[0].Label); Assert.AreEqual(entity.TaxonomyMultiProperty[1].Id, copyEntity.TaxonomyMultiProperty[1].Id); Assert.AreEqual(entity.TaxonomyMultiProperty[1].Label, copyEntity.TaxonomyMultiProperty[1].Label); } } }
public void EnsureField_WhenListFieldCollection_AndSiteColumnAlreadyExist_ShouldAddFieldToListAndShouldAvoidModifyingSiteColumn() { using (var testScope = SiteTestScope.BlankSite()) { 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); 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); defaultSiteCollectionTermStore.CommitAll(); var textFieldId = new Guid("{0C58B4A1-B360-47FE-84F7-4D8F58AE80F6}"); TextFieldInfo textFieldInfo = new TextFieldInfo( "TestInternalName", textFieldId, "NameKey", "DescriptionKey", "GroupKey") { MaxLength = 50 }; var taxoFieldId = new Guid("{9708BECA-D3EF-41C3-ABD3-5F1BAC3CE5AE}"); TaxonomyFieldInfo taxoFieldInfo = new TaxonomyFieldInfo( "TestInternalNameTaxo", taxoFieldId, "NameKey", "DescriptionKey", "GroupKey") { TermStoreMapping = new TaxonomyContext(testTermSet) // choices limited to all terms in test term set }; var taxoMultiFieldId = new Guid("{B2517ECF-819E-4F75-88AF-18E926AD30BD}"); TaxonomyMultiFieldInfo taxoMultiFieldInfo = new TaxonomyMultiFieldInfo( "TestInternalNameTaxoMulti", taxoMultiFieldId, "NameKeyMulti", "DescriptionKey", "GroupKey") { // no term store mapping }; ListInfo listInfo = new ListInfo("sometestlistpath", "DynamiteTestListNameKey", "DynamiteTestListDescriptionKey"); using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope()) { // 1) Ensure the fields on the site collection with first version of their definition var siteCollectionFields = testScope.SiteCollection.RootWeb.Fields; IFieldHelper fieldHelper = injectionScope.Resolve<IFieldHelper>(); SPField textSiteColumn = fieldHelper.EnsureField(siteCollectionFields, textFieldInfo); SPField taxoSiteColumn = fieldHelper.EnsureField(siteCollectionFields, taxoFieldInfo); SPField taxoMultiSiteColumn = fieldHelper.EnsureField(siteCollectionFields, taxoMultiFieldInfo); // 2) Change the field definitions slightly textFieldInfo.Required = RequiredType.Required; textFieldInfo.DefaultValue = "SomeDefaultValue"; taxoFieldInfo.TermStoreMapping = new TaxonomyContext(levelOneTermA); // constrain the term to a child term of the term set taxoMultiFieldInfo.TermStoreMapping = new TaxonomyContext(testTermSet); // list column has a mapping, whereas the site column doesn't // 3) Ensure the modified field definitions directly on the list IListHelper listHelper = injectionScope.Resolve<IListHelper>(); SPList list = listHelper.EnsureList(testScope.SiteCollection.RootWeb, listInfo); var listFields = list.Fields; SPField textListColumn = fieldHelper.EnsureField(listFields, textFieldInfo); SPField taxoListColumn = fieldHelper.EnsureField(listFields, taxoFieldInfo); SPField taxoMultiListColumn = fieldHelper.EnsureField(listFields, taxoMultiFieldInfo); // 4) Assert that the site column definitions were not touched list = testScope.SiteCollection.RootWeb.Lists[list.ID]; // Text field var siteText = testScope.SiteCollection.RootWeb.Fields[textFieldInfo.Id]; var listText = list.Fields[textFieldInfo.Id]; Assert.IsFalse(siteText.Required); Assert.IsTrue(string.IsNullOrEmpty(siteText.DefaultValue)); Assert.IsTrue(listText.Required); Assert.AreEqual("SomeDefaultValue", listText.DefaultValue); // Taxo single field var siteTaxo = (TaxonomyField)testScope.SiteCollection.RootWeb.Fields[taxoFieldInfo.Id]; var listTaxo = (TaxonomyField)list.Fields[taxoFieldInfo.Id]; Assert.AreEqual(testTermSet.Id, siteTaxo.TermSetId); Assert.AreEqual(defaultSiteCollectionTermStore.Id, siteTaxo.SspId); Assert.AreEqual(Guid.Empty, siteTaxo.AnchorId); // choices should not be constrained to a child term Assert.IsTrue(siteTaxo.IsTermSetValid); Assert.AreEqual(testTermSet.Id, listTaxo.TermSetId); Assert.AreEqual(defaultSiteCollectionTermStore.Id, listTaxo.SspId); Assert.AreEqual(levelOneTermA.Id, listTaxo.AnchorId); // choices should be constrained to a child term Assert.IsTrue(listTaxo.IsTermSetValid); Assert.IsTrue(listTaxo.IsAnchorValid); // Taxo multi field var siteTaxoMulti = (TaxonomyField)testScope.SiteCollection.RootWeb.Fields[taxoMultiFieldInfo.Id]; var listTaxoMulti = (TaxonomyField)list.Fields[taxoMultiFieldInfo.Id]; Assert.AreEqual(Guid.Empty, siteTaxoMulti.TermSetId); // empty binding on site column Assert.AreEqual(Guid.Empty, siteTaxoMulti.SspId); Assert.AreEqual(Guid.Empty, siteTaxoMulti.AnchorId); Assert.IsFalse(siteTaxoMulti.IsTermSetValid); Assert.AreEqual(testTermSet.Id, listTaxoMulti.TermSetId); Assert.AreEqual(defaultSiteCollectionTermStore.Id, listTaxoMulti.SspId); Assert.AreEqual(Guid.Empty, listTaxoMulti.AnchorId); // choices should not be constrained to a child term Assert.IsTrue(listTaxoMulti.IsTermSetValid); } } }
public void EnsureField_WhenFieldAddedToListWithDefaultValue_NewItemsCreatedOnListShouldHaveDefaultValues() { using (var testScope = SiteTestScope.BlankSite()) { // Arrange IntegerFieldInfo integerFieldInfo = new IntegerFieldInfo( "TestInternalNameInteger", new Guid("{12E262D0-C7C4-4671-A266-064CDBD3905A}"), "NameKeyInt", "DescriptionKeyInt", "GroupKey") { DefaultValue = 555 }; NumberFieldInfo numberFieldInfo = new NumberFieldInfo( "TestInternalNameNumber", new Guid("{5DD4EE0F-8498-4033-97D0-317A24988786}"), "NameKeyNumber", "DescriptionKeyNumber", "GroupKey") { DefaultValue = 5.5 }; CurrencyFieldInfo currencyFieldInfo = new CurrencyFieldInfo( "TestInternalNameCurrency", new Guid("{9E9963F6-1EE6-46FB-9599-783BBF4D6249}"), "NameKeyCurrency", "DescriptionKeyCurrency", "GroupKey") { DefaultValue = 500.95, LocaleId = 3084 // fr-CA }; 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") { DefaultValue = new DateTime(2005, 10, 21) }; TextFieldInfo textFieldInfo = new TextFieldInfo( "TestInternalNameText", new Guid("{0C58B4A1-B360-47FE-84F7-4D8F58AE80F6}"), "NameKey", "DescriptionKey", "GroupKey") { DefaultValue = "Text default value" }; NoteFieldInfo noteFieldInfo = new NoteFieldInfo( "TestInternalNameNote", new Guid("{E315BB24-19C3-4F2E-AABC-9DE5EFC3D5C2}"), "NameKeyAlt", "DescriptionKeyAlt", "GroupKey") { DefaultValue = "Note default value" }; HtmlFieldInfo htmlFieldInfo = new HtmlFieldInfo( "TestInternalNameHtml", new Guid("{D16958E7-CF9A-4C38-A8BB-99FC03BFD913}"), "NameKeyAlt", "DescriptionKeyAlt", "GroupKey") { DefaultValue = "<p class=\"some-css-class\">HTML default value</p>" }; ImageFieldInfo imageFieldInfo = new ImageFieldInfo( "TestInternalNameImage", new Guid("{6C5B9E77-B621-43AA-BFBF-B333093EFCAE}"), "NameKeyImage", "DescriptionKeyImage", "GroupKey") { DefaultValue = new ImageValue() { Hyperlink = "http://github.com/GSoft-SharePoint/", ImageUrl = "/_layouts/15/MyFolder/MyImage.png" } }; UrlFieldInfo urlFieldInfo = new UrlFieldInfo( "TestInternalNameUrl", new Guid("{208F904C-5A1C-4E22-9A79-70B294FABFDA}"), "NameKeyUrl", "DescriptionKeyUrl", "GroupKey") { DefaultValue = new UrlValue() { Url = "http://github.com/GSoft-SharePoint/", Description = "patate!" } }; UrlFieldInfo urlFieldInfoImage = new UrlFieldInfo( "TestInternalNameUrlImg", new Guid("{96D22CFF-5B40-4675-B632-28567792E11B}"), "NameKeyUrlImg", "DescriptionKeyUrlImg", "GroupKey") { Format = UrlFieldFormat.Image, DefaultValue = new UrlValue() { Url = "http://github.com/GSoft-SharePoint/", Description = "patate!" } }; LookupFieldInfo lookupFieldInfo = new LookupFieldInfo( "TestInternalNameLookup", new Guid("{62F8127C-4A8C-4217-8BD8-C6712753AFCE}"), "NameKey", "DescriptionKey", "GroupKey") { // ShowField should be Title by default DefaultValue = new LookupValue(1, "Test Item 1") }; LookupFieldInfo lookupFieldInfoAlt = new LookupFieldInfo( "TestInternalNameLookupAlt", new Guid("{1F05DFFA-6396-4AEF-AD23-72217206D35E}"), "NameKey", "DescriptionKey", "GroupKey") { ShowField = "ID", DefaultValue = new LookupValue(2, "2") }; LookupMultiFieldInfo lookupMultiFieldInfo = new LookupMultiFieldInfo( "TestInternalNameLookupM", new Guid("{2C9D4C0E-21EB-4742-8C6C-4C30DCD08A05}"), "NameKeyMulti", "DescriptionKeyMulti", "GroupKey") { DefaultValue = new LookupValueCollection() { new LookupValue(1, "Test Item 1"), new LookupValue(2, "Test Item 2") } }; 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") { DefaultValue = new UserValue(ensuredUser1) }; UserMultiFieldInfo userMultiFieldInfo = new UserMultiFieldInfo( "TestInternalNameUserMulti", new Guid("{8C662588-D54E-4905-B232-856C2239B036}"), "NameKeyUserMulti", "DescriptionKeyUserMulti", "GroupKey") { DefaultValue = new UserValueCollection() { new UserValue(ensuredUser1), new UserValue(ensuredUser2) } }; MediaFieldInfo mediaFieldInfo = new MediaFieldInfo( "TestInternalNameMedia", new Guid("{A2F070FE-FE33-44FC-9FDF-D18E74ED4D67}"), "NameKeyMedia", "DescriptionKeyMEdia", "GroupKey") { DefaultValue = 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" } }; 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") { DefaultValue = new TaxonomyValue(levelOneTermB), 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") { DefaultValue = new TaxonomyValueCollection( new List<TaxonomyValue>() { new TaxonomyValue(levelTwoTermAA), new TaxonomyValue(levelTwoTermAB) }), 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 listInfo1 = new ListInfo("sometestlistpath", "DynamiteTestListNameKey", "DynamiteTestListDescriptionKey"); ListInfo listInfo2 = new ListInfo("sometestlistpathalt", "DynamiteTestListNameKeyAlt", "DynamiteTestListDescriptionKeyAlt") { FieldDefinitions = fieldsToEnsure }; using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope()) { 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 list1 = listHelper.EnsureList(testScope.SiteCollection.RootWeb, listInfo1); var fieldHelper = injectionScope.Resolve<IFieldHelper>(); // we need to ensure all fields on first list directly IList<SPField> ensuredFieldsOnList1 = fieldHelper.EnsureField(list1.Fields, fieldsToEnsure).ToList(); // second ListInfo object holds its own field definitions (which should be ensured at same time as list through listHelper) SPList list2 = listHelper.EnsureList(testScope.SiteCollection.RootWeb, listInfo2); // Act var itemOnList1 = list1.AddItem(); itemOnList1.Update(); var itemOnList2 = list2.AddItem(); itemOnList2.Update(); // Assert // List item #1 (fields on list ensured via FieldHelper.EnsureField) Assert.AreEqual(555, itemOnList1["TestInternalNameInteger"]); Assert.AreEqual(5.5, itemOnList1["TestInternalNameNumber"]); Assert.AreEqual(500.95, itemOnList1["TestInternalNameCurrency"]); Assert.IsNull(itemOnList1["TestInternalNameBool"]); Assert.IsTrue((bool)itemOnList1["TestInternalNameBoolTrue"]); Assert.IsFalse((bool)itemOnList1["TestInternalNameBoolFalse"]); Assert.AreEqual(DateTime.Today, itemOnList1["TestInternalNameDateFormula"]); Assert.AreEqual(new DateTime(2005, 10, 21), itemOnList1["TestInternalNameDateDefault"]); Assert.AreEqual("Text default value", itemOnList1["TestInternalNameText"]); Assert.AreEqual("Note default value", itemOnList1["TestInternalNameNote"]); Assert.AreEqual("<p class=\"some-css-class\">HTML default value</p>", itemOnList1["TestInternalNameHtml"]); var imageFieldVal = (ImageFieldValue)itemOnList1["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(itemOnList1["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 var urlImageFieldVal = new SPFieldUrlValue(itemOnList1["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 var lookupFieldVal = new SPFieldLookupValue(itemOnList1["TestInternalNameLookup"].ToString()); Assert.AreEqual(1, lookupFieldVal.LookupId); Assert.AreEqual("Test Item 1", lookupFieldVal.LookupValue); var lookupAltFieldVal = new SPFieldLookupValue(itemOnList1["TestInternalNameLookupAlt"].ToString()); Assert.AreEqual(2, lookupAltFieldVal.LookupId); Assert.AreEqual("2", lookupAltFieldVal.LookupValue); // ShowField/LookupField is ID var lookupMultiFieldVal = new SPFieldLookupValueCollection(itemOnList1["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, itemOnList1["TestInternalNameUser"].ToString()); Assert.AreEqual(ensuredUser1.Name, userFieldVal.User.Name); var userMultiFieldVal = new SPFieldUserValueCollection(testScope.SiteCollection.RootWeb, itemOnList1["TestInternalNameUserMulti"].ToString()); Assert.AreEqual(ensuredUser1.Name, userMultiFieldVal[0].User.Name); Assert.AreEqual("Maxime Boissonneault", userMultiFieldVal[1].User.Name); var mediaFieldVal = MediaFieldValue.FromString(itemOnList1["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)itemOnList1["TestInternalNameTaxo"]; Assert.AreNotEqual(-1, taxoFieldValue.WssId); Assert.AreEqual(levelOneTermB.Id, new Guid(taxoFieldValue.TermGuid)); Assert.AreEqual(levelOneTermB.Label, taxoFieldValue.Label); var taxoFieldValueMulti = (TaxonomyFieldValueCollection)itemOnList1["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); // List item #2 (fields on list ensured via ListHelper.EnsureList) Assert.AreEqual(555, itemOnList2["TestInternalNameInteger"]); Assert.AreEqual(5.5, itemOnList2["TestInternalNameNumber"]); Assert.AreEqual(500.95, itemOnList2["TestInternalNameCurrency"]); Assert.IsNull(itemOnList2["TestInternalNameBool"]); Assert.IsTrue((bool)itemOnList2["TestInternalNameBoolTrue"]); Assert.IsFalse((bool)itemOnList2["TestInternalNameBoolFalse"]); Assert.AreEqual(DateTime.Today, itemOnList2["TestInternalNameDateFormula"]); Assert.AreEqual(new DateTime(2005, 10, 21), itemOnList2["TestInternalNameDateDefault"]); Assert.AreEqual("Text default value", itemOnList2["TestInternalNameText"]); Assert.AreEqual("Note default value", itemOnList2["TestInternalNameNote"]); Assert.AreEqual("<p class=\"some-css-class\">HTML default value</p>", itemOnList2["TestInternalNameHtml"]); imageFieldVal = (ImageFieldValue)itemOnList2["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(itemOnList2["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(itemOnList2["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(itemOnList2["TestInternalNameLookup"].ToString()); Assert.AreEqual(1, lookupFieldVal.LookupId); Assert.AreEqual("Test Item 1", lookupFieldVal.LookupValue); lookupAltFieldVal = new SPFieldLookupValue(itemOnList2["TestInternalNameLookupAlt"].ToString()); Assert.AreEqual(2, lookupAltFieldVal.LookupId); Assert.AreEqual("2", lookupAltFieldVal.LookupValue); // ShowField/LookupField is ID lookupMultiFieldVal = new SPFieldLookupValueCollection(itemOnList2["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, itemOnList2["TestInternalNameUser"].ToString()); Assert.AreEqual(ensuredUser1.Name, userFieldVal.User.Name); userMultiFieldVal = new SPFieldUserValueCollection(testScope.SiteCollection.RootWeb, itemOnList2["TestInternalNameUserMulti"].ToString()); Assert.AreEqual(ensuredUser1.Name, userMultiFieldVal[0].User.Name); Assert.AreEqual("Maxime Boissonneault", userMultiFieldVal[1].User.Name); mediaFieldVal = MediaFieldValue.FromString(itemOnList2["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)itemOnList2["TestInternalNameTaxo"]; Assert.AreNotEqual(-1, taxoFieldValue.WssId); Assert.AreEqual(levelOneTermB.Id, new Guid(taxoFieldValue.TermGuid)); Assert.AreEqual(levelOneTermB.Label, taxoFieldValue.Label); taxoFieldValueMulti = (TaxonomyFieldValueCollection)itemOnList2["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(); } }
public void EnsureField_WhenEnsuringListColumnWithEnforceUniqueValue_AndFieldInfoIsSupportedFieldType_ShouldInitializeFieldToEnforceUniqueness_AndForceIndexation() { using (var testScope = SiteTestScope.BlankSite()) { // Arrange IntegerFieldInfo integerFieldInfo = new IntegerFieldInfo( "TestInternalNameInteger", new Guid("{12E262D0-C7C4-4671-A266-064CDBD3905A}"), "NameKeyInt", "DescriptionKeyInt", "GroupKey") { EnforceUniqueValues = true }; NumberFieldInfo numberFieldInfo = new NumberFieldInfo( "TestInternalNameNumber", new Guid("{5DD4EE0F-8498-4033-97D0-317A24988786}"), "NameKeyNumber", "DescriptionKeyNumber", "GroupKey") { EnforceUniqueValues = true }; CurrencyFieldInfo currencyFieldInfo = new CurrencyFieldInfo( "TestInternalNameCurrency", new Guid("{9E9963F6-1EE6-46FB-9599-783BBF4D6249}"), "NameKeyCurrency", "DescriptionKeyCurrency", "GroupKey") { EnforceUniqueValues = true, LocaleId = 3084 // fr-CA }; DateTimeFieldInfo dateTimeFieldInfo = new DateTimeFieldInfo( "TestInternalNameDate", new Guid("{016BF8D9-CEDC-4BF4-BA21-AC6A8F174AD5}"), "NameKeyDateTime", "DescriptionKeyDateTime", "GroupKey") { EnforceUniqueValues = true }; TextFieldInfo textFieldInfo = new TextFieldInfo( "TestInternalNameText", new Guid("{0C58B4A1-B360-47FE-84F7-4D8F58AE80F6}"), "NameKey", "DescriptionKey", "GroupKey") { EnforceUniqueValues = true }; var ensuredUser1 = testScope.SiteCollection.RootWeb.EnsureUser(Environment.UserDomainName + "\\" + Environment.UserName); UserFieldInfo userFieldInfo = new UserFieldInfo( "TestInternalNameUser", new Guid("{5B74DD50-0D2D-4D24-95AF-0C4B8AA3F68A}"), "NameKeyUser", "DescriptionKeyUser", "GroupKey") { EnforceUniqueValues = true }; LookupFieldInfo lookupFieldInfo = new LookupFieldInfo( "TestInternalNameLookup", new Guid("{62F8127C-4A8C-4217-8BD8-C6712753AFCE}"), "NameKey", "DescriptionKey", "GroupKey") { EnforceUniqueValues = true }; 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") { EnforceUniqueValues = true, TermStoreMapping = new TaxonomyContext(testTermSet) // choices limited to all terms in test term set }; var fieldsToEnsure = new List<BaseFieldInfo>() { integerFieldInfo, numberFieldInfo, currencyFieldInfo, dateTimeFieldInfo, textFieldInfo, userFieldInfo, lookupFieldInfo, taxoFieldInfo, }; ListInfo lookupListInfo = new ListInfo("sometestlistpathlookup", "DynamiteTestListNameKeyLookup", "DynamiteTestListDescriptionKeyLookup"); ListInfo listInfo1 = new ListInfo("sometestlistpath", "DynamiteTestListNameKey", "DynamiteTestListDescriptionKey") { FieldDefinitions = fieldsToEnsure }; using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope()) { var listHelper = injectionScope.Resolve<IListHelper>(); // Lookup field ListId setup SPList lookupList = listHelper.EnsureList(testScope.SiteCollection.RootWeb, lookupListInfo); lookupFieldInfo.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 test list (which should provision both site columns and list columns) SPList list = listHelper.EnsureList(testScope.SiteCollection.RootWeb, listInfo1); // Act var originalItemWithUniqueValues = list.AddItem(); originalItemWithUniqueValues["TestInternalNameInteger"] = 555; originalItemWithUniqueValues["TestInternalNameNumber"] = 5.5; originalItemWithUniqueValues["TestInternalNameCurrency"] = 500.95; originalItemWithUniqueValues["TestInternalNameDate"] = new DateTime(2005, 10, 21); originalItemWithUniqueValues["TestInternalNameText"] = "Text value"; originalItemWithUniqueValues["TestInternalNameLookup"] = new SPFieldLookupValue(1, "Test Item 1"); originalItemWithUniqueValues["TestInternalNameUser"] = new SPFieldUserValue(testScope.SiteCollection.RootWeb, ensuredUser1.ID, ensuredUser1.Name); var taxonomyField = (TaxonomyField)originalItemWithUniqueValues.Fields.GetFieldByInternalName("TestInternalNameTaxo"); taxonomyField.SetFieldValue(originalItemWithUniqueValues, createdTermB); originalItemWithUniqueValues.Update(); // Assert Assert.IsTrue(list.Fields.GetFieldByInternalName("TestInternalNameInteger").Indexed); try { var uniquenessBreakingItem = list.AddItem(); uniquenessBreakingItem["TestInternalNameInteger"] = 555; uniquenessBreakingItem.Update(); Assert.Fail("Should've thrown SPException because values should be unique on this Integer field"); } catch (SPException) { } Assert.IsTrue(list.Fields.GetFieldByInternalName("TestInternalNameNumber").Indexed); try { var uniquenessBreakingItem = list.AddItem(); uniquenessBreakingItem["TestInternalNameNumber"] = 5.5; uniquenessBreakingItem.Update(); Assert.Fail("Should've thrown SPException because values should be unique on this Number field"); } catch (SPException) { } Assert.IsTrue(list.Fields.GetFieldByInternalName("TestInternalNameCurrency").Indexed); try { var uniquenessBreakingItem = list.AddItem(); uniquenessBreakingItem["TestInternalNameCurrency"] = 500.95; uniquenessBreakingItem.Update(); Assert.Fail("Should've thrown SPException because values should be unique on this Currency field"); } catch (SPException) { } Assert.IsTrue(list.Fields.GetFieldByInternalName("TestInternalNameDate").Indexed); try { var uniquenessBreakingItem = list.AddItem(); uniquenessBreakingItem["TestInternalNameDate"] = new DateTime(2005, 10, 21); uniquenessBreakingItem.Update(); Assert.Fail("Should've thrown SPException because values should be unique on this DateTime field"); } catch (SPException) { } Assert.IsTrue(list.Fields.GetFieldByInternalName("TestInternalNameText").Indexed); try { var uniquenessBreakingItem = list.AddItem(); uniquenessBreakingItem["TestInternalNameText"] = "Text value"; uniquenessBreakingItem.Update(); Assert.Fail("Should've thrown SPException because values should be unique on this Text field"); } catch (SPException) { } Assert.IsTrue(list.Fields.GetFieldByInternalName("TestInternalNameLookup").Indexed); try { var uniquenessBreakingItem = list.AddItem(); uniquenessBreakingItem["TestInternalNameLookup"] = new SPFieldLookupValue(1, "Test Item 1"); uniquenessBreakingItem.Update(); Assert.Fail("Should've thrown SPException because values should be unique on this Lookup field"); } catch (SPException) { } Assert.IsTrue(list.Fields.GetFieldByInternalName("TestInternalNameUser").Indexed); try { var uniquenessBreakingItem = list.AddItem(); uniquenessBreakingItem["TestInternalNameUser"] = new SPFieldUserValue(testScope.SiteCollection.RootWeb, ensuredUser1.ID, ensuredUser1.Name); uniquenessBreakingItem.Update(); Assert.Fail("Should've thrown SPException because values should be unique on this User field"); } catch (SPException) { } Assert.IsTrue(list.Fields.GetFieldByInternalName("TestInternalNameTaxo").Indexed); try { var uniquenessBreakingItem = list.AddItem(); taxonomyField = (TaxonomyField)uniquenessBreakingItem.Fields.GetFieldByInternalName("TestInternalNameTaxo"); taxonomyField.SetFieldValue(uniquenessBreakingItem, createdTermB); uniquenessBreakingItem.Update(); Assert.Fail("Should've thrown SPException because values should be unique on this Taxonomy field"); } catch (SPException) { } } // Cleanup term set so that we don't pollute the metadata store newTermSet.Delete(); defaultSiteCollectionTermStore.CommitAll(); } }
public void EnsureField_WhenEnsuringAMinimalFieldInfoOOTBColumnAsFieldOnList_ShouldMakeFieldAvailableOnList() { using (var testScope = SiteTestScope.BlankSite()) { // Arrange ListInfo listInfo = new ListInfo("somelistpath", "ListNameKey", "ListDescrKey") { FieldDefinitions = new List<BaseFieldInfo>() { BuiltInFields.AssignedTo, // OOTB User field BuiltInFields.Cellphone, // OOTB Text field } }; using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope()) { IListHelper listHelper = injectionScope.Resolve<IListHelper>(); IFieldHelper fieldHelper = injectionScope.Resolve<IFieldHelper>(); // Act (ensure fields on list through both listHelper and fieldHelper) SPList list = listHelper.EnsureList(testScope.SiteCollection.RootWeb, listInfo); SPField field = fieldHelper.EnsureField(list.Fields, BuiltInFields.EnterpriseKeywords); // OOTB Taxonomy Multi field // Assert Assert.IsNotNull(list.Fields[BuiltInFields.AssignedTo.Id]); Assert.IsNotNull(list.Fields[BuiltInFields.Cellphone.Id]); Assert.IsNotNull(list.Fields[BuiltInFields.EnterpriseKeywords.Id]); // Use the a list and create an item just for kicks SPListItem item = list.AddItem(); item.Update(); var ensuredUser1 = testScope.SiteCollection.RootWeb.EnsureUser(Environment.UserName); IFieldValueWriter writer = injectionScope.Resolve<IFieldValueWriter>(); writer.WriteValuesToListItem( item, new List<FieldValueInfo>() { new FieldValueInfo(BuiltInFields.AssignedTo, new UserValue(ensuredUser1)), new FieldValueInfo(BuiltInFields.Cellphone, "Test Cellphone Value"), new FieldValueInfo(BuiltInFields.EnterpriseKeywords, new TaxonomyValueCollection()) }); item.Update(); Assert.IsNotNull(item[BuiltInFields.AssignedTo.Id]); Assert.IsNotNull(item[BuiltInFields.Cellphone.Id]); Assert.IsNotNull(item[BuiltInFields.EnterpriseKeywords.Id]); } } }
public void EnsureField_WhenEnsuringAMinimalFieldInfoOOTBColumnAsFieldOnList_AndOOTBSiteColumnIsNOTAvailable_ShouldFailBecauseSuchOOTBSiteColumnShouldBeAddedByOOTBFeatures() { using (var testScope = SiteTestScope.BlankSite()) { // Arrange ListInfo listInfo = new ListInfo("somelistpath", "ListNameKey", "ListDescrKey") { FieldDefinitions = new List<BaseFieldInfo>() { PublishingFields.PublishingPageContent // Should be missing from site columns (only available in Publishing sites) } }; using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope()) { IListHelper listHelper = injectionScope.Resolve<IListHelper>(); IFieldHelper fieldHelper = injectionScope.Resolve<IFieldHelper>(); SPList list = null; // Act try { // Field ensured through ListHelper->FieldHelper list = listHelper.EnsureList(testScope.SiteCollection.RootWeb, listInfo); Assert.Fail("Should've thrown NotSupportedException because pre-requisite site column doesn't exist on RootWeb."); } catch (NotSupportedException) { } try { listInfo.FieldDefinitions.Clear(); list = listHelper.EnsureList(testScope.SiteCollection.RootWeb, listInfo); // Field ensured through FieldHelper only fieldHelper.EnsureField(list.Fields, PublishingFields.PublishingPageContent); Assert.Fail("Should've thrown NotSupportedException because pre-requisite site column doesn't exist on RootWeb."); } catch (NotSupportedException) { } } } }
/// <summary> /// Gets the metadata navigation settings information by list information from this configuration. /// </summary> /// <param name="list">The list information.</param> /// <returns> /// The Managed navigation settings /// </returns> public MetadataNavigationSettingsInfo GetMetadataNavigationSettingsInfo(ListInfo list) { return this.MetadataNavigationSettings.Single(s => s.List.WebRelativeUrl.Equals(list.WebRelativeUrl)); }
public void EnsureField_WhenAttemptingToSetEnforceUniqueValue_ButFieldTypeDoesntSupportUniqueness_ShouldThrowNotSupportedException() { using (var testScope = SiteTestScope.BlankSite()) { // Arrange BooleanFieldInfo boolFieldInfoBasic = new BooleanFieldInfo( "TestInternalNameBool", new Guid("{F556AB6B-9E51-43E2-99C9-4A4E551A4BEF}"), "NameKeyBool", "DescriptionKeyBool", "GroupKey") { EnforceUniqueValues = true }; GuidFieldInfo guidFieldInfo = new GuidFieldInfo( "TestInternalNameGuid", new Guid("{7F486426-D3BC-48D8-8E28-85CFC9A457A0}"), "NameKeyGuid", "DescriptionKeyGuid", "GroupKey") { EnforceUniqueValues = true }; NoteFieldInfo noteFieldInfo = new NoteFieldInfo( "TestInternalNameNote", new Guid("{E315BB24-19C3-4F2E-AABC-9DE5EFC3D5C2}"), "NameKeyAlt", "DescriptionKeyAlt", "GroupKey") { EnforceUniqueValues = true }; HtmlFieldInfo htmlFieldInfo = new HtmlFieldInfo( "TestInternalNameHtml", new Guid("{D16958E7-CF9A-4C38-A8BB-99FC03BFD913}"), "NameKeyAlt", "DescriptionKeyAlt", "GroupKey") { EnforceUniqueValues = true }; ImageFieldInfo imageFieldInfo = new ImageFieldInfo( "TestInternalNameImage", new Guid("{6C5B9E77-B621-43AA-BFBF-B333093EFCAE}"), "NameKeyImage", "DescriptionKeyImage", "GroupKey") { EnforceUniqueValues = true }; UrlFieldInfo urlFieldInfo = new UrlFieldInfo( "TestInternalNameUrl", new Guid("{208F904C-5A1C-4E22-9A79-70B294FABFDA}"), "NameKeyUrl", "DescriptionKeyUrl", "GroupKey") { EnforceUniqueValues = true }; UrlFieldInfo urlFieldInfoImage = new UrlFieldInfo( "TestInternalNameUrlImg", new Guid("{96D22CFF-5B40-4675-B632-28567792E11B}"), "NameKeyUrlImg", "DescriptionKeyUrlImg", "GroupKey") { Format = UrlFieldFormat.Image, EnforceUniqueValues = true }; LookupMultiFieldInfo lookupMultiFieldInfo = new LookupMultiFieldInfo( "TestInternalNameLookupM", new Guid("{2C9D4C0E-21EB-4742-8C6C-4C30DCD08A05}"), "NameKeyMulti", "DescriptionKeyMulti", "GroupKey") { EnforceUniqueValues = true }; var ensuredUser1 = testScope.SiteCollection.RootWeb.EnsureUser(Environment.UserDomainName + "\\" + Environment.UserName); var ensuredUser2 = testScope.SiteCollection.RootWeb.EnsureUser("OFFICE\\maxime.boissonneault"); UserMultiFieldInfo userMultiFieldInfo = new UserMultiFieldInfo( "TestInternalNameUserMulti", new Guid("{8C662588-D54E-4905-B232-856C2239B036}"), "NameKeyUserMulti", "DescriptionKeyUserMulti", "GroupKey") { EnforceUniqueValues = true }; MediaFieldInfo mediaFieldInfo = new MediaFieldInfo( "TestInternalNameMedia", new Guid("{A2F070FE-FE33-44FC-9FDF-D18E74ED4D67}"), "NameKeyMedia", "DescriptionKeyMEdia", "GroupKey") { EnforceUniqueValues = true }; 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(); TaxonomyMultiFieldInfo taxoMultiFieldInfo = new TaxonomyMultiFieldInfo( "TestInternalNameTaxoMulti", new Guid("{2F49D362-B014-41BB-9959-1000C9A7FFA0}"), "NameKeyMulti", "DescriptionKey", "GroupKey") { EnforceUniqueValues = true, TermStoreMapping = new TaxonomyContext(levelOneTermA) // choices limited to children of a specific term, instead of having full term set choices }; ListInfo lookupListInfo = new ListInfo("sometestlistpathlookup", "DynamiteTestListNameKeyLookup", "DynamiteTestListDescriptionKeyLookup"); ListInfo listInfo = new ListInfo("sometestlistpathalt", "DynamiteTestListNameKeyAlt", "DynamiteTestListDescriptionKeyAlt"); using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope()) { var fieldHelper = injectionScope.Resolve<IFieldHelper>(); var listHelper = injectionScope.Resolve<IListHelper>(); // Lookup field ListId setup SPList lookupList = listHelper.EnsureList(testScope.SiteCollection.RootWeb, lookupListInfo); 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 test list (which should provision both site columns and list columns) SPList list = listHelper.EnsureList(testScope.SiteCollection.RootWeb, listInfo); // Act + Assert try { fieldHelper.EnsureField(list.Fields, boolFieldInfoBasic); Assert.Fail("Should've thrown NotSupportedException because Boolean fields don't support EnforceUniqueValues."); } catch (NotSupportedException) { } try { fieldHelper.EnsureField(list.Fields, guidFieldInfo); Assert.Fail("Should've thrown NotSupportedException because Guid fields don't support EnforceUniqueValues."); } catch (NotSupportedException) { } try { fieldHelper.EnsureField(list.Fields, noteFieldInfo); Assert.Fail("Should've thrown NotSupportedException because Note fields don't support EnforceUniqueValues."); } catch (NotSupportedException) { } try { fieldHelper.EnsureField(list.Fields, htmlFieldInfo); Assert.Fail("Should've thrown NotSupportedException because Html fields don't support EnforceUniqueValues."); } catch (NotSupportedException) { } try { fieldHelper.EnsureField(list.Fields, imageFieldInfo); Assert.Fail("Should've thrown NotSupportedException because Image fields don't support EnforceUniqueValues."); } catch (NotSupportedException) { } try { fieldHelper.EnsureField(list.Fields, urlFieldInfo); Assert.Fail("Should've thrown NotSupportedException because URL fields don't support EnforceUniqueValues."); } catch (NotSupportedException) { } try { fieldHelper.EnsureField(list.Fields, urlFieldInfoImage); Assert.Fail("Should've thrown NotSupportedException because URL-Image fields don't support EnforceUniqueValues."); } catch (NotSupportedException) { } try { fieldHelper.EnsureField(list.Fields, lookupMultiFieldInfo); Assert.Fail("Should've thrown NotSupportedException because LookupMulti fields don't support EnforceUniqueValues."); } catch (NotSupportedException) { } try { fieldHelper.EnsureField(list.Fields, userMultiFieldInfo); Assert.Fail("Should've thrown NotSupportedException because UserMulti fields don't support EnforceUniqueValues."); } catch (NotSupportedException) { } try { fieldHelper.EnsureField(list.Fields, mediaFieldInfo); Assert.Fail("Should've thrown NotSupportedException because Media fields don't support EnforceUniqueValues."); } catch (NotSupportedException) { } try { fieldHelper.EnsureField(list.Fields, taxoMultiFieldInfo); Assert.Fail("Should've thrown NotSupportedException because TaxoMulti fields don't support EnforceUniqueValues."); } catch (NotSupportedException) { } } } }
public void ToEntity_WhenAllValuesInListItemAreNull_AndEntityTypeHasNullablePrimitiveValues_ShouldInitializeEntityWithEmptyNullable() { 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"); DateTimeFieldInfo dateTimeFieldInfo = new DateTimeFieldInfo( "TestInternalNameDate", new Guid("{016BF8D9-CEDC-4BF4-BA21-AC6A8F174AD5}"), "NameKeyDateTimeDefault", "DescriptionKeyDateTimeDefault", "GroupKey"); GuidFieldInfo guidFieldInfo = new GuidFieldInfo( "TestInternalNameGuid", new Guid("{308C0899-DDBE-44EE-A8A8-226F7A6A7C89}"), "NameKeyGuid", "DescriptionKeyGuid", "GroupKey"); var fieldsToEnsure = new List<BaseFieldInfo>() { integerFieldInfo, numberFieldInfo, currencyFieldInfo, boolFieldInfoBasic, dateTimeFieldInfo, guidFieldInfo }; 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>(); // Create the test list SPList list = listHelper.EnsureList(testScope.SiteCollection.RootWeb, listInfo); list.EnableVersioning = true; list.Update(); // Create an empty item var itemOnList = list.AddItem(); itemOnList.Update(); // Act var entityBinder = injectionScope.Resolve<ISharePointEntityBinder>(); var entityMappedFromSingleItem = new TestItemEntityWithNullablePrimitivesOnly(); var entityMappedFromItemVersion = new TestItemEntityWithNullablePrimitivesOnly(); // Act // Map from SPListItem entityBinder.ToEntity<TestItemEntityWithNullablePrimitivesOnly>(entityMappedFromSingleItem, itemOnList); // Map from SPListItemVersion entityBinder.ToEntity<TestItemEntityWithNullablePrimitivesOnly>(entityMappedFromItemVersion, itemOnList.Versions[0]); // Map from DataRow/SPListItemCollection var entitiesMappedFromItemCollection = entityBinder.Get<TestItemEntityWithNullablePrimitivesOnly>(list.Items); // Assert // #1 Check SPListItem-mapped values Assert.IsFalse(entityMappedFromSingleItem.IntegerProperty.HasValue); Assert.IsFalse(entityMappedFromSingleItem.DoubleProperty.HasValue); Assert.IsFalse(entityMappedFromSingleItem.CurrencyProperty.HasValue); Assert.IsFalse(entityMappedFromSingleItem.BoolProperty.HasValue); Assert.IsFalse(entityMappedFromSingleItem.DateTimeProperty.HasValue); Assert.IsFalse(entityMappedFromSingleItem.GuidProperty.HasValue); // #2 Check SPListItemVersion-mapped values Assert.IsFalse(entityMappedFromItemVersion.IntegerProperty.HasValue); Assert.IsFalse(entityMappedFromItemVersion.DoubleProperty.HasValue); Assert.IsFalse(entityMappedFromItemVersion.CurrencyProperty.HasValue); Assert.IsFalse(entityMappedFromItemVersion.BoolProperty.HasValue); Assert.IsFalse(entityMappedFromItemVersion.DateTimeProperty.HasValue); Assert.IsFalse(entityMappedFromItemVersion.GuidProperty.HasValue); // #1 Check SPListItemCollection/DataRow-mapped values // Note that the DataRow item conversion prevents us from distinguishing // empty integer value from 0. Assert.AreEqual(0, entitiesMappedFromItemCollection[0].IntegerProperty); Assert.IsFalse(entitiesMappedFromItemCollection[0].DoubleProperty.HasValue); Assert.IsFalse(entitiesMappedFromItemCollection[0].CurrencyProperty.HasValue); Assert.IsFalse(entitiesMappedFromItemCollection[0].BoolProperty.HasValue); Assert.IsFalse(entitiesMappedFromItemCollection[0].DateTimeProperty.HasValue); Assert.IsFalse(entitiesMappedFromItemCollection[0].GuidProperty.HasValue); } } }
public void EnsureList_WhenEnsuringAnExistingListAndWithAWriteSecuritySpecified_ItShouldUpdateTheListWithTheRightPermission() { // Arrange const string Url = "testUrl"; var listInfo = new ListInfo(Url, "NameKey", "DescriptionKey"); using (var testScope = SiteTestScope.BlankSite()) { var rootWeb = testScope.SiteCollection.RootWeb; using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope()) { var listHelper = injectionScope.Resolve<IListHelper>(); var list = listHelper.EnsureList(rootWeb, listInfo); var numberOfListsBeforeUpdate = rootWeb.Lists.Count; // Nobody = 4 listInfo.WriteSecurity = WriteSecurityOptions.Nobody; // Act var updatedList = listHelper.EnsureList(rootWeb, listInfo); // Assert Assert.AreEqual(listInfo.DisplayNameResourceKey, updatedList.TitleResource.Value); updatedList = rootWeb.GetList(Url); Assert.IsNotNull(updatedList); Assert.AreEqual(numberOfListsBeforeUpdate, rootWeb.Lists.Count); Assert.AreEqual(updatedList.WriteSecurity, 4); } } }
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(); } }
/// <summary> /// Method to find a list with the ListInfo /// </summary> /// <param name="web">The Web where to find the list</param> /// <param name="listInfo">The ListInfo of the list to locate</param> /// <returns>A SharePoint SPList</returns> public SPList TryGetList(SPWeb web, ListInfo listInfo) { return(this.TryGetList(web, listInfo.WebRelativeUrl.ToString())); }
/// <summary> /// Actually creates a list in SharePoint. For internal use in this class only. /// </summary> /// <param name="web">The current web</param> /// <param name="listInfo">The list information contains all the necessary data to create the list</param> /// <returns>The created List</returns> private SPList CreateList(SPWeb web, ListInfo listInfo) { // Throw an exception if the proposed web-relative URL conflicts with an existing subsite/folder URL or a managed path Guid id; try { var title = this.resourceLocator.GetResourceString(listInfo.ResourceFileName, listInfo.DisplayNameResourceKey); var description = this.resourceLocator.GetResourceString(listInfo.ResourceFileName, listInfo.DescriptionResourceKey); id = web.Lists.Add( title, description, listInfo.WebRelativeUrl.ToString(), listInfo.ListTemplateInfo.FeatureId.ToString(), listInfo.ListTemplateInfo.ListTempateTypeId, null); } catch (SPException sharepointException) { var messageFormat = "The web-relative URL '{0}' for the ensured list conflicts with an existing URL " + "(subweb, folder, ...). Try with a different one."; throw new ArgumentException( string.Format(CultureInfo.InvariantCulture, messageFormat, listInfo.WebRelativeUrl), sharepointException); } return web.Lists[id]; }
public void EnsureField_WhenSubWebFieldCollection_AndSiteColumnAlreadyExist_ShouldThrowExceptionToShowHowImpossibleThisIs() { using (var testScope = SiteTestScope.BlankSite()) { var fieldId = new Guid("{0C58B4A1-B360-47FE-84F7-4D8F58AE80F6}"); TextFieldInfo textFieldInfo = new TextFieldInfo( "TestInternalName", fieldId, "NameKey", "DescriptionKey", "GroupKey") { MaxLength = 50, Required = RequiredType.Required }; ListInfo listInfo = new ListInfo("sometestlistpath", "DynamiteTestListNameKey", "DynamiteTestListDescriptionKey"); using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope()) { SPWeb subWeb = testScope.SiteCollection.RootWeb.Webs.Add("subweb"); IFieldHelper fieldHelper = injectionScope.Resolve<IFieldHelper>(); var rootWebFields = testScope.SiteCollection.RootWeb.Fields; var subWebFields = subWeb.Fields; SPField field = fieldHelper.EnsureField(rootWebFields, textFieldInfo); textFieldInfo.Required = RequiredType.NotRequired; // Act + Assert // Should be impossible to re-define a field that already exists on root web SPField sameSubWebFieldShouldThrowException = fieldHelper.EnsureField(subWebFields, textFieldInfo); } } }
public void EnsureField_WhenListFieldCollection_AndSiteColumnDoesntExist_ShouldAddFieldToBothListAndParentRootWeb() { using (var testScope = SiteTestScope.BlankSite()) { var fieldId = new Guid("{0C58B4A1-B360-47FE-84F7-4D8F58AE80F6}"); TextFieldInfo textFieldInfo = new TextFieldInfo( "TestInternalName", fieldId, "NameKey", "DescriptionKey", "GroupKey") { MaxLength = 50, Required = RequiredType.Required }; ListInfo listInfo = new ListInfo("sometestlistpath", "DynamiteTestListNameKey", "DynamiteTestListDescriptionKey"); using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope()) { IListHelper listHelper = injectionScope.Resolve<IListHelper>(); SPList list = listHelper.EnsureList(testScope.SiteCollection.RootWeb, listInfo); IFieldHelper fieldHelper = injectionScope.Resolve<IFieldHelper>(); var fieldsCollection = list.Fields; SPField field = fieldHelper.EnsureField(fieldsCollection, textFieldInfo); SPList testList = testScope.SiteCollection.RootWeb.Lists[list.ID]; Assert.IsNotNull(testList.Fields[fieldId]); Assert.IsNotNull(testScope.SiteCollection.RootWeb.Fields[fieldId]); // would be null if we hadn't bothered ensuring the field on the root web } } }
public void EnsureField_WhenSubWebFieldCollection_AndSiteColumnDoesntExist_ShouldAddFieldParentRootWebInAReallySneakyWay() { using (var testScope = SiteTestScope.BlankSite()) { var fieldId = new Guid("{0C58B4A1-B360-47FE-84F7-4D8F58AE80F6}"); TextFieldInfo textFieldInfo = new TextFieldInfo( "TestInternalName", fieldId, "NameKey", "DescriptionKey", "GroupKey") { MaxLength = 50, Required = RequiredType.Required }; ListInfo listInfo = new ListInfo("sometestlistpath", "DynamiteTestListNameKey", "DynamiteTestListDescriptionKey"); using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope()) { SPWeb subWeb = testScope.SiteCollection.RootWeb.Webs.Add("subweb"); IFieldHelper fieldHelper = injectionScope.Resolve<IFieldHelper>(); var fieldsCollection = subWeb.Fields; SPField field = fieldHelper.EnsureField(fieldsCollection, textFieldInfo); SPWeb testSubWeb = testScope.SiteCollection.RootWeb.Webs["subweb"]; try { var shouldBeMissingAndThrowException = testSubWeb.Fields[fieldId]; Assert.Fail(); } catch (ArgumentException) { // we got sneaky and created the site column on the root web instead // (customizing a field definition in a sub-web is impossible once the rootweb // column exists) } Assert.IsNotNull(testScope.SiteCollection.RootWeb.Fields[fieldId]); // would be null if we hadn't bothered ensuring the field on the root web } } }
/// <summary> /// Event Receiver Info (List) /// </summary> /// <param name="list">The list</param> /// <param name="type">The event receiver type</param> public EventReceiverInfo(ListInfo list, SPEventReceiverType type) : this(list, type, SPEventReceiverSynchronization.Default) { }
public void EnsureField_WhenLookupSingleOrMultiField_ShouldApplyLookupFieldDefinitionAndDefaultValue() { using (var testScope = SiteTestScope.BlankSite()) { // Gotta create the list before we even think about provisioning a lookup ListInfo listInfo = new ListInfo("sometestlistpath", "DynamiteTestListNameKey", "DynamiteTestListDescriptionKey"); LookupFieldInfo lookupFieldInfo = new LookupFieldInfo( "TestInternalNameLookup", new Guid("{0C58B4A1-B360-47FE-84F7-4D8F58AE80F6}"), "NameKey", "DescriptionKey", "GroupKey") { // ShowField should be Title by default // ListId will be known only once the SPList is created }; LookupFieldInfo lookupFieldInfoWithDefault = new LookupFieldInfo( "TestInternalNameLookupD", new Guid("{0F413213-9B75-49AD-850E-38EF551B1D1F}"), "NameKeyDef", "DescriptionKeyDef", "GroupKey") { // Default value will be assigned below once the list and the lookup item are created ShowField = "ID" }; LookupMultiFieldInfo lookupMultiFieldInfo = new LookupMultiFieldInfo( "TestInternalNameLookupM", new Guid("{2A3DAD08-F9F7-4BF7-82D5-9E490DAEC242}"), "NameKeyMulti", "DescriptionKeyMulti", "GroupKey") { ShowField = "ID" }; LookupMultiFieldInfo lookupMultiFieldInfoWithDefault = new LookupMultiFieldInfo( "TestInternalNameLookupMD", new Guid("{9ACF13BF-F42C-4488-AE54-5E971B7619AB}"), "NameKeyMultiDef", "DescriptionKeyMultiDef", "GroupKey") { // ShowField should be Title by default // Default value will be assigned below once the list and the lookup items are created }; using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope()) { // Create the lookup list IListHelper listHelper = injectionScope.Resolve<IListHelper>(); SPList list = listHelper.EnsureList(testScope.SiteCollection.RootWeb, listInfo); // Add an item to lookup list to act as default lookup field value SPListItem item1 = list.Items.Add(); item1["Title"] = "Test Item 1"; item1.Update(); SPListItem item2 = list.Items.Add(); item2["Title"] = "Test Item 2"; item2.Update(); // Add the list ID to the Lookup field definitions lookupFieldInfo.ListId = list.ID; lookupFieldInfoWithDefault.ListId = list.ID; lookupFieldInfoWithDefault.DefaultValue = new LookupValue(item1.ID, item1.ID.ToString()); lookupMultiFieldInfo.ListId = list.ID; lookupMultiFieldInfoWithDefault.ListId = list.ID; lookupMultiFieldInfoWithDefault.DefaultValue = new LookupValueCollection() { new LookupValue(item1.ID, "Test Item 1"), new LookupValue(item2.ID, "Test Item 2") }; IFieldHelper fieldHelper = injectionScope.Resolve<IFieldHelper>(); var fieldsCollection = testScope.SiteCollection.RootWeb.Fields; // 1) Basic lookup field (no default value) SPFieldLookup lookupField = (SPFieldLookup)fieldHelper.EnsureField(fieldsCollection, lookupFieldInfo); this.ValidateFieldBasicValues(lookupFieldInfo, lookupField); Assert.IsTrue(string.IsNullOrEmpty(lookupField.DefaultValue)); Assert.AreEqual("Title", lookupField.LookupField); Assert.AreEqual(list.ID, new Guid(lookupField.LookupList)); Assert.IsFalse(lookupField.AllowMultipleValues); SPFieldLookup lookupFieldRefetched = (SPFieldLookup)testScope.SiteCollection.RootWeb.Fields[lookupFieldInfo.Id]; // refetch to make sure .Update() was properly called on SPField this.ValidateFieldBasicValues(lookupFieldInfo, lookupFieldRefetched); Assert.IsTrue(string.IsNullOrEmpty(lookupFieldRefetched.DefaultValue)); Assert.AreEqual("Title", lookupFieldRefetched.LookupField); Assert.AreEqual(list.ID, new Guid(lookupFieldRefetched.LookupList)); Assert.IsFalse(lookupFieldRefetched.AllowMultipleValues); // 2) Basic lookup field (with default value) lookupField = (SPFieldLookup)fieldHelper.EnsureField(fieldsCollection, lookupFieldInfoWithDefault); this.ValidateFieldBasicValues(lookupFieldInfoWithDefault, lookupField); Assert.AreEqual("ID", lookupField.LookupField); Assert.AreEqual(list.ID, new Guid(lookupField.LookupList)); Assert.IsFalse(lookupField.AllowMultipleValues); Assert.AreEqual("1;#1", lookupField.DefaultValue); lookupFieldRefetched = (SPFieldLookup)testScope.SiteCollection.RootWeb.Fields[lookupFieldInfoWithDefault.Id]; // refetch to make sure .Update() was properly called on SPField this.ValidateFieldBasicValues(lookupFieldInfoWithDefault, lookupFieldRefetched); Assert.AreEqual("ID", lookupFieldRefetched.LookupField); Assert.AreEqual(list.ID, new Guid(lookupFieldRefetched.LookupList)); Assert.IsFalse(lookupFieldRefetched.AllowMultipleValues); Assert.AreEqual("1;#1", lookupFieldRefetched.DefaultValue); // 3) Basic lookup multi field (no default value) lookupField = (SPFieldLookup)fieldHelper.EnsureField(fieldsCollection, lookupMultiFieldInfo); this.ValidateFieldBasicValues(lookupMultiFieldInfo, lookupField); Assert.IsTrue(string.IsNullOrEmpty(lookupField.DefaultValue)); Assert.AreEqual("ID", lookupField.LookupField); Assert.AreEqual(list.ID, new Guid(lookupField.LookupList)); Assert.IsTrue(lookupField.AllowMultipleValues); lookupFieldRefetched = (SPFieldLookup)testScope.SiteCollection.RootWeb.Fields[lookupMultiFieldInfo.Id]; // refetch to make sure .Update() was properly called on SPField this.ValidateFieldBasicValues(lookupMultiFieldInfo, lookupFieldRefetched); Assert.IsTrue(string.IsNullOrEmpty(lookupFieldRefetched.DefaultValue)); Assert.AreEqual("ID", lookupFieldRefetched.LookupField); Assert.AreEqual(list.ID, new Guid(lookupFieldRefetched.LookupList)); Assert.IsTrue(lookupFieldRefetched.AllowMultipleValues); // 4) Basic lookup multi field (with default value) lookupField = (SPFieldLookup)fieldHelper.EnsureField(fieldsCollection, lookupMultiFieldInfoWithDefault); this.ValidateFieldBasicValues(lookupMultiFieldInfoWithDefault, lookupField); Assert.AreEqual("Title", lookupField.LookupField); Assert.AreEqual(list.ID, new Guid(lookupField.LookupList)); Assert.IsTrue(lookupField.AllowMultipleValues); Assert.AreEqual("1;#Test Item 1;#2;#Test Item 2", lookupField.DefaultValue); lookupFieldRefetched = (SPFieldLookup)testScope.SiteCollection.RootWeb.Fields[lookupMultiFieldInfoWithDefault.Id]; // refetch to make sure .Update() was properly called on SPField this.ValidateFieldBasicValues(lookupMultiFieldInfoWithDefault, lookupFieldRefetched); Assert.AreEqual("Title", lookupFieldRefetched.LookupField); Assert.AreEqual(list.ID, new Guid(lookupFieldRefetched.LookupList)); Assert.IsTrue(lookupFieldRefetched.AllowMultipleValues); Assert.AreEqual("1;#Test Item 1;#2;#Test Item 2", lookupFieldRefetched.DefaultValue); } } }
/// <summary> /// Method to find a list with the ListInfo /// </summary> /// <param name="web">The Web where to find the list</param> /// <param name="listInfo">The ListInfo of the list to locate</param> /// <returns>A SharePoint SPList</returns> public SPList TryGetList(SPWeb web, ListInfo listInfo) { return this.TryGetList(web, listInfo.WebRelativeUrl.ToString()); }
public void EnsureField_WhenOnListInFrenchSubWeb_ShouldCreateListFieldWithFrenchDisplayName() { // English root web using (var testScope = SiteTestScope.BlankSite(Language.English.Culture.LCID)) { var fieldId = new Guid("{0C58B4A1-B360-47FE-84F7-4D8F58AE80F6}"); TextFieldInfo textFieldInfo = new TextFieldInfo( "TestInternalName", fieldId, "Test_FieldTitle", "Test_FieldDescription", "Test_ContentGroup") { MaxLength = 50, Required = RequiredType.Required }; ListInfo listInfo = new ListInfo("sometestlistpath", "DynamiteTestListNameKey", "DynamiteTestListDescriptionKey"); using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope()) { SPWeb frenchSubWeb = testScope.SiteCollection.RootWeb.Webs.Add("subweb", "French sub-web", string.Empty, (uint)Language.French.Culture.LCID, "STS#1", false, false); IListHelper listHelper = injectionScope.Resolve<IListHelper>(); SPList subWebList = listHelper.EnsureList(frenchSubWeb, listInfo); IFieldHelper fieldHelper = injectionScope.Resolve<IFieldHelper>(); SPFieldCollection listFields = testScope.SiteCollection.RootWeb.Webs["subweb"].Lists[subWebList.ID].Fields; SPField field = fieldHelper.EnsureField(listFields, textFieldInfo); SPField fieldOnOldCollection = listFields[textFieldInfo.Id]; SPField fieldRefetched = testScope.SiteCollection.RootWeb.Webs["subweb"].Lists[subWebList.ID].Fields[textFieldInfo.Id]; // Set MUI to french var ambientThreadCulture = Thread.CurrentThread.CurrentUICulture; Thread.CurrentThread.CurrentUICulture = Language.French.Culture; Assert.AreEqual("FR Nom de champ", field.Title); Assert.AreEqual("FR Description de champ", field.Description); Assert.AreEqual("FR Groupe de contenu", field.Group); Assert.AreEqual("FR Nom de champ", fieldOnOldCollection.Title); Assert.AreEqual("FR Description de champ", fieldOnOldCollection.Description); Assert.AreEqual("FR Groupe de contenu", fieldOnOldCollection.Group); Assert.AreEqual("FR Nom de champ", fieldRefetched.Title); Assert.AreEqual("FR Description de champ", fieldRefetched.Description); Assert.AreEqual("FR Groupe de contenu", fieldRefetched.Group); // Reset MUI to its old abient value Thread.CurrentThread.CurrentUICulture = ambientThreadCulture; } } }