public static void DeleteLists(Web web) { ClientRuntimeContext context = web.Context; try { var lessonslearned = web.Lists.GetByTitle(LESSONSLEARNEDLISTTITLE); context.Load(lessonslearned); lessonslearned.DeleteObject(); context.ExecuteQuery(); } catch { } try { var projects = web.Lists.GetByTitle(PROJECTSLISTTITLE); context.Load(projects); projects.DeleteObject(); context.ExecuteQuery(); } catch { } try { var keywords = web.Lists.GetByTitle(KEYWORDSLISTTITLE); context.Load(keywords); keywords.DeleteObject(); context.ExecuteQuery(); } catch { } }
private static NavigationTermSet GetEditableNavigationTermSetByProviderName( Web web, ClientRuntimeContext context, String providerName) { // Get the current taxonomy session and update cache, just in case TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(web.Context); taxonomySession.UpdateCache(); context.ExecuteQueryRetry(); // Retrieve the Navigation TermSet for the current web NavigationTermSet navigationTermSet = TaxonomyNavigation.GetTermSetForWeb(web.Context, web, providerName, true); context.Load(navigationTermSet); context.ExecuteQueryRetry(); // Retrieve an editable TermSet for the current target navigation NavigationTermSet editableNavigationTermSet = navigationTermSet.GetAsEditable(taxonomySession); context.Load(editableNavigationTermSet); context.ExecuteQueryRetry(); return(editableNavigationTermSet); }
/// <summary> /// Parse {anchorid:*} tokens and replace with the id from the termstore. /// </summary> /// <param name="str">String to parse.</param> /// <param name="context"></param> /// <returns></returns> public static string ParseAnchorTermTokens(this string str, ClientRuntimeContext context) { TaxonomySession session = TaxonomySession.GetTaxonomySession(context); var termStore = session.GetDefaultSiteCollectionTermStore(); context.Load(termStore); context.ExecuteQueryRetry(); if (!termStore.ServerObjectIsNull.Value) { var pattern = @"{anchorid:[^}]*}"; str = str.ParseMatches(pattern, delegate(Capture capture, string parsedString) { string[] properties = Regex.Replace(capture.Value, @"[{}]", string.Empty).Split(':'); var group = termStore.Groups.GetByName(properties[1]); var termset = group.TermSets.GetByName(properties[2]); var term = termset.Terms.GetByName(properties[properties.Length - 1]); context.Load(term, t => t.Id); context.ExecuteQueryRetry(); return(parsedString.Remove(capture.Index, capture.Length).Insert(capture.Index, term.Id.ToString())); }); } return(str); }
/// <summary> /// Check if all tokens where replaced. If the field is a taxonomy field then we will check for the values of the referenced termstore and termset. /// </summary> /// <param name="fieldXml">The xml to parse</param> /// <param name="parser"></param> /// <param name="context"></param> /// <returns></returns> protected static bool IsFieldXmlValid(string fieldXml, TokenParser parser, ClientRuntimeContext context) { var isValid = true; var leftOverTokens = parser.GetLeftOverTokens(fieldXml); if (!leftOverTokens.Any()) { var fieldElement = XElement.Parse(fieldXml); if (fieldElement.Attribute("Type").Value == "TaxonomyFieldType") { var termStoreIdElement = fieldElement.XPathSelectElement("//ArrayOfProperty/Property[Name='SspId']/Value"); if (termStoreIdElement != null) { var termStoreId = Guid.Parse(termStoreIdElement.Value); TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(context); try { taxSession.EnsureProperty(t => t.TermStores); var store = taxSession.TermStores.GetById(termStoreId); context.Load(store); context.ExecuteQueryRetry(); if (store.ServerObjectIsNull.HasValue && !store.ServerObjectIsNull.Value) { var termSetIdElement = fieldElement.XPathSelectElement("//ArrayOfProperty/Property[Name='TermSetId']/Value"); if (termSetIdElement != null) { var termSetId = Guid.Parse(termSetIdElement.Value); try { var termSet = store.GetTermSet(termSetId); context.Load(termSet); context.ExecuteQueryRetry(); isValid = termSet.ServerObjectIsNull.HasValue && !termSet.ServerObjectIsNull.Value; } catch (Exception) { isValid = false; } } } } catch (Exception) { isValid = false; } } else { isValid = false; } } } else { //Some tokens where not replaced isValid = false; } return(isValid); }
private long GetWebSize(Web currentWeb) { long tmpSize = 0; ClientRuntimeContext clientContext = currentWeb.Context; clientContext.Load(currentWeb); clientContext.ExecuteQuery(); //ListCollection lists = currentWeb.Lists; //clientContext.Load(lists); //clientContext.ExecuteQuery(); var Libraries = clientContext.LoadQuery(currentWeb.Lists.Where(l => l.BaseTemplate == 101)); clientContext.ExecuteQuery(); foreach (List tmpList in Libraries) { clientContext.Load(tmpList); clientContext.ExecuteQuery(); string Query = String.Concat( "<View>", "<ViewFields>", "<FieldRef Name='Title'/>", "<FieldRef Name='ID'/>", "<FieldRef Name='File_x0020_Size'/>", "</ViewFields>", "</View>"); CamlQuery oQuery = new CamlQuery(); ListItemCollection collListItems = tmpList.GetItems(oQuery); clientContext.Load(collListItems); //FileCollection listFiles = tmpList.RootFolder.Files; //clientContext.Load(listFiles, // files => files.Include(file => file.ETag), // files => files.Include(file => file.ListItemAllFields["File_x0020_Size"])); clientContext.ExecuteQuery(); foreach (ListItem oListItem in collListItems) { clientContext.Load(oListItem); clientContext.ExecuteQuery(); var fileSize = (string)oListItem["File_x0020_Size"]; int itemFileSize = String.IsNullOrEmpty(fileSize) ? 0 : int.Parse(fileSize); tmpSize += itemFileSize; } } return(tmpSize); }
async Task AddScriptLinkAsync(Web web, StringBuilder b, string scriptDescription, string scriptLocation) { var action = web.UserCustomActions.Add(); action.Description = scriptDescription ?? DefaultScriptDescription; action.Location = scriptLocation ?? DefaultScriptLocation; action.ScriptBlock = b.ToString(); action.Update(); _ctx.Load(_web, s => s.UserCustomActions); await _ctx.ExecuteQueryAsync(); }
/// <summary> /// Gets the term labels within a term recursively /// </summary> /// <param name="subTermPath"></param> /// <param name="term"></param> /// <param name="termSetId"></param> /// <param name="clientContext"></param> /// <returns></returns> /// Reference: https://github.com/SharePoint/PnP-Sites-Core/blob/master/Core/OfficeDevPnP.Core/Extensions/TaxonomyExtensions.cs public static Dictionary <Guid, TermData> ParseSubTerms(string subTermPath, Term term, Guid termSetId, ClientRuntimeContext clientContext) { var items = new Dictionary <Guid, TermData>(); if (term.ServerObjectIsNull == null || term.ServerObjectIsNull == false) { clientContext.Load(term.Terms); clientContext.ExecuteQueryRetry(); } foreach (var subTerm in term.Terms) { var termName = subTerm.Name; var termPath = $"{subTermPath}{TermTransformator.TermNodeDelimiter}{termName}"; items.Add(subTerm.Id, new TermData() { TermGuid = subTerm.Id, TermLabel = termName, TermPath = termPath, TermSetId = termSetId }); if (term.TermsCount > 0) { var moreSubTerms = ParseSubTerms(termPath, subTerm, termSetId, clientContext); foreach (var foundTerm in moreSubTerms) { items.Add(foundTerm.Key, foundTerm.Value); } } } return(items); }
private static List <string> ParseSubTerms(string subTermPath, Term term, bool includeId, string delimiter, ClientRuntimeContext clientContext) { List <string> items = new List <string>(); if (term.ServerObjectIsNull == null || term.ServerObjectIsNull == false) { clientContext.Load(term.Terms); clientContext.ExecuteQuery(); } foreach (Term subTerm in term.Terms) { //ClientResult<string> termName = TaxonomyItem.NormalizeName(clientContext, subTerm.Name); //clientContext.ExecuteQuery(); string termName = DenormalizeName(subTerm.Name); string termPath = string.Format("{0}{3}{1}{2}", subTermPath, termName, (includeId) ? string.Format(";#{0}", subTerm.Id.ToString()) : "", delimiter); items.Add(termPath); if (term.TermsCount > 0) { items.AddRange(ParseSubTerms(termPath, subTerm, includeId, delimiter, clientContext)); } } return(items); }
protected PropertyValues ExtractProperties(object modelHost) { PropertyValues result = null; ClientRuntimeContext context = null; if (modelHost is SiteModelHost) { result = (modelHost as SiteModelHost).HostSite.RootWeb.AllProperties; context = (modelHost as SiteModelHost).HostSite.RootWeb.Context; } else if (modelHost is WebModelHost) { result = (modelHost as WebModelHost).HostWeb.AllProperties; context = (modelHost as WebModelHost).HostWeb.Context; } else if (modelHost is ListModelHost) { result = (modelHost as ListModelHost).HostList.RootFolder.Properties; context = (modelHost as ListModelHost).HostList.RootFolder.Context; } else if (modelHost is FolderModelHost) { var folderModelHost = modelHost as FolderModelHost; if (folderModelHost.CurrentLibraryFolder != null) { result = folderModelHost.CurrentLibraryFolder.Properties; context = folderModelHost.CurrentLibraryFolder.Context; } else { result = folderModelHost.CurrentListItem.Folder.Properties; context = folderModelHost.CurrentListItem.Context; } } else if (modelHost is ListItem) { // http://officespdev.uservoice.com/forums/224641-general/suggestions/6343086-expose-properties-property-for-microsoft-sharepo throw new SPMeta2NotImplementedException("ListItem properties provision is not supported yet."); //DeployProperty(host, host.CurrentListItem.all, property); } else if (modelHost is File) { // http://officespdev.uservoice.com/forums/224641-general/suggestions/6343087-expose-properties-property-for-microsoft-sharepo throw new SPMeta2NotImplementedException("File properties provision is not supported yet."); // DeployProperty(host, host.CurrentFile., property); } else { throw new SPMeta2NotImplementedException(string.Format("Model host [{0}] is not supported yet.", modelHost)); } context.Load(result); context.ExecuteQueryWithTrace(); return(result); }
protected virtual Group ResolveSecurityGroup(SecurityGroupLinkDefinition securityGroupLinkModel, Web web, ClientRuntimeContext context) { Group securityGroup = null; if (securityGroupLinkModel.IsAssociatedMemberGroup) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "IsAssociatedMemberGroup = true. Resolving AssociatedMemberGroup"); context.Load(web, w => w.AssociatedMemberGroup); context.ExecuteQueryWithTrace(); securityGroup = web.AssociatedMemberGroup; } else if (securityGroupLinkModel.IsAssociatedOwnerGroup) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "IsAssociatedOwnerGroup = true. Resolving IsAssociatedOwnerGroup"); context.Load(web, w => w.AssociatedOwnerGroup); context.ExecuteQueryWithTrace(); securityGroup = web.AssociatedOwnerGroup; } else if (securityGroupLinkModel.IsAssociatedVisitorGroup) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "IsAssociatedVisitorGroup = true. Resolving IsAssociatedVisitorGroup"); context.Load(web, w => w.AssociatedVisitorGroup); context.ExecuteQueryWithTrace(); securityGroup = web.AssociatedVisitorGroup; } else if (!string.IsNullOrEmpty(securityGroupLinkModel.SecurityGroupName)) { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Resolving group by name: [{0}]", securityGroupLinkModel.SecurityGroupName); securityGroup = WebExtensions.FindGroupByName(web.SiteGroups, securityGroupLinkModel.SecurityGroupName); } else { TraceService.Error((int)LogEventId.ModelProvisionCoreCall, "IsAssociatedMemberGroup/IsAssociatedOwnerGroup/IsAssociatedVisitorGroup/SecurityGroupName should be defined. Throwing SPMeta2Exception"); throw new SPMeta2Exception("securityGroupLinkModel"); } return(securityGroup); }
/// <summary> /// Loads values within a specified SharePoint object from the server. /// </summary> /// <param name="context">The Client Rutime Context object representing the client connection with the server.</param> /// <param name="obj">The object to populate the values of.</param> static public void Load(ClientRuntimeContext context, ClientObject obj) { if (context != null && obj != null) { context.Load(obj); context.ExecuteQuery(); } }
async Task <string> GetCatalogPathByIdAsync(int typeCatalog) { var gallery = _web.GetCatalog(typeCatalog); _ctx.Load(gallery, g => g.RootFolder.ServerRelativeUrl); await _ctx.ExecuteQueryAsync(); return($"{gallery.RootFolder.ServerRelativeUrl.TrimEnd(FileShaman.TrimChars)}/"); }
/// <summary> /// Check if the property is loaded on the site object, if not the site object will be reloaded /// </summary> /// <param name="cc">Context to execute upon</param> /// <param name="site">Site to execute upon</param> /// <param name="propertyToCheck">Property to check</param> /// <returns>A reloaded site object</returns> public static Site EnsureSite(ClientRuntimeContext cc, Site site, string propertyToCheck) { if (!site.IsObjectPropertyInstantiated(propertyToCheck)) { // get instances to root web, since we are processing currently sub site cc.Load(site); cc.ExecuteQuery(); } return(site); }
/// <summary> /// Check if the property is loaded on the site object, if not the site object will be reloaded /// </summary> /// <param name="cc">Context to execute upon</param> /// <param name="site">Site to execute upon</param> /// <param name="propertyToCheck">Property to check</param> /// <returns>A reloaded site object</returns> public static Site EnsureSite(ClientRuntimeContext cc, Site site, string propertyToCheck) { if (!site.IsObjectPropertyInstantiated(propertyToCheck)) { // get instances to root web, since we are processing currently sub site cc.Load(site); cc.ExecuteQuery(); } return site; }
/// <summary> /// Check if the property is loaded on the web object, if not the web object will be reloaded /// </summary> /// <param name="cc">Context to execute upon</param> /// <param name="web">Web to execute upon</param> /// <param name="propertyToCheck">Property to check</param> /// <returns>A reloaded web object</returns> public static Web EnsureWeb(ClientRuntimeContext cc, Web web, string propertyToCheck) { if (!web.IsObjectPropertyInstantiated(propertyToCheck)) { // get instances to root web, since we are processing currently sub site cc.Load(web); cc.ExecuteQuery(); } return web; }
/// <summary> /// Delete the search configuration at the specified object level - does not apply to managed properties. /// </summary> /// <param name="context"></param> /// <param name="searchObjectLevel"></param> /// <param name="searchConfiguration"></param> private static void DeleteSearchConfigurationImplementation(ClientRuntimeContext context, SearchObjectLevel searchObjectLevel, string searchConfiguration) { SearchConfigurationPortability searchConfig = new SearchConfigurationPortability(context); SearchObjectOwner owner = new SearchObjectOwner(context, searchObjectLevel); // Delete search configuration searchConfig.DeleteSearchConfiguration(owner, searchConfiguration); context.Load(searchConfig); context.ExecuteQueryRetry(); }
/// <summary> /// Check if the property is loaded on the web object, if not the web object will be reloaded /// </summary> /// <param name="cc">Context to execute upon</param> /// <param name="web">Web to execute upon</param> /// <param name="propertyToCheck">Property to check</param> /// <returns>A reloaded web object</returns> public static Web EnsureWeb(ClientRuntimeContext cc, Web web, string propertyToCheck) { if (!web.IsObjectPropertyInstantiated(propertyToCheck)) { // get instances to root web, since we are processing currently sub site cc.Load(web); cc.ExecuteQuery(); } return(web); }
public static List <string> ShowAllLists(this Web web) { ClientRuntimeContext ctx = web.Context; ctx.Load(web.Lists); ctx.ExecuteQuery(); var listTitles = web.Lists.Select(l => l.Title).ToList(); return(listTitles); }
/// <summary> /// Gets a site collection context for the passed web. This site collection client context uses the same credentials /// as the passed client context /// </summary> /// <param name="clientContext">Client context to take the credentials from</param> /// <returns>A site collection client context object for the site collection</returns> public static ClientContext GetSiteCollectionContext(this ClientRuntimeContext clientContext) { Site site = (clientContext as ClientContext).Site; if (!site.IsObjectPropertyInstantiated("Url")) { clientContext.Load(site); clientContext.ExecuteQueryRetry(); } return(clientContext.Clone(site.Url)); }
private static bool CheckForDefaultTimeSlotList(ClientRuntimeContext clientContext, List spList) { var query = new CamlQuery() { ViewXml = "<View><Query><Where><IsNotNull><FieldRef Name='TimeSlot'/></IsNotNull></Where></Query><RowLimit>25</RowLimit><ViewFields><FieldRef Name='ID'/></ViewFields></View>" }; var listItems = spList.GetItems(query); clientContext.Load(listItems); clientContext.ExecuteQuery(); return(listItems.Count != 0); }
public Folder EnsureFolder(ClientRuntimeContext context, Folder ParentFolder, string FolderPath) { if (string.IsNullOrEmpty(FolderPath)) { return(ParentFolder); } //Split up the incoming path so we have the first element as the a new sub-folder name //and add it to ParentFolder folders collection string[] PathElements = FolderPath.Split(new char[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries); string Head = PathElements[0]; var NewFolder = ParentFolder.Folders.GetByUrl(Head); try { context.ExecuteQuery(); } catch (Exception e) { NewFolder = ParentFolder.Folders.Add(Head); context.Load(NewFolder); try { context.ExecuteQuery(); } catch (Exception eee) { throw; } } //If we have subfolders to create then the length of PathElements will be greater than 1 if (PathElements.Length > 1) { //If we have more nested folders to create then reassemble the folder path using what we have left i.e. the tail string Tail = string.Empty; for (int i = 1; i < PathElements.Length; i++) { Tail = Tail + "/" + PathElements[i]; } //Then make a recursive call to create the next subfolder return(EnsureFolder(context, NewFolder, Tail)); } else { //This ensures that the folder at the end of the chain gets returned return(NewFolder); } }
private Principal ResolvePrincipal(ClientRuntimeContext context, Web web, string owner) { Principal result = null; var targetSources = new Dictionary <PrincipalType, PrincipalInfo>(); // owner might be only a user or sharepoint group // making a few attempts and checking NULL ref later in the code targetSources.Add(PrincipalType.SharePointGroup, null); targetSources.Add(PrincipalType.User, null); foreach (var targetSource in targetSources.Keys) { // ResolvePrincipal != SearchPrincipals, at all! //var principalInfos = Utility.ResolvePrincipal(context, web, owner, targetSource, PrincipalSource.All, null, false); var principalInfos = Utility.SearchPrincipals(context, web, owner, targetSource, PrincipalSource.All, null, 2); context.ExecuteQueryWithTrace(); if (principalInfos.Count > 0) //if (principalInfos.Value != null) { var info = principalInfos[0]; //var info = principalInfos.Value; targetSources[targetSource] = info; if (targetSource == PrincipalType.User || targetSource == PrincipalType.SecurityGroup) { result = web.EnsureUser(info.LoginName); } if (targetSource == PrincipalType.SharePointGroup) { result = web.SiteGroups.GetById(info.PrincipalId); } context.Load(result); context.ExecuteQueryWithTrace(); // nic, found, break, profit! break; } } return(result); }
/// <summary> /// Delete the search configuration at the specified object level - does not apply to managed properties. /// </summary> /// <param name="context"></param> /// <param name="searchObjectLevel"></param> /// <param name="searchConfiguration"></param> private static void DeleteSearchConfigurationImplementation(ClientRuntimeContext context, SearchObjectLevel searchObjectLevel, string searchConfiguration) { #if ONPREMISES if (searchObjectLevel == SearchObjectLevel.Ssa) { // Reference: https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.search.portability.searchconfigurationportability_members.aspx throw new Exception("You cannot import customized search configuration settings to a Search service application (SSA)."); } #endif SearchConfigurationPortability searchConfig = new SearchConfigurationPortability(context); SearchObjectOwner owner = new SearchObjectOwner(context, searchObjectLevel); // Delete search configuration searchConfig.DeleteSearchConfiguration(owner, searchConfiguration); context.Load(searchConfig); context.ExecuteQueryRetry(); }
private static string ExtractResourceFolderServerRelativeUrl(Web web, ClientRuntimeContext context, ContentType currentContentType) { if (!currentContentType.IsPropertyAvailable("SchemaXml") || !web.IsPropertyAvailable("ServerRelativeUrl")) { context.Load(web, w => w.ServerRelativeUrl); currentContentType.Context.Load(currentContentType, c => c.SchemaXml); currentContentType.Context.ExecuteQueryWithTrace(); } var ctDocument = XDocument.Parse(currentContentType.SchemaXml); var folderUrlNode = ctDocument.Descendants().FirstOrDefault(d => d.Name == "Folder"); var webRelativeFolderUrl = folderUrlNode.Attribute("TargetName").Value; var serverRelativeFolderUrl = UrlUtility.CombineUrl(web.ServerRelativeUrl, webRelativeFolderUrl); TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "webRelativeFolderUrl is: [{0}]", webRelativeFolderUrl); return(serverRelativeFolderUrl); }
private static List <TimeregWithTimeslot> GetTopTimeregsWithTimeslot(ClientRuntimeContext clientContext, List spList, Toolkit tk) { var rowLimit = 250; var query = new CamlQuery() { ViewXml = $@"<View><Query><Where><IsNotNull><FieldRef Name='{tk.TimeslotFieldName}'/></IsNotNull></Where><OrderBy><FieldRef Name='ID' Ascending='FALSE'/></OrderBy></Query><ViewFields><FieldRef Name='Sag_x003a_Sags_x0020_Id' /><FieldRef Name='{tk.TimeslotFieldName}' /></ViewFields><RowLimit>{rowLimit}</RowLimit></View>" }; var listItems = spList.GetItems(query); clientContext.Load(listItems); clientContext.ExecuteQuery(); var listOfTimeregsWithTimelots = new List <TimeregWithTimeslot>(); foreach (var item in listItems) { var timeregWithTimeslot = new TimeregWithTimeslot { Timeslot = tk.TimeslotIsFieldLookup ? (from field in item.FieldValues where field.Key == tk.TimeslotFieldName select((FieldLookupValue)field.Value).LookupValue).Single() : (from field in item.FieldValues where field.Key == tk.TimeslotFieldName select field.Value.ToString()).Single(), TimeslotId = tk.TimeslotIsFieldLookup ? (from field in item.FieldValues where field.Key == tk.TimeslotFieldName select((FieldLookupValue)field.Value).LookupId).Single() : -1, CaseId = (from field in item.FieldValues where field.Key == "Sag_x003a_Sags_x0020_Id" select ExtractCaseIdFromField(((FieldLookupValue)field.Value).LookupValue)).Single() }; listOfTimeregsWithTimelots.Add(timeregWithTimeslot); } return(listOfTimeregsWithTimelots); }
private static IList<ListItem> GetAllItems(ClientRuntimeContext context, List list, int pageSize = MaxListPageSize) { ListItemCollectionPosition position = null; IEnumerable<ListItem> results = Enumerable.Empty<ListItem>(); do { var query = new CamlQuery { ListItemCollectionPosition = position, ViewXml = string.Format("<View Scope=\"RecursiveAll\"><Query></Query><RowLimit>{0}</RowLimit></View>", pageSize) }; var items = list.GetItems(query); context.Load(items); context.ExecuteQuery(); position = items.ListItemCollectionPosition; results = results.Concat(items); } while (position != null); return results.ToList(); }
/// <summary> /// Check if all tokens where replaced. If the field is a taxonomy field then we will check for the values of the referenced termstore and termset. /// </summary> /// <param name="fieldXml">The xml to parse</param> /// <param name="parser"></param> /// <param name="context"></param> /// <returns></returns> protected static bool IsFieldXmlValid(string fieldXml, TokenParser parser, ClientRuntimeContext context) { var isValid = true; var leftOverTokens = parser.GetLeftOverTokens(fieldXml); if (!leftOverTokens.Any()) { var fieldElement = XElement.Parse(fieldXml); if (fieldElement.Attribute("Type").Value == "TaxonomyFieldType") { var termStoreIdElement = fieldElement.XPathSelectElement("//ArrayOfProperty/Property[Name='SspId']/Value"); if (termStoreIdElement != null) { var termStoreId = Guid.Parse(termStoreIdElement.Value); TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(context); try { taxSession.EnsureProperty(t => t.TermStores); var store = taxSession.TermStores.GetById(termStoreId); context.Load(store); context.ExecuteQueryRetry(); if (store.ServerObjectIsNull.HasValue && !store.ServerObjectIsNull.Value) { var termSetIdElement = fieldElement.XPathSelectElement("//ArrayOfProperty/Property[Name='TermSetId']/Value"); if (termSetIdElement != null) { var termSetId = Guid.Parse(termSetIdElement.Value); try { var termSet = store.GetTermSet(termSetId); context.Load(termSet); context.ExecuteQueryRetry(); isValid = termSet.ServerObjectIsNull.HasValue && !termSet.ServerObjectIsNull.Value; } catch (Exception) { isValid = false; } } } } catch (Exception) { isValid = false; } } else { isValid = false; } } } else { //Some tokens where not replaced isValid = false; } return isValid; }
private static Field GetLookupField(ClientRuntimeContext sourceContext, List sourceList, string lookupName) { var sourceFields = sourceList.Fields; sourceContext.Load(sourceFields); sourceContext.ExecuteQuery(); return sourceFields.ToList().SingleOrDefault(f => f.Title == lookupName); }
private List <Model.Term> GetTerms <T>(ClientRuntimeContext context, TaxonomyItem parent, int defaultLanguage, Boolean isSiteCollectionTermGroup = false) { List <Model.Term> termsToReturn = new List <Model.Term>(); TermCollection terms; var customSortOrder = string.Empty; if (parent is TermSet) { terms = ((TermSet)parent).Terms; customSortOrder = ((TermSet)parent).CustomSortOrder; } else { terms = ((Term)parent).Terms; customSortOrder = ((Term)parent).CustomSortOrder; } context.Load(terms, tms => tms.IncludeWithDefaultProperties(t => t.Labels, t => t.CustomSortOrder, t => t.IsReused, t => t.IsSourceTerm, t => t.SourceTerm, t => t.IsDeprecated, t => t.Description, t => t.Owner)); context.ExecuteQueryRetry(); foreach (var term in terms) { var modelTerm = new Model.Term(); if (!isSiteCollectionTermGroup || term.IsReused) { modelTerm.Id = term.Id; } modelTerm.Name = term.Name; modelTerm.IsAvailableForTagging = term.IsAvailableForTagging; modelTerm.IsReused = term.IsReused; modelTerm.IsSourceTerm = term.IsSourceTerm; modelTerm.SourceTermId = (term.SourceTerm != null) ? term.SourceTerm.Id : Guid.Empty; modelTerm.IsDeprecated = term.IsDeprecated; modelTerm.Description = term.Description; modelTerm.Owner = term.Owner; if ((!term.IsReused || term.IsSourceTerm) && term.Labels.Any()) { foreach (var label in term.Labels) { if ((label.Language == defaultLanguage && label.Value != term.Name) || label.Language != defaultLanguage) { var modelLabel = new Model.TermLabel(); modelLabel.IsDefaultForLanguage = label.IsDefaultForLanguage; modelLabel.Value = label.Value; modelLabel.Language = label.Language; modelTerm.Labels.Add(modelLabel); } } } //else //{ // foreach (var label in term.Labels) // { // var modelLabel = new Model.TermLabel(); // modelLabel.IsDefaultForLanguage = label.IsDefaultForLanguage; // modelLabel.Value = label.Value; // modelLabel.Language = label.Language; // modelTerm.Labels.Add(modelLabel); // } //} foreach (var localProperty in term.LocalCustomProperties) { modelTerm.LocalProperties.Add(localProperty.Key, localProperty.Value); } // Shared Properties have to be extracted just for source terms or not reused terms if (!term.IsReused || term.IsSourceTerm) { foreach (var customProperty in term.CustomProperties) { modelTerm.Properties.Add(customProperty.Key, customProperty.Value); } } if (term.TermsCount > 0) { modelTerm.Terms.AddRange(GetTerms <Term>(context, term, defaultLanguage, isSiteCollectionTermGroup)); } termsToReturn.Add(modelTerm); } if (!string.IsNullOrEmpty(customSortOrder)) { int count = 1; foreach (var id in customSortOrder.Split(new[] { ':' })) { var term = termsToReturn.FirstOrDefault(t => t.Id == Guid.Parse(id)); if (term != null) { term.CustomSortOrder = count; count++; } } termsToReturn = termsToReturn.OrderBy(t => t.CustomSortOrder).ToList(); } return(termsToReturn); }
private static string ExtractResourceFolderServerRelativeUrl(Web web, ClientRuntimeContext context, ContentType currentContentType) { if (!currentContentType.IsPropertyAvailable("SchemaXml") || !web.IsPropertyAvailable("ServerRelativeUrl")) { context.Load(web, w => w.ServerRelativeUrl); currentContentType.Context.Load(currentContentType, c => c.SchemaXml); currentContentType.Context.ExecuteQueryWithTrace(); } var ctDocument = XDocument.Parse(currentContentType.SchemaXml); var folderUrlNode = ctDocument.Descendants().FirstOrDefault(d => d.Name == "Folder"); var webRelativeFolderUrl = folderUrlNode.Attribute("TargetName").Value; var serverRelativeFolderUrl = UrlUtility.CombineUrl(web.ServerRelativeUrl, webRelativeFolderUrl); TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "webRelativeFolderUrl is: [{0}]", webRelativeFolderUrl); return serverRelativeFolderUrl; }
private static List GetList(ClientRuntimeContext context, Web web, string listTitle) { var sourceList = web.Lists.GetByTitle(listTitle); context.Load(sourceList); context.ExecuteQuery(); return sourceList; }
/// <summary> /// Sets the search configuration at the specified object level /// </summary> /// <param name="context"></param> /// <param name="searchObjectLevel"></param> /// <param name="searchConfiguration"></param> private static void SetSearchConfigurationImplementation(ClientRuntimeContext context, SearchObjectLevel searchObjectLevel, string searchConfiguration) { #if CLIENTSDKV15 if (searchObjectLevel == SearchObjectLevel.Ssa) { // Reference: https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.search.portability.searchconfigurationportability_members.aspx throw new Exception("You cannot import customized search configuration settings to a Search service application (SSA)."); } #endif SearchConfigurationPortability searchConfig = new SearchConfigurationPortability(context); SearchObjectOwner owner = new SearchObjectOwner(context, searchObjectLevel); // Import search configuration searchConfig.ImportSearchConfiguration(owner, searchConfiguration); context.Load(searchConfig); context.ExecuteQueryRetry(); }
public override void DeployModel(object modelHost, DefinitionBase model) { var definition = model.WithAssertAndCast <SearchSettingsDefinition>("model", value => value.RequireNotNull()); Web spObject = null; SearchSettingsConfig searchSettings = null; var searchCenterUrl = String.Empty; ClientRuntimeContext context = null; if (modelHost is SiteModelHost) { spObject = (modelHost as SiteModelHost).HostSite.RootWeb; context = spObject.Context; context.Load(spObject); context.Load(spObject, w => w.AllProperties); context.ExecuteQueryWithTrace(); searchSettings = GetCurrentSearchConfigAtSiteLevel(spObject); searchCenterUrl = GetSearchCenterUrlAtSiteLevel(spObject); } else if (modelHost is WebModelHost) { spObject = (modelHost as WebModelHost).HostWeb; context = spObject.Context; context.Load(spObject); context.Load(spObject, w => w.AllProperties); context.ExecuteQueryWithTrace(); searchSettings = GetCurrentSearchConfigAtWebLevel(spObject); searchCenterUrl = GetSearchCenterUrlAtWebLevel(spObject); } var assert = ServiceFactory.AssertService .NewAssert(definition, spObject) .ShouldNotBeNull(spObject); if (!string.IsNullOrEmpty(definition.SearchCenterUrl)) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.SearchCenterUrl); var isValid = s.SearchCenterUrl == searchCenterUrl; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.SearchCenterUrl); } if (!string.IsNullOrEmpty(definition.UseCustomResultsPageUrl)) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.UseCustomResultsPageUrl); var isValid = s.UseCustomResultsPageUrl == searchSettings.ResultsPageAddress; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.UseCustomResultsPageUrl); } if (definition.UseParentResultsPageUrl.HasValue) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.UseParentResultsPageUrl); var isValid = s.UseParentResultsPageUrl.Value == searchSettings.Inherit; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.UseParentResultsPageUrl, "UseParentResultsPageUrl is null"); } if (definition.UseFirstSearchNavigationNode.HasValue) { } else { assert.SkipProperty(m => m.UseFirstSearchNavigationNode, "UseFirstSearchNavigationNode is null"); } }
private static List<string> ParseSubTerms(string subTermPath, Term term, bool includeId, string delimiter, ClientRuntimeContext clientContext) { List<string> items = new List<string>(); if (term.ServerObjectIsNull == null || term.ServerObjectIsNull == false) { clientContext.Load(term.Terms); clientContext.ExecuteQuery(); } foreach (Term subTerm in term.Terms) { //ClientResult<string> termName = TaxonomyItem.NormalizeName(clientContext, subTerm.Name); //clientContext.ExecuteQuery(); string termName = DenormalizeName(subTerm.Name); string termPath = string.Format("{0}{3}{1}{2}", subTermPath, termName, (includeId) ? string.Format(";#{0}", subTerm.Id.ToString()) : "", delimiter); items.Add(termPath); if (term.TermsCount > 0) { items.AddRange(ParseSubTerms(termPath, subTerm, includeId, delimiter, clientContext)); } } return items; }
protected virtual Group ResolveSecurityGroup(SecurityGroupLinkDefinition securityGroupLinkModel, Web web, ClientRuntimeContext context) { Group securityGroup = null; if (securityGroupLinkModel.IsAssociatedMemberGroup) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "IsAssociatedMemberGroup = true. Resolving AssociatedMemberGroup"); context.Load(web, w => w.AssociatedMemberGroup); context.ExecuteQueryWithTrace(); securityGroup = web.AssociatedMemberGroup; } else if (securityGroupLinkModel.IsAssociatedOwnerGroup) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "IsAssociatedOwnerGroup = true. Resolving IsAssociatedOwnerGroup"); context.Load(web, w => w.AssociatedOwnerGroup); context.ExecuteQueryWithTrace(); securityGroup = web.AssociatedOwnerGroup; } else if (securityGroupLinkModel.IsAssociatedVisitorGroup) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "IsAssociatedVisitorGroup = true. Resolving IsAssociatedVisitorGroup"); context.Load(web, w => w.AssociatedVisitorGroup); context.ExecuteQueryWithTrace(); securityGroup = web.AssociatedVisitorGroup; } else if (!string.IsNullOrEmpty(securityGroupLinkModel.SecurityGroupName)) { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Resolving group by name: [{0}]", securityGroupLinkModel.SecurityGroupName); securityGroup = WebExtensions.FindGroupByName(web.SiteGroups, securityGroupLinkModel.SecurityGroupName); } else { TraceService.Error((int)LogEventId.ModelProvisionCoreCall, "IsAssociatedMemberGroup/IsAssociatedOwnerGroup/IsAssociatedVisitorGroup/SecurityGroupName should be defined. Throwing SPMeta2Exception"); throw new SPMeta2Exception("securityGroupLinkModel"); } return securityGroup; }
private static NavigationTermSet GetEditableNavigationTermSetByProviderName( Web web, ClientRuntimeContext context, String providerName) { // Get the current taxonomy session and update cache, just in case TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(web.Context); taxonomySession.UpdateCache(); context.ExecuteQueryRetry(); // Retrieve the Navigation TermSet for the current web NavigationTermSet navigationTermSet = TaxonomyNavigation.GetTermSetForWeb(web.Context, web, providerName, true); context.Load(navigationTermSet); context.ExecuteQueryRetry(); // Retrieve an editable TermSet for the current target navigation NavigationTermSet editableNavigationTermSet = navigationTermSet.GetAsEditable(taxonomySession); context.Load(editableNavigationTermSet); context.ExecuteQueryRetry(); return (editableNavigationTermSet); }
private Principal ResolvePrincipal(ClientRuntimeContext context, Web web, string owner) { Principal result = null; var targetSources = new Dictionary<PrincipalType, PrincipalInfo>(); // owner might be only a user or sharepoint group // making a few attempts and checking NULL ref later in the code targetSources.Add(PrincipalType.SharePointGroup, null); targetSources.Add(PrincipalType.User, null); foreach (var targetSource in targetSources.Keys) { // ResolvePrincipal != SearchPrincipals, at all! //var principalInfos = Utility.ResolvePrincipal(context, web, owner, targetSource, PrincipalSource.All, null, false); var principalInfos = Utility.SearchPrincipals(context, web, owner, targetSource, PrincipalSource.All, null, 2); context.ExecuteQueryWithTrace(); if (principalInfos.Count > 0) //if (principalInfos.Value != null) { var info = principalInfos[0]; //var info = principalInfos.Value; targetSources[targetSource] = info; if (targetSource == PrincipalType.User || targetSource == PrincipalType.SecurityGroup) result = web.EnsureUser(info.LoginName); if (targetSource == PrincipalType.SharePointGroup) result = web.SiteGroups.GetById(info.PrincipalId); context.Load(result); context.ExecuteQueryWithTrace(); // nic, found, break, profit! break; } } return result; }
public static void ExecuteLoad <T>(this ClientRuntimeContext context, T clientObject, params Expression <Func <T, object> >[] retrievals) where T : ClientObject { context.Load(clientObject, retrievals); context.ExecuteQuery(); }
private static List GetList(ClientRuntimeContext context, Web web, Guid listId) { var sourceList = web.Lists.GetById(listId); context.Load(sourceList); context.ExecuteQuery(); return sourceList; }
private List <Model.Term> GetTerms <T>(ClientRuntimeContext context, TaxonomyItem parent, int defaultLanguage) { List <Model.Term> termsToReturn = new List <Model.Term>(); TermCollection terms = null; var customSortOrder = string.Empty; if (parent is TermSet) { terms = ((TermSet)parent).Terms; customSortOrder = ((TermSet)parent).CustomSortOrder; } else { terms = ((Term)parent).Terms; customSortOrder = ((Term)parent).CustomSortOrder; } context.Load(terms, tms => tms.IncludeWithDefaultProperties(t => t.Labels, t => t.CustomSortOrder)); context.ExecuteQueryRetry(); foreach (var term in terms) { var modelTerm = new Model.Term(); modelTerm.Id = term.Id; modelTerm.Name = term.Name; modelTerm.IsAvailableForTagging = term.IsAvailableForTagging; if (term.Labels.Any()) { foreach (var label in term.Labels) { if ((label.Language == defaultLanguage && label.Value != term.Name) || label.Language != defaultLanguage) { var modelLabel = new Model.TermLabel(); modelLabel.IsDefaultForLanguage = label.IsDefaultForLanguage; modelLabel.Value = label.Value; modelLabel.Language = label.Language; modelTerm.Labels.Add(modelLabel); } } } //else //{ // foreach (var label in term.Labels) // { // var modelLabel = new Model.TermLabel(); // modelLabel.IsDefaultForLanguage = label.IsDefaultForLanguage; // modelLabel.Value = label.Value; // modelLabel.Language = label.Language; // modelTerm.Labels.Add(modelLabel); // } //} foreach (var localProperty in term.LocalCustomProperties) { modelTerm.LocalProperties.Add(localProperty.Key, localProperty.Value); } foreach (var customProperty in term.CustomProperties) { modelTerm.Properties.Add(customProperty.Key, customProperty.Value); } if (term.TermsCount > 0) { modelTerm.Terms.AddRange(GetTerms <Term>(context, term, defaultLanguage)); } termsToReturn.Add(modelTerm); } if (!string.IsNullOrEmpty(customSortOrder)) { int count = 1; foreach (var id in customSortOrder.Split(new[] { ':' })) { var term = termsToReturn.FirstOrDefault(t => t.Id == Guid.Parse(id)); if (term != null) { term.CustomSortOrder = count; count++; } } termsToReturn = termsToReturn.OrderBy(t => t.CustomSortOrder).ToList(); } return(termsToReturn); }
/// <summary> /// Loads values within a specified SharePoint object from the server. /// </summary> /// <param name="context">The Client Rutime Context object representing the client connection with the server.</param> /// <param name="obj">The object to populate the values of.</param> public static void Load(ClientRuntimeContext context, ClientObject obj) { if (context != null && obj != null) { context.Load(obj); context.ExecuteQuery(); } }