public void SetDefaultColumnValuesTest() { if (TestCommon.AppOnlyTesting()) { Assert.Inconclusive("Taxonomy tests are not supported when testing using app-only"); } using (var clientContext = TestCommon.CreateClientContext()) { TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(clientContext); List <IDefaultColumnValue> defaultValues = new List <IDefaultColumnValue>(); var defaultColumnValue = new DefaultColumnTermValue(); defaultColumnValue.FieldInternalName = "TaxKeyword"; // Enterprise metadata field, should be present on the list defaultColumnValue.FolderRelativePath = "/"; // Root Folder var term = taxSession.GetTerm(_termId); defaultColumnValue.Terms.Add(term); defaultValues.Add(defaultColumnValue); var testDefaultValue = new DefaultColumnTextValue(); testDefaultValue.Text = "Bla"; testDefaultValue.FieldInternalName = _textFieldName; testDefaultValue.FolderRelativePath = "/"; // Root folder defaultValues.Add(testDefaultValue); var list = clientContext.Web.Lists.GetById(_listId); list.SetDefaultColumnValues(defaultValues); } }
public TermInstance GetTerm(object termId) { var termGuid = GuidInstance.ConvertFromJsObjectToGuid(termId); var term = m_taxonomySession.GetTerm(termGuid); return(new TermInstance(this.Engine.Object.InstancePrototype, term)); }
public void SetDefaultColumnValuesTest() { using (var clientContext = TestCommon.CreateClientContext()) { TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(clientContext); List <DefaultColumnTermValue> defaultValues = new List <DefaultColumnTermValue>(); var defaultColumnValue = new DefaultColumnTermValue(); defaultColumnValue.FieldInternalName = "TaxKeyword"; // Enterprise metadata field, should be present on the list defaultColumnValue.FolderRelativePath = "/"; // Root Folder var term = taxSession.GetTerm(_termId); //clientContext.Load(term, t => t.Id, t => t.Name); //clientContext.ExecuteQuery(); defaultColumnValue.Terms.Add(term); defaultValues.Add(defaultColumnValue); var list = clientContext.Web.Lists.GetById(_listId); list.SetDefaultColumnValues(defaultValues); } }
public static void RetrieveTerm(SPSite site, Guid termId) { TaxonomySession session = new TaxonomySession(site); // Retrieves a Term with the provided Id Term term = session.GetTerm(termId); Console.WriteLine("Got Term " + term.Name); }
public override Term Read() { var ctx = SPOSiteContext.CurrentSiteContext.Context; TaxonomySession ts = TaxonomySession.GetTaxonomySession(ctx); var term = ts.GetTerm(_termId); ctx.Load(term); ctx.ExecuteQuery(); return(term); }
/// <summary> /// Return information for the given term /// </summary> /// <param name="context">ClientContext object to operate on</param> /// <param name="termId">Id of the term to lookup</param> /// <returns>Term label</returns> public string GetTermFromId(ClientContext context, Guid termId) { // Lookup the provided term TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(context); var loadedTerm = taxSession.GetTerm(termId); context.Load(loadedTerm, p => p.Name); context.ExecuteQueryRetry(); return(loadedTerm.Name); }
private static List<DraftAsset> GetDraftContent(SPSite site, Hashtable links) { log.Enter(); List<DraftAsset> assets = null; if (links.ContainsValue(true)) { assets = new List<DraftAsset>(); log.TraceInformation(string.Format("Looking for draft content")); foreach (DictionaryEntry entry in links) { if ((bool)entry.Value == true) { string linkUrl = HttpUtility.HtmlDecode(entry.Key.ToString()); Uri originalUri = new Uri(linkUrl, UriKind.RelativeOrAbsolute); DraftAsset asset = null; if (!(originalUri.ToString().Contains('~') || originalUri.ToString().Contains("/_catalogs"))) { if (originalUri.IsAbsoluteUri) { if (originalUri.PathAndQuery != "/") { try { //Handle external URLs if (!originalUri.GetLeftPart(UriPartial.Authority).ToLower().Contains(Utility.GetPublishingUrl(site))) { log.TraceInformation(string.Format("Extenal valid link found (ignoring): {0}", originalUri)); } else { if (originalUri.ToString().ToLower().Contains("fixupredirect.aspx")) { string qry = originalUri.Query.Substring(1); System.Collections.Specialized.NameValueCollection parameters = HttpUtility.ParseQueryString(qry); string termId = parameters["termid"]; TaxonomySession session = new TaxonomySession(site, true); Term term = session.GetTerm(new Guid(termId)); string url = ""; if (term != null) { if (term.LocalCustomProperties != null && term.LocalCustomProperties.Count > 0) { if (term.LocalCustomProperties.ContainsKey("_Sys_Nav_TargetUrl")) { term.LocalCustomProperties.TryGetValue("_Sys_Nav_TargetUrl", out url); originalUri = new Uri(new Uri(Utility.GetPublishingUrl(site)), url); } } } } using (SPSite externalSite = new SPSite(originalUri.ToString())) { using (SPWeb web = externalSite.OpenWeb()) { string relativePathWithoutQueryParams = string.Format("/{0}",originalUri.GetComponents(UriComponents.Path, UriFormat.UriEscaped)); SPFile file = web.GetFile(relativePathWithoutQueryParams); //If file does not exist at this url then check if file is a friendly URL of a publishing page if (file == null || !file.Exists) { //Get physical publishing page URL from friendly url file = GetFileFromFriendlyUrl(web, originalUri); } if (file != null && file.Exists) { asset = new DraftAsset(); asset.IsInternal = true; asset.Url = file.ServerRelativeUrl; asset = GetDraftAssetFromFile(file, asset); if (asset != null && asset.FileType == "Linked Page") { //asset.Assets = GetDraftContent(externalSite, file.Item); } } else { asset = new DraftAsset(); asset.Url = originalUri.ToString(); asset.LastError = GetLastException(); } } } } } catch (Exception ex) { log.TraceException(ex, "SharePoint site does not exist"); RecordLastException(ex); if (asset == null) { asset = new DraftAsset(); asset.Url = originalUri.ToString(); } asset.LastError = GetLastException(); } if (asset != null) { assets.Add(asset); } } } } } } } log.Leave(); return assets; }
/// <summary> /// Gets the term for identifier. /// </summary> /// <param name="site">The site.</param> /// <param name="termStoreName">Name of the term store.</param> /// <param name="id">The identifier.</param> /// <returns>The specific term.</returns> public Term GetTermForId(SPSite site, string termStoreName, Guid id) { TaxonomySession session = this.taxonomyCacheManager.GetSiteTaxonomyCache(site, termStoreName, this.taxonomyHelper).TaxonomySession; return(session.GetTerm(id)); }
public static Dictionary <string, object> GetFieldValues(PnP.Core.Model.SharePoint.IList list, PnP.Core.Model.SharePoint.IListItem existingItem, Hashtable valuesToSet, ClientContext clientContext, PnPBatch batch) { TermStore store = null; TaxonomySession taxSession = null; int defaultLanguage = CultureInfo.CurrentCulture.LCID; var item = new Dictionary <string, object>(); // xxx: return early if hashtable is empty to save getting fields? var fields = list.Fields; Hashtable values = valuesToSet ?? new Hashtable(); foreach (var key in values.Keys) { var field = fields.AsRequested().FirstOrDefault(f => f.InternalName == key as string || f.Title == key as string); if (field != null) { switch (field.TypeAsString) { case "User": case "UserMulti": { var userValueCollection = field.NewFieldValueCollection(); var value = values[key]; if (value == null) { goto default; } if (value is string && string.IsNullOrWhiteSpace(value + "")) { goto default; } if (value.GetType().IsArray) { foreach (var arrayItem in (value as IEnumerable)) { int userId; if (!int.TryParse(arrayItem.ToString(), out userId)) { var user = list.PnPContext.Web.EnsureUser(arrayItem as string); userValueCollection.Values.Add(field.NewFieldUserValue(user)); } else { userValueCollection.Values.Add(field.NewFieldUserValue(userId)); } } item[key as string] = userValueCollection; } else { int userId; if (!int.TryParse(value as string, out userId)) { var user = list.PnPContext.Web.EnsureUser(value as string); item[key as string] = field.NewFieldUserValue(user); } else { item[key as string] = field.NewFieldUserValue(userId); } } break; } case "TaxonomyFieldType": case "TaxonomyFieldTypeMulti": { var value = values[key]; if (value != null && value.GetType().IsArray) { var fieldValueCollection = field.NewFieldValueCollection(); if (batch.TermStore == null) { taxSession = clientContext.Site.GetTaxonomySession(); store = taxSession.GetDefaultSiteCollectionTermStore(); clientContext.Load(store, s => s.DefaultLanguage); clientContext.ExecuteQueryRetry(); defaultLanguage = store.DefaultLanguage; batch.TermStore = store; batch.TaxonomySession = taxSession; batch.DefaultTermStoreLanguage = defaultLanguage; } else { taxSession = batch.TaxonomySession; store = batch.TermStore; defaultLanguage = batch.DefaultTermStoreLanguage.Value; } foreach (var arrayItem in value as object[]) { Term taxonomyItem; Guid termGuid; var label = string.Empty; var itemId = Guid.Empty; if (!Guid.TryParse(arrayItem as string, out termGuid)) { var batchedTerm = batch.GetCachedTerm(termGuid.ToString()); if (batchedTerm.key == null) { taxonomyItem = clientContext.Site.GetTaxonomyItemByPath(arrayItem as string) as Term; if (taxonomyItem == null) { throw new PSInvalidOperationException($"Cannot find term {arrayItem}"); } var labelResult = taxonomyItem.GetDefaultLabel(defaultLanguage); clientContext.ExecuteQueryRetry(); label = labelResult.Value; itemId = taxonomyItem.Id; batch.CacheTerm(termGuid.ToString(), termGuid, label); } else { itemId = batchedTerm.id; label = batchedTerm.label; } } else { var batchedTerm = batch.GetCachedTerm(termGuid.ToString()); if (batchedTerm.key == null) { taxonomyItem = taxSession.GetTerm(termGuid); if (taxonomyItem == null) { throw new PSInvalidOperationException($"Cannot find term {arrayItem}"); } var labelResult = taxonomyItem.GetDefaultLabel(defaultLanguage); clientContext.Load(taxonomyItem); clientContext.ExecuteQueryRetry(); itemId = taxonomyItem.Id; label = labelResult.Value; batch.CacheTerm(termGuid.ToString(), termGuid, label); } else { itemId = batchedTerm.id; label = batchedTerm.label; } fieldValueCollection.Values.Add(field.NewFieldTaxonomyValue(itemId, label)); } item[key as string] = fieldValueCollection; } } else { Guid termGuid = Guid.Empty; Term taxonomyItem = null; var label = string.Empty; var itemId = Guid.Empty; if (value != null && !Guid.TryParse(value as string, out termGuid)) { var batchedTerm = batch.GetCachedTerm(termGuid.ToString()); if (batchedTerm.key == null) { // Assume it's a TermPath taxonomyItem = clientContext.Site.GetTaxonomyItemByPath(value as string) as Term; var labelResult = taxonomyItem.GetDefaultLabel(defaultLanguage); clientContext.ExecuteQueryRetry(); itemId = taxonomyItem.Id; label = labelResult.Value; } else { itemId = batchedTerm.id; label = batchedTerm.label; } } else { if (value != null) { var batchedTerm = batch.GetCachedTerm(termGuid.ToString()); if (batchedTerm.key == null) { taxonomyItem = taxSession.GetTerm(termGuid); var labelResult = taxonomyItem.GetDefaultLabel(defaultLanguage); clientContext.Load(taxonomyItem); clientContext.ExecuteQueryRetry(); label = labelResult.Value; } else { itemId = batchedTerm.id; label = batchedTerm.label; } } } item[key as string] = field.NewFieldTaxonomyValue(taxonomyItem.Id, label); } break; } case "Lookup": case "LookupMulti": { var value = values[key]; if (value == null) { goto default; } int[] multiValue; if (value is Array) { var fieldValueCollection = field.NewFieldValueCollection(); var arr = (object[])values[key]; for (int i = 0; i < arr.Length; i++) { var arrayValue = arr[i].ToString(); fieldValueCollection.Values.Add(field.NewFieldLookupValue(int.Parse(arrayValue))); } item[key as string] = fieldValueCollection; } else { var fieldValueCollection = field.NewFieldValueCollection(); string valStr = values[key].ToString(); multiValue = valStr.Split(',', ';').Select(int.Parse).ToArray(); if (multiValue.Length > 1) { for (int i = 0; i < multiValue.Length; i++) { fieldValueCollection.Values.Add(field.NewFieldLookupValue(multiValue[i])); } item[key as string] = fieldValueCollection; } else { item[key as string] = field.NewFieldLookupValue(multiValue[0]); } } break; } default: { item[key as string] = values[key]; break; } } } else { throw new PSInvalidOperationException($"Field {key} not present in list."); } } if (existingItem != null && existingItem.Requested) { var specialFields = new[] { "Author", "Editor", "Created", "Modified" }; // check if we are setting editor or author fields if (item.Any(i => specialFields.Contains(i.Key))) { foreach (var field in specialFields) { if (!item.ContainsKey(field)) { item[field] = existingItem[field]; } } } } return(item); }
public static ICamlParameterBinding GetValueBinding(SPSite parentSite, SPFieldType fieldType, string fieldTypeAsString, bool includeTimeValue, Type memberType, object value) { try { Type valueType = value.GetType(); Type enumeratedType = valueType.GetEnumeratedType(); switch (fieldType) { case SPFieldType.Boolean: return(new CamlParameterBindingBoolean(Convert <bool>(value))); case SPFieldType.DateTime: if (enumeratedType != null) { return(new CamlParameterBindingDateTime(ResolveValueCollection(value, Convert <DateTime>), includeTimeValue)); } return(new CamlParameterBindingDateTime(Convert <DateTime>(value), includeTimeValue)); case SPFieldType.Guid: if (enumeratedType != null) { return(new CamlParameterBindingGuid(ResolveValueCollection(value, Convert <Guid>))); } return(new CamlParameterBindingGuid(Convert <Guid>(value))); case SPFieldType.Counter: case SPFieldType.Integer: if (enumeratedType != null) { return(new CamlParameterBindingInteger(ResolveValueCollection(value, Convert <int>))); } return(new CamlParameterBindingInteger(Convert <int>(value))); case SPFieldType.Currency: case SPFieldType.Number: if (enumeratedType != null) { return(new CamlParameterBindingNumber(ResolveValueCollection(value, Convert <double>))); } return(new CamlParameterBindingNumber(Convert <double>(value))); case SPFieldType.Lookup: case SPFieldType.User: if (enumeratedType != null) { if (enumeratedType.IsOf <SPModel>()) { return(new CamlParameterBindingLookup(((IEnumerable)value).OfType <SPModel>().Select(v => v.Adapter.ListItemId))); } if (enumeratedType.IsOf <int>()) { return(new CamlParameterBindingLookup(((IEnumerable)value).OfType <int>())); } if (enumeratedType.IsOf <SPPrincipal>()) { return(new CamlParameterBindingLookup(((IEnumerable)value).OfType <SPPrincipal>())); } if (enumeratedType.IsOf <SPListItem>()) { return(new CamlParameterBindingLookup(((IEnumerable)value).OfType <SPListItem>())); } if (enumeratedType.IsOf <Guid>()) { return(new CamlParameterBindingGuid(((IEnumerable)value).OfType <Guid>())); } } if (valueType.IsOf <SPModel>()) { return(new CamlParameterBindingLookup(((SPModel)value).Adapter.ListItemId)); } if (valueType.IsOf <int>()) { return(new CamlParameterBindingLookup((int)value)); } if (valueType.IsOf <SPPrincipal>()) { return(new CamlParameterBindingLookup((SPPrincipal)value)); } if (valueType.IsOf <SPListItem>()) { return(new CamlParameterBindingLookup((SPListItem)value)); } if (valueType.IsOf <Guid>()) { return(new CamlParameterBindingGuid((Guid)value)); } break; case SPFieldType.URL: if (enumeratedType != null) { return(new CamlParameterBindingUrl(ResolveValueCollection(value, ConvertToString))); } return(new CamlParameterBindingUrl(ConvertToString(value))); case SPFieldType.Choice: if (memberType.IsEnum) { return(new CamlParameterBindingString(Enum.GetName(memberType, Convert <int>(value)))); } break; case SPFieldType.ModStat: if (enumeratedType != null) { return(new CamlParameterBindingModStat(ResolveValueCollection(value, ConvertToEnum <SPModerationStatusType>))); } return(new CamlParameterBindingModStat(ConvertToEnum <SPModerationStatusType>(value))); } switch (fieldTypeAsString) { case "TaxonomyFieldType": case "TaxonomyFieldTypeMulti": if (enumeratedType != null) { if (enumeratedType.IsOf <int>()) { return(new CamlParameterBindingLookup(((IEnumerable)value).OfType <int>())); } if (enumeratedType.IsOf <Guid>()) { TaxonomySession session = new TaxonomySession(parentSite); int[] wssIds = ((IEnumerable)value).OfType <Guid>().SelectMany(v => session.GetTerm(v) == null ? new int[0] : session.GetTerm(v).GetWssIds(parentSite, true)).ToArray(); if (wssIds.Length > 0) { return(new CamlParameterBindingLookup(wssIds)); } return(new CamlParameterBindingLookup(0)); } if (enumeratedType.IsOf <Term>()) { int[] wssIds = ((IEnumerable)value).OfType <Term>().SelectMany(v => v.GetWssIds(parentSite, true)).ToArray(); if (wssIds.Length > 0) { return(new CamlParameterBindingLookup(wssIds)); } return(new CamlParameterBindingLookup(0)); } } if (valueType.IsOf <int>()) { return(new CamlParameterBindingLookup((int)value)); } if (valueType.IsOf <Guid>()) { TaxonomySession session = new TaxonomySession(parentSite); Term term = session.GetTerm((Guid)value); if (term != null) { IList <int> wssIds = term.GetWssIds(parentSite, true); if (wssIds.Count > 0) { return(new CamlParameterBindingLookup(wssIds)); } } return(new CamlParameterBindingLookup(0)); } if (valueType.IsOf <Term>()) { IList <int> wssIds = ((Term)value).GetWssIds(parentSite, true); if (wssIds.Count > 0) { return(new CamlParameterBindingLookup(wssIds)); } return(new CamlParameterBindingLookup(0)); } break; } if (enumeratedType != null) { return(new CamlParameterBindingString(ResolveValueCollection(value, ConvertToString))); } return(new CamlParameterBindingString(ConvertToString(value))); } catch (InvalidCastException) { throw new ArgumentException(String.Format("Supplied value cannot be converted to binding type '{0}'", fieldTypeAsString), "value"); } }