static void EnsureCustomPagesLibrary() { string libraryTitle = "Custom Pages"; string libraryUrl = "CustomPages"; // delete document library if it already exists ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext); using (scope.StartScope()) { using (scope.StartTry()) { site.Lists.GetByTitle(libraryTitle).DeleteObject(); } using (scope.StartCatch()) { } } ListCreationInformation lci = new ListCreationInformation(); lci.Title = libraryTitle; lci.Url = libraryUrl; lci.TemplateType = (int)ListTemplateType.DocumentLibrary; CustomPagesLibrary = site.Lists.Add(lci); CustomPagesLibrary.OnQuickLaunch = true; CustomPagesLibrary.Update(); CustomPagesLibrary.RootFolder.Folders.Add("content"); CustomPagesLibrary.RootFolder.Folders.Add("scripts"); clientContext.Load(CustomPagesLibrary); clientContext.ExecuteQuery(); CustomPagesLibraryRelativeUrl = "~site/" + libraryUrl + "/"; CustomPagesLibraryAbsoluteUrl = site.Url + "/" + libraryUrl + "/"; }
public Web Setup() { using (var ctx = TestCommon.CreateClientContext()) { var name = "WebExtensions"; ctx.ExecuteQuery(); ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx); Web web; using (scope.StartScope()) { using (scope.StartTry()) { web = ctx.Site.OpenWeb(name); web.DeleteObject(); } using (scope.StartCatch()) { web = ctx.Web.Webs.Add(new WebCreationInformation { Title = name, WebTemplate = "STS#0", Url = name }); } using (scope.StartFinally()) { return web; } } } }
protected TermSet FindTermSet(TermGroup termGroup, TaxonomyTermSetDefinition termSetModel) { TermSet result = null; var context = termGroup.Context; context.Load(termGroup.TermSets); context.ExecuteQueryWithTrace(); if (termSetModel.Id.HasValue) { var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { result = termGroup.TermSets.GetById(termSetModel.Id.Value); context.Load(result); } using (scope.StartCatch()) { } } } else if (!string.IsNullOrEmpty(termSetModel.Name)) { var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { result = termGroup.TermSets.GetByName(termSetModel.Name); context.Load(result); } using (scope.StartCatch()) { } } } context.ExecuteQueryWithTrace(); if (result != null && result.ServerObjectIsNull == false) { context.Load(result); //context.Load(result, g => g.Id); //context.Load(result, g => g.Name); context.ExecuteQueryWithTrace(); return result; } return null; }
protected void cmdCreateCustomersList_Click(object sender, EventArgs e) { SharePointContext spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (ClientContext clientContext = spContext.CreateUserClientContextForSPHost()) { clientContext.Load(clientContext.Web); clientContext.ExecuteQuery(); string listTitle = "Customers"; // delete list if it exists ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext); using (scope.StartScope()) { using (scope.StartTry()) { clientContext.Web.Lists.GetByTitle(listTitle).DeleteObject(); } using (scope.StartCatch()) { } } // create and initialize ListCreationInformation object ListCreationInformation listInformation = new ListCreationInformation(); listInformation.Title = listTitle; listInformation.Url = "Lists/Customers"; listInformation.QuickLaunchOption = QuickLaunchOptions.On; listInformation.TemplateType = (int)ListTemplateType.Contacts; // Add ListCreationInformation to lists collection and return list object List list = clientContext.Web.Lists.Add(listInformation); // modify additional list properties and update list.OnQuickLaunch = true; list.EnableAttachments = false; list.Update(); // send command to server to create list clientContext.ExecuteQuery(); // add an item to the list ListItemCreationInformation lici1 = new ListItemCreationInformation(); var item1 = list.AddItem(lici1); item1["Title"] = "Lennon"; item1["FirstName"] = "John"; item1.Update(); // add a second item ListItemCreationInformation lici2 = new ListItemCreationInformation(); var item2 = list.AddItem(lici2); item2["Title"] = "McCartney"; item2["FirstName"] = "Paul"; item2.Update(); // send add commands to server clientContext.ExecuteQuery(); // add message to app’s start page placeholderMainContent.Text = "New list created"; } }
public SPOTermSet CreateTermSet(string name, Guid id, int lcid, string contact, string description, string customSortOrder, bool isAvailableForTagging, string owner, bool isOpenForTermCreation) { var ctx = _termGroup.Context; TermSet termSet = null; ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx); using (scope.StartScope()) { using (scope.StartTry()) { termSet = _termGroup.TermSets.GetByName(name); ctx.Load(termSet); } using (scope.StartCatch()) { } } ctx.ExecuteQuery(); if (termSet == null || termSet.ServerObjectIsNull == null || termSet.ServerObjectIsNull.Value) { if (lcid == 0) { lcid = GetWorkingLanguage(_termGroup.TermStore); } if (string.IsNullOrEmpty(owner)) { var web = SPOSiteContext.CurrentSiteContext.Context.Web; ctx.Load(web, w => w.CurrentUser); ctx.ExecuteQuery(); owner = web.CurrentUser.LoginName; } termSet = _termGroup.CreateTermSet(name, id, lcid); termSet.Contact = contact; termSet.Description = description; termSet.CustomSortOrder = customSortOrder; termSet.IsAvailableForTagging = isAvailableForTagging; termSet.Owner = owner; termSet.IsOpenForTermCreation = isOpenForTermCreation; ctx.Load(termSet); ctx.ExecuteQuery(); return new SPOTermSet(termSet); } else { throw new Exception("The specified term set already exists."); } }
public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties) { SPRemoteEventResult result = new SPRemoteEventResult(); using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, useAppWeb: false)) { if (clientContext != null) { clientContext.Load(clientContext.Web); string listTitle = "Customers"; // delete list if it exists ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext); using (scope.StartScope()) { using (scope.StartTry()) { clientContext.Web.Lists.GetByTitle(listTitle).DeleteObject(); } using (scope.StartCatch()) { } } // create and initialize ListCreationInformation object ListCreationInformation listInformation = new ListCreationInformation(); listInformation.Title = listTitle; listInformation.Url = "Lists/Customers"; listInformation.QuickLaunchOption = QuickLaunchOptions.On; listInformation.TemplateType = (int)ListTemplateType.Contacts; // Add ListCreationInformation to lists collection and return list object List list = clientContext.Web.Lists.Add(listInformation); // modify additional list properties and update list.OnQuickLaunch = true; list.EnableAttachments = false; list.Update(); // send command to server to create list clientContext.ExecuteQuery(); // create a sample item in the list var customer1 = list.AddItem(new ListItemCreationInformation()); customer1["FirstName"] = "Mike"; customer1["Title"] = "Fitzmaurice"; customer1["Company"] = "Wingtip Toys"; customer1["WorkPhone"] = "(111)111-1111"; customer1["HomePhone"] = "(222)222-2222"; customer1["Email"] = "*****@*****.**"; customer1.Update(); // send command to server to create item clientContext.ExecuteQuery(); } } return result; }
protected Field FindExistingListField(List list, FieldDefinition fieldModel) { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "FindListField with Id: [{0}]", fieldModel.Id); var context = list.Context; Field field; var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { field = list.Fields.GetById(fieldModel.Id); context.Load(field); } using (scope.StartCatch()) { field = null; //context.Load(field); } } context.ExecuteQueryWithTrace(); if (!scope.HasException) { field = list.Fields.GetById(fieldModel.Id); context.Load(field); TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Found list field with Id: [{0}]", fieldModel.Id); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()"); context.ExecuteQueryWithTrace(); } else { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Cannot find list field with Id: [{0}]", fieldModel.Id); } return(field); }
private Field DeployListField(ListModelHost modelHost, FieldDefinition fieldModel) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Deploying list field"); var list = modelHost.HostList; var context = list.Context; var scope = new ExceptionHandlingScope(context); Field field; using (scope.StartScope()) { using (scope.StartTry()) { field = list.Fields.GetById(fieldModel.Id); context.Load(field); } using (scope.StartCatch()) { } } TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()"); context.ExecuteQueryWithTrace(); if (!scope.HasException) { field = list.Fields.GetById(fieldModel.Id); context.Load(field); TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Found site list with Id: [{0}]", fieldModel.Id); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()"); context.ExecuteQueryWithTrace(); return(EnsureField(context, field, list.Fields, fieldModel)); } TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Cannot find list field with Id: [{0}]", fieldModel.Id); return(EnsureField(context, null, list.Fields, fieldModel)); }
/// <summary> /// Ensures the folder asynchronous. /// </summary> /// <param name="listUrl">The list URL.</param> /// <param name="folderUrl">The folder URL.</param> /// <param name="parentFolder">The parent folder.</param> /// <param name="retrievals">The retrievals.</param> /// <returns></returns> public async Task <Folder> EnsureFolderAsync(string listUrl, string folderUrl, Folder parentFolder = null, params Expression <Func <Folder, object> >[] retrievals) { if (string.IsNullOrEmpty(listUrl)) { throw new ArgumentNullException(nameof(listUrl)); } if (string.IsNullOrEmpty(folderUrl)) { throw new ArgumentNullException(nameof(folderUrl)); } listUrl = listUrl.Replace("\\", "/"); folderUrl = folderUrl.Replace("\\", "/"); Folder folder; var list = await GetListFromUrlAsync(listUrl); var scope = new ExceptionHandlingScope(_web.Context); using (scope.StartScope()) { using (scope.StartTry()) GetExistingFolder(listUrl, folderUrl, parentFolder, null); using (scope.StartCatch()) CreateFolder(list, folderUrl, parentFolder); using (scope.StartFinally()) folder = GetExistingFolder(listUrl, folderUrl, parentFolder, retrievals); } var attempt = 0; while (true) { try { await _web.Context.ExecuteQueryAsync(); return(folder); } catch (ServerException e) when(e.Message == "File Not Found." && attempt++ <= 2) { _log?.LogInformation($"Retry{attempt}: {e.Message}"); Thread.Sleep(100); } } }
static void CreateCustomersList() { string listTitle = "Customers"; string listUrl = "Lists/Customers"; // delete document library if it already exists ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext); using (scope.StartScope()) { using (scope.StartTry()) { site.Lists.GetByTitle(listTitle).DeleteObject(); } using (scope.StartCatch()) { } } ListCreationInformation lci = new ListCreationInformation(); lci.Title = listTitle; lci.Url = listUrl; lci.TemplateType = (int)ListTemplateType.Contacts; listCustomers = site.Lists.Add(lci); listCustomers.OnQuickLaunch = true; listCustomers.Update(); // attach JSLink script to default view for client-side rendering listCustomers.DefaultView.JSLink = AppRootFolderRelativeUrl + "scripts/CustomersListCSR.js"; listCustomers.DefaultView.Update(); listCustomers.Update(); clientContext.Load(listCustomers); clientContext.Load(listCustomers.Fields); clientContext.ExecuteQuery(); string[] UnwantedFields = { "FullName", "JobTitle", "CellPhone", "WorkFax", "WorkCountry", "WebPage", "Comments" }; foreach (string UnwantedField in UnwantedFields) { listCustomers.Fields.GetByInternalNameOrTitle(UnwantedField).DeleteObject(); } clientContext.ExecuteQuery(); // add some sample data to make things more interesting PopulateCustomersList(); }
static void DeleteAllTopNavNodes() { // delete all existing nodes for (int index = (TopNavNodes.Count - 1); index >= 0; index--) { ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext); using (scope.StartScope()) { using (scope.StartTry()) { TopNavNodes[index].DeleteObject(); } using (scope.StartCatch()) { } } clientContext.ExecuteQuery(); } clientContext.Load(TopNavNodes); clientContext.ExecuteQuery(); // add back in Home node AddHomeTopNavNode(); }
public Web Setup(string webTemplate = "STS#0", bool enablePublishingInfrastructure = false) { using (var ctx = TestCommon.CreateClientContext()) { var name = "WebExtensions"; ctx.ExecuteQueryRetry(); ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx); Web web; Site site; site = ctx.Site; if (enablePublishingInfrastructure && !site.IsFeatureActive(publishingSiteFeatureId)) { site.ActivateFeature(publishingSiteFeatureId); deactivatePublishingOnTearDown = true; } using (scope.StartScope()) { using (scope.StartTry()) { web = ctx.Site.OpenWeb(name); web.DeleteObject(); } using (scope.StartCatch()) { web = ctx.Web.Webs.Add(new WebCreationInformation { Title = name, WebTemplate = webTemplate, Url = name }); } using (scope.StartFinally()) { return web; } } } }
public static void DeleteOrdersList() { if (OrdersListExists()) { // delete customer lookup column if it exists ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext); using (scope.StartScope()) { using (scope.StartTry()) { var col = listOrders.Fields.GetByInternalNameOrTitle("Customer"); col.DeleteObject(); listOrders.Update(); } using (scope.StartCatch()) { } } clientContext.ExecuteQuery(); // delete orders list DeleteList("Orders"); listOrders = null; } }
private static Group EnsureGroup(Web web, string groupName) { ExceptionHandlingScope ensureGroupScope = new ExceptionHandlingScope(web.Context); using (ensureGroupScope.StartScope()) { using (ensureGroupScope.StartTry()) { web.SiteGroups.GetByName(groupName); } using (ensureGroupScope.StartCatch()) { GroupCreationInformation groupCreationInfo = new GroupCreationInformation(); groupCreationInfo.Title = groupName; web.SiteGroups.Add(groupCreationInfo); } } return(web.SiteGroups.GetByName(groupName)); }
public Web Setup(string webTemplate = "STS#0", bool enablePublishingInfrastructure = false) { using (var ctx = TestCommon.CreateClientContext()) { var name = "WebExtensions"; ctx.ExecuteQuery(); ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx); Web web; Site site; site = ctx.Site; if (enablePublishingInfrastructure && !site.IsFeatureActive(publishingSiteFeatureId)) { site.ActivateFeature(publishingSiteFeatureId); deactivatePublishingOnTearDown = true; } using (scope.StartScope()) { using (scope.StartTry()) { web = ctx.Site.OpenWeb(name); web.DeleteObject(); } using (scope.StartCatch()) { web = ctx.Web.Webs.Add(new WebCreationInformation { Title = name, WebTemplate = webTemplate, Url = name }); } using (scope.StartFinally()) { return(web); } } } }
static void CreateCustomersList() { string listTitle = "Customers"; string listUrl = "Lists/Customers"; // delete document library if it already exists ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext); using (scope.StartScope()) { using (scope.StartTry()) { site.Lists.GetByTitle(listTitle).DeleteObject(); } using (scope.StartCatch()) { } } ListCreationInformation lci = new ListCreationInformation(); lci.Title = listTitle; lci.Url = listUrl; lci.TemplateType = (int)ListTemplateType.Contacts; listCustomers = site.Lists.Add(lci); listCustomers.OnQuickLaunch = true; listCustomers.Update(); // attach JSLink script to default view for client-side rendering listCustomers.DefaultView.JSLink = AppRootFolderRelativeUrl + "scripts/CustomersListCSR.js"; listCustomers.DefaultView.Update(); listCustomers.Update(); clientContext.Load(listCustomers); clientContext.Load(listCustomers.Fields); clientContext.ExecuteQuery(); string[] UnwantedFields = { "FullName", "JobTitle", "CellPhone", "WorkFax", "WorkCountry", "WebPage", "Comments" }; foreach (string UnwantedField in UnwantedFields) { listCustomers.Fields.GetByInternalNameOrTitle(UnwantedField).DeleteObject(); } clientContext.ExecuteQuery(); // add some sample data to make things more interesting PopulateCustomersList(); }
public async Task DeleteFolderAsync(string listUrl, string folderUrl, Folder parentFolder = null) { if (string.IsNullOrEmpty(listUrl)) { throw new ArgumentNullException(nameof(listUrl)); } if (string.IsNullOrEmpty(folderUrl)) { return; } var scope = new ExceptionHandlingScope(_web.Context); using (scope.StartScope()) { using (scope.StartTry()) { var folderPath = $"{listUrl.TrimEnd(FileShaman.TrimChars)}/{folderUrl}"; var folder = _web.GetFolderByServerRelativeUrl($"{listUrl.TrimEnd(FileShaman.TrimChars)}/{folderUrl}"); folder.DeleteObject(); } using (scope.StartCatch()) { } } var attempt = 0; while (true) { try { await _web.Context.ExecuteQueryAsync(); return; } catch (ServerException e) when(e.Message == "File Not Found." && attempt++ <= 3) { _log?.LogInformation($"Retry{attempt}: {e.Message}"); Thread.Sleep(500); } } }
private Field FindExistingField(Web web, Guid id) { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Finding site field by ID: [{0}]", id); var context = web.Context; var scope = new ExceptionHandlingScope(context); Field field = null; using (scope.StartScope()) { using (scope.StartTry()) { web.AvailableFields.GetById(id); } using (scope.StartCatch()) { } } context.ExecuteQueryWithTrace(); if (!scope.HasException) { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Found site field by ID: [{0}]", id); field = web.AvailableFields.GetById(id); context.Load(field); context.ExecuteQueryWithTrace(); } else { TraceService.ErrorFormat((int)LogEventId.ModelProvisionCoreCall, "Cannot find site field by ID: [{0}]. Provision might fatally fail.", id); } return(field); }
protected virtual FieldLookup GetDependentLookupField(FieldCollection fields, DependentLookupFieldDefinition definition) { var context = fields.Context; Field field = null; var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { fields.GetByInternalNameOrTitle(definition.InternalName); } using (scope.StartCatch()) { } } TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()"); context.ExecuteQueryWithTrace(); if (!scope.HasException) { field = fields.GetByInternalNameOrTitle(definition.InternalName); context.Load(field); context.ExecuteQueryWithTrace(); return(context.CastTo <FieldLookup>(field)); } return(null); }
static void Main() { string url = "http://intranet.wingtip.com"; ClientContext clientContext = new ClientContext(url); Web site = clientContext.Web; clientContext.ExecuteQuery(); ExceptionHandlingScope scope1 = new ExceptionHandlingScope(clientContext); using (scope1.StartScope()) { using (scope1.StartTry()) { site.Lists.GetByTitle("Teams").DeleteObject(); } using (scope1.StartCatch()) { } } ExceptionHandlingScope scope2 = new ExceptionHandlingScope(clientContext); using (scope2.StartScope()) { using (scope2.StartTry()) { site.Lists.GetByTitle("Players").DeleteObject(); } using (scope2.StartCatch()) { } } ListCreationInformation ciTeams = new ListCreationInformation(); ciTeams.Title = "Teams"; ciTeams.Url = "Lists/Teams"; ciTeams.QuickLaunchOption = QuickLaunchOptions.On; ciTeams.TemplateType = (int)ListTemplateType.GenericList; List Teams = site.Lists.Add(ciTeams); Teams.EnableAttachments = false; Teams.Update(); ListItem team1 = Teams.AddItem(new ListItemCreationInformation()); team1["Title"] = "Boston Celtics"; team1.Update(); ListItem team2 = Teams.AddItem(new ListItemCreationInformation()); team2["Title"] = "LA Lakers"; team2.Update(); clientContext.Load(Teams); clientContext.ExecuteQuery(); ListCreationInformation ciPlayers = new ListCreationInformation(); ciPlayers.Title = "Players"; ciPlayers.Url = "Lists/Players"; ciPlayers.QuickLaunchOption = QuickLaunchOptions.On; ciPlayers.TemplateType = (int)ListTemplateType.GenericList; List Players = site.Lists.Add(ciPlayers); Players.EnableAttachments = false; Players.Update(); string fieldXML = @"<Field Name='Team' " + "DisplayName='Team' " + "Type='Lookup' > " + "</Field>"; FieldLookup lookup = clientContext.CastTo <FieldLookup>(Players.Fields.AddFieldAsXml(fieldXML, true, AddFieldOptions.DefaultValue)); lookup.LookupField = "Title"; lookup.LookupList = Teams.Id.ToString(); lookup.Update(); Console.WriteLine("ID: " + Teams.Id.ToString()); clientContext.ExecuteQuery(); }
public SPOTermGroup CreateGroup(string name, Guid id, string description) { var ctx = _termStore.Context; TermGroup group = null; ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx); using (scope.StartScope()) { using (scope.StartTry()) { group = _termStore.Groups.GetByName(name); ctx.Load(group); } using (scope.StartCatch()) { } } ctx.ExecuteQuery(); if (group == null || group.ServerObjectIsNull == null || group.ServerObjectIsNull.Value) { group = _termStore.CreateGroup(name, id); group.Description = description; ctx.ExecuteQuery(); ctx.Load(group); ctx.ExecuteQuery(); return new SPOTermGroup(group); } else { throw new Exception("The specified term group already exists."); } }
private static Folder EnsureFolder(Web web, string listUrl, string folderUrl, Folder parentFolder) { Folder folder = null; var folderServerRelativeUrl = parentFolder == null ? listUrl.TrimEnd(Program.trimChars) + "/" + folderUrl : parentFolder.ServerRelativeUrl.TrimEnd(Program.trimChars) + "/" + folderUrl; if (string.IsNullOrEmpty(folderUrl)) { return null; } var lists = web.Lists; web.Context.Load(web); web.Context.Load(lists, l => l.Include(ll => ll.DefaultViewUrl)); web.Context.ExecuteQuery(); ExceptionHandlingScope scope = new ExceptionHandlingScope(web.Context); using (scope.StartScope()) { using (scope.StartTry()) { folder = web.GetFolderByServerRelativeUrl(folderServerRelativeUrl); web.Context.Load(folder); } using (scope.StartCatch()) { var list = lists.Where(l => l.DefaultViewUrl.IndexOf(listUrl, StringComparison.CurrentCultureIgnoreCase) >= 0).FirstOrDefault(); if (parentFolder == null) { parentFolder = list.RootFolder; } folder = parentFolder.Folders.Add(folderUrl); web.Context.Load(folder); } using (scope.StartFinally()) { folder = web.GetFolderByServerRelativeUrl(folderServerRelativeUrl); web.Context.Load(folder); } } web.Context.ExecuteQuery(); return folder; }
protected Web GetExistingWeb(Site site, Web parentWeb, string currentWebUrl) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Entering GetExistingWeb()"); var srcUrl = currentWebUrl.ToLower().Trim('/').Trim('\\'); #if !NET35 // for self-hosting and '/' if (parentWeb.Url.ToLower().Trim('/').Trim('\\').EndsWith(srcUrl)) { return(parentWeb); } #endif #if NET35 // for self-hosting and '/' if (parentWeb.ServerRelativeUrl.ToLower().Trim('/').Trim('\\').EndsWith(srcUrl)) { return(parentWeb); } #endif var context = parentWeb.Context; Web web; var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { web = site.OpenWeb(currentWebUrl); } using (scope.StartCatch()) { } } TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()"); context.ExecuteQueryWithTrace(); if (!scope.HasException && web != null && web.ServerObjectIsNull == false) { TraceService.InformationFormat((int)LogEventId.ModelProvisionCoreCall, "Found web with URL: [{0}]", currentWebUrl); context.Load(web); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()"); context.ExecuteQueryWithTrace(); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Exciting GetExistingWeb()"); return(web); } TraceService.InformationFormat((int)LogEventId.ModelProvisionCoreCall, "Can't find web with URL: [{0}]. Returning NULL.", currentWebUrl); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Exciting GetExistingWeb()"); return(null); }
public void ConfigureTaxonomyNavigation() { ClientContext clientContext = new ClientContext(TestConfig.ServerUrl); TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext); taxonomySession.UpdateCache(); NavigationTermSet termSet = DemoUtilities.RecreateSampleNavTermSet( this.TestContext, clientContext, taxonomySession, clientContext.Web); // Clear out any old settings WebNavigationSettings webNavigationSettings = new WebNavigationSettings(clientContext, clientContext.Web); webNavigationSettings.ResetToDefaults(); webNavigationSettings.Update(taxonomySession); TaxonomyNavigation.FlushSiteFromCache(clientContext, clientContext.Site); clientContext.ExecuteQuery(); this.WaitForSync(); // Verify the TermSet is not running NavigationTermSet actualTermSet; ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext); using (scope.StartScope()) { using (scope.StartTry()) { actualTermSet = TaxonomyNavigation.GetTermSetForWeb(clientContext, clientContext.Web, "GlobalNavigationTaxonomyProvider", includeInheritedSettings: true); } using (scope.StartCatch()) { } } clientContext.ExecuteQuery(); Assert.IsTrue(actualTermSet.ServerObjectIsNull.Value); // Assign the new settings webNavigationSettings = new WebNavigationSettings(clientContext, clientContext.Web); clientContext.Load(webNavigationSettings, w => w.GlobalNavigation, w => w.CurrentNavigation ); clientContext.Load(termSet, ts => ts.TermStoreId, ts => ts.Id ); clientContext.ExecuteQuery(); // GlobalNavigation = top menu (aka "top nav") // CurrentNavigation = left menu (aka "quick launch") webNavigationSettings.GlobalNavigation.Source = StandardNavigationSource.TaxonomyProvider; webNavigationSettings.GlobalNavigation.TermStoreId = termSet.TermStoreId; webNavigationSettings.GlobalNavigation.TermSetId = termSet.Id; webNavigationSettings.Update(taxonomySession); TaxonomyNavigation.FlushSiteFromCache(clientContext, clientContext.Site); clientContext.ExecuteQuery(); this.WaitForSync(); actualTermSet = TaxonomyNavigation.GetTermSetForWeb(clientContext, clientContext.Web, "GlobalNavigationTaxonomyProvider", includeInheritedSettings: true); clientContext.Load(actualTermSet, ts => ts.Id); clientContext.ExecuteQuery(); Assert.AreEqual(termSet.Id, actualTermSet.Id); }
internal void LoadWebPartsInWikiContentFromServer(List <WebPartEntity> webparts, File wikiPage, List <WebPartPlaceHolder> webPartsToRetrieve) { // Load web part manager and use it to load each web part LimitedWebPartManager limitedWPManager = wikiPage.GetLimitedWebPartManager(PersonalizationScope.Shared); cc.Load(limitedWPManager); foreach (var webPartToRetrieve in webPartsToRetrieve) { // Check if the web part was loaded when we loaded the web parts collection via the web part manager if (!Guid.TryParse(webPartToRetrieve.Id, out Guid webPartToRetrieveGuid)) { // Skip since guid is not valid continue; } // Sometimes the returned wiki html contains web parts which are not anymore on the page...using the ExceptionHandlingScope // we can handle these errors server side while just doing a single roundtrip var scope = new ExceptionHandlingScope(cc); using (scope.StartScope()) { using (scope.StartTry()) { webPartToRetrieve.WebPartDefinition = limitedWPManager.WebParts.GetByControlId(webPartToRetrieve.ControlId); cc.Load(webPartToRetrieve.WebPartDefinition, wp => wp.Id, wp => wp.WebPart.ExportMode, wp => wp.WebPart.Title, wp => wp.WebPart.ZoneIndex, wp => wp.WebPart.IsClosed, wp => wp.WebPart.Hidden, wp => wp.WebPart.Properties); } using (scope.StartCatch()) { } } } cc.ExecuteQueryRetry(); // Load the web part XML for the web parts that do allow it bool isDirty = false; foreach (var webPartToRetrieve in webPartsToRetrieve) { // Important to only process the web parts that did not return an error in the previous server call if (webPartToRetrieve.WebPartDefinition != null && (webPartToRetrieve.WebPartDefinition.ServerObjectIsNull.HasValue && webPartToRetrieve.WebPartDefinition.ServerObjectIsNull.Value == false)) { // Retry to load the properties, sometimes they're not retrieved webPartToRetrieve.WebPartDefinition.EnsureProperty(wp => wp.Id); webPartToRetrieve.WebPartDefinition.WebPart.EnsureProperties(wp => wp.ExportMode, wp => wp.Title, wp => wp.ZoneIndex, wp => wp.IsClosed, wp => wp.Hidden, wp => wp.Properties); if (webPartToRetrieve.WebPartDefinition.WebPart.ExportMode == WebPartExportMode.All) { webPartToRetrieve.WebPartXml = limitedWPManager.ExportWebPart(webPartToRetrieve.WebPartDefinition.Id); isDirty = true; } } } if (isDirty) { cc.ExecuteQueryRetry(); } // Determine the web part type and store it in the web parts array foreach (var webPartToRetrieve in webPartsToRetrieve) { if (webPartToRetrieve.WebPartDefinition != null && (webPartToRetrieve.WebPartDefinition.ServerObjectIsNull.HasValue && webPartToRetrieve.WebPartDefinition.ServerObjectIsNull.Value == false)) { // Important to only process the web parts that did not return an error in the previous server call if (webPartToRetrieve.WebPartDefinition.WebPart.ExportMode != WebPartExportMode.All) { // Use different approach to determine type as we can't export the web part XML without indroducing a change webPartToRetrieve.WebPartType = GetTypeFromProperties(webPartToRetrieve.WebPartDefinition.WebPart.Properties); } else { webPartToRetrieve.WebPartType = GetType(webPartToRetrieve.WebPartXml.Value); } webparts.Add(new WebPartEntity() { Title = webPartToRetrieve.WebPartDefinition.WebPart.Title, Type = webPartToRetrieve.WebPartType, Id = webPartToRetrieve.WebPartDefinition.Id, ServerControlId = webPartToRetrieve.Id, Row = webPartToRetrieve.Row, Column = webPartToRetrieve.Column, Order = webPartToRetrieve.Order, ZoneId = "", ZoneIndex = (uint)webPartToRetrieve.WebPartDefinition.WebPart.ZoneIndex, IsClosed = webPartToRetrieve.WebPartDefinition.WebPart.IsClosed, Hidden = webPartToRetrieve.WebPartDefinition.WebPart.Hidden, Properties = Properties(webPartToRetrieve.WebPartDefinition.WebPart.Properties, webPartToRetrieve.WebPartType, webPartToRetrieve.WebPartXml == null ? "" : webPartToRetrieve.WebPartXml.Value), }); } } #region old approach /* * // Load web parts on wiki page * var limitedWPManager = wikiPage.GetLimitedWebPartManager(PersonalizationScope.Shared); * cc.Load(limitedWPManager); * var webParts = limitedWPManager.WebParts; * cc.Load(webParts, p => p.Include(wp => wp.Id, wp => wp.WebPart.ExportMode, wp => wp.WebPart.Title, wp => wp.WebPart.ZoneIndex, wp => wp.WebPart.IsClosed, wp => wp.WebPart.Hidden, wp => wp.WebPart.Properties)); * cc.ExecuteQueryRetry(); * * foreach (var webPartToRetrieve in webPartsToRetrieve) * { * try * { * // Check if the web part was loaded when we loaded the web parts collection via the web part manager * Guid webPartToRetrieveGuid; * if (!Guid.TryParse(webPartToRetrieve.Id, out webPartToRetrieveGuid)) * { * // Skip since guid is not valid * continue; * } * * var foundWebPart = webParts.Where(p => p.Id.Equals(webPartToRetrieveGuid)).FirstOrDefault(); * if (foundWebPart == null) * { * // If not found then try to retrieve the webpart via the GetByControlId method * foundWebPart = limitedWPManager.WebParts.GetByControlId(webPartToRetrieve.ControlId); * cc.Load(foundWebPart, wp => wp.Id, wp => wp.WebPart.ExportMode, wp => wp.WebPart.Title, wp => wp.WebPart.ZoneIndex, wp => wp.WebPart.IsClosed, wp => wp.WebPart.Hidden, wp => wp.WebPart.Properties); * cc.ExecuteQueryRetry(); * } * * if (foundWebPart != null) * { * // Retry to load the properties, sometimes they're not retrieved * foundWebPart.EnsureProperty(wp => wp.Id); * foundWebPart.WebPart.EnsureProperties(wp => wp.ExportMode, wp => wp.Title, wp => wp.ZoneIndex, wp => wp.IsClosed, wp => wp.Hidden, wp => wp.Properties); * * //var changed = false; * string webPartXml = ""; * string webPartType = ""; * var exportMode = foundWebPart.WebPart.ExportMode; * if (foundWebPart.WebPart.ExportMode != WebPartExportMode.All) * { * // Use different approach to determine type as we can't export the web part XML without indroducing a change * webPartType = GetTypeFromProperties(foundWebPart.WebPart.Properties); * } * else * { * * var result = limitedWPManager.ExportWebPart(foundWebPart.Id); * cc.ExecuteQueryRetry(); * webPartXml = result.Value; * webPartType = GetType(webPartXml); * } * * webparts.Add(new WebPartEntity() * { * Title = foundWebPart.WebPart.Title, * Type = webPartType, * Id = foundWebPart.Id, * ServerControlId = webPartToRetrieve.Id, * Row = webPartToRetrieve.Row, * Column = webPartToRetrieve.Column, * Order = webPartToRetrieve.Order, * ZoneId = "", * ZoneIndex = (uint)foundWebPart.WebPart.ZoneIndex, * IsClosed = foundWebPart.WebPart.IsClosed, * Hidden = foundWebPart.WebPart.Hidden, * Properties = Properties(foundWebPart.WebPart.Properties, webPartType, webPartXml), * }); * } * } * catch (ServerException) * { * //Eat exception because we've found a WebPart ID which is not available on the server-side * } * } */ #endregion }
protected Field FindExistingSiteField(SiteModelHost siteHost, FieldDefinition fieldDefinition) { var id = fieldDefinition.Id; var rootWeb = siteHost.HostSite.RootWeb; TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "FindExistingSiteField with Id: [{0}]", id); var context = rootWeb.Context; var scope = new ExceptionHandlingScope(context); Field field = null; using (scope.StartScope()) { using (scope.StartTry()) { rootWeb.Fields.GetById(id); } using (scope.StartCatch()) { } } TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()"); context.ExecuteQueryWithTrace(); if (!scope.HasException) { field = rootWeb.Fields.GetById(id); context.Load(field); TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Found site field with Id: [{0}]", id); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()"); context.ExecuteQueryWithTrace(); } else { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Cannot find site field with Id: [{0}]", id); } return field; }
private static void EnsureFolder(Web web, string filePath, string fileFolder) { if (string.IsNullOrEmpty(fileFolder)) { return; } var lists = web.Lists; web.Context.Load(web); web.Context.Load(lists, l => l.Include(ll => ll.DefaultViewUrl)); web.Context.ExecuteQuery(); ExceptionHandlingScope scope = new ExceptionHandlingScope(web.Context); using (scope.StartScope()) { using (scope.StartTry()) { var folder = web.GetFolderByServerRelativeUrl(string.Concat(filePath, fileFolder)); web.Context.Load(folder); } using (scope.StartCatch()) { var list = lists.Where(l => l.DefaultViewUrl.IndexOf(filePath, StringComparison.CurrentCultureIgnoreCase) >= 0).FirstOrDefault(); ListItemCreationInformation newFolder = new ListItemCreationInformation(); newFolder.UnderlyingObjectType = FileSystemObjectType.Folder; newFolder.FolderUrl = filePath.TrimEnd(Program.trimChars); newFolder.LeafName = fileFolder; ListItem item = list.AddItem(newFolder); web.Context.Load(item); item.Update(); } using (scope.StartFinally()) { var folder = web.GetFolderByServerRelativeUrl(string.Concat(filePath, fileFolder)); web.Context.Load(folder); } } web.Context.ExecuteQuery(); }
protected Term FindTermInTermSet(TermSet termSet, TaxonomyTermDefinition termModel) { Term result = null; var context = termSet.Context; if (termModel.Id.HasValue) { var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { result = termSet.Terms.GetById(termModel.Id.Value); context.Load(result); } using (scope.StartCatch()) { } } context.ExecuteQueryWithTrace(); } else if (!string.IsNullOrEmpty(termModel.Name)) { var terms = termSet.GetTerms(new LabelMatchInformation(context) { Lcid = termModel.LCID, TermLabel = termModel.Name, TrimUnavailable = false }); context.Load(terms); context.ExecuteQueryWithTrace(); result = terms.FirstOrDefault(); } if (result != null && result.ServerObjectIsNull == false) { context.Load(result); context.ExecuteQueryWithTrace(); return result; } return null; }
static public void CreateAnnouncementsList(ClientContext clientContext) { string listTitle = "Announcements"; // delete list if it exists ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext); using (scope.StartScope()) { using (scope.StartTry()) { clientContext.Web.Lists.GetByTitle(listTitle).DeleteObject(); } using (scope.StartCatch()) { } } // create and initialize ListCreationInformation object ListCreationInformation listInformation = new ListCreationInformation(); listInformation.Title = listTitle; listInformation.Url = "Lists/Announcements"; listInformation.QuickLaunchOption = QuickLaunchOptions.On; listInformation.TemplateType = (int)ListTemplateType.Announcements; // Add ListCreationInformation to lists collection and return list object List list = clientContext.Web.Lists.Add(listInformation); // modify additional list properties and update list.OnQuickLaunch = true; list.EnableAttachments = false; list.Update(); // send command to server to create list clientContext.ExecuteQuery(); clientContext.Load(list); clientContext.ExecuteQuery(); string urlEventReceiver = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + @"/Services/AnnouncementsEventReceiver.svc"; EventReceiverDefinitionCreationInformation erci1 = new EventReceiverDefinitionCreationInformation(); erci1.ReceiverName = "ItemAdding"; erci1.EventType = EventReceiverType.ItemAdding; erci1.ReceiverUrl = urlEventReceiver; erci1.SequenceNumber = 1000; EventReceiverDefinition er1 = list.EventReceivers.Add(erci1); er1.Update(); EventReceiverDefinitionCreationInformation erci2 = new EventReceiverDefinitionCreationInformation(); erci2.ReceiverName = "ItemUpdating"; erci2.EventType = EventReceiverType.ItemUpdating; erci2.ReceiverUrl = urlEventReceiver; erci2.SequenceNumber = 1000; EventReceiverDefinition er2 = list.EventReceivers.Add(erci2); er2.Update(); clientContext.ExecuteQuery(); ListItemCreationInformation lici = new ListItemCreationInformation(); var item1 = list.AddItem(lici); item1["Title"] = "SharePoint introduces new app model"; item1["Body"] = "<div>Developers wonder what happened to solutions.</div>"; item1["Expires"] = DateTime.Today.AddYears(10); item1.Update(); var item2 = list.AddItem(lici); item2["Title"] = "All SharePoint developers must now learn JavaScript"; item2["Body"] = "<div>Some developers are more excited than others.</div>"; item2["Expires"] = DateTime.Today.AddYears(1); item2.Update(); var item3 = list.AddItem(lici); item3["Title"] = "CSOM programming is super fun"; item3["Body"] = "<div>Just ask my mom.</div>"; item3["Expires"] = DateTime.Today.AddDays(7); item3.Update(); clientContext.ExecuteQuery(); }
private Field FindField(FieldCollection fields, ListFieldLinkDefinition listFieldLinkModel) { var context = fields.Context; var scope = new ExceptionHandlingScope(context); Field field = null; if (listFieldLinkModel.FieldId.HasGuidValue()) { var id = listFieldLinkModel.FieldId.Value; using (scope.StartScope()) { using (scope.StartTry()) { fields.GetById(id); } using (scope.StartCatch()) { } } } else if (!string.IsNullOrEmpty(listFieldLinkModel.FieldInternalName)) { var fieldInternalName = listFieldLinkModel.FieldInternalName; using (scope.StartScope()) { using (scope.StartTry()) { fields.GetByInternalNameOrTitle(fieldInternalName); } using (scope.StartCatch()) { } } } context.ExecuteQueryWithTrace(); if (!scope.HasException) { if (listFieldLinkModel.FieldId.HasGuidValue()) { field = fields.GetById(listFieldLinkModel.FieldId.Value); } else if (!string.IsNullOrEmpty(listFieldLinkModel.FieldInternalName)) { field = fields.GetByInternalNameOrTitle(listFieldLinkModel.FieldInternalName); } context.Load(field); context.Load(field, f => f.SchemaXml); context.ExecuteQueryWithTrace(); } return(field); }
public static Term LookupTerm(ClientContext clientContext, TermStore termStore, TermSet termSet, TaxonomyFieldDefinition termModel) { var context = clientContext; var site = clientContext.Site; Term result = null; TermGroup currenGroup = null; var termGroupName = termModel.TermGroupName; var termGroupId = termModel.TermGroupId; var isSiteCollectionGroup = termModel.IsSiteCollectionGroup; if (!string.IsNullOrEmpty(termGroupName)) { currenGroup = termStore.Groups.GetByName(termGroupName); context.Load(currenGroup); context.ExecuteQueryWithTrace(); } else if (termGroupId != null && termGroupId.HasGuidValue()) { currenGroup = termStore.Groups.GetById(termGroupId.Value); context.Load(currenGroup); context.ExecuteQueryWithTrace(); } else if (isSiteCollectionGroup == true) { currenGroup = termStore.GetSiteCollectionGroup(site, false); context.Load(currenGroup); context.ExecuteQueryWithTrace(); } if (currenGroup != null) { if (termModel.TermId.HasValue) { // by ID, the only one match var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { result = termStore.GetTerm(termModel.TermId.Value); context.Load(result); } using (scope.StartCatch()) { } } context.ExecuteQueryWithTrace(); } else if (!string.IsNullOrEmpty(termModel.TermName)) { var terms = termStore.GetTerms(new LabelMatchInformation(context) { Lcid = termModel.TermLCID, TermLabel = termModel.TermName, TrimUnavailable = false }); context.Load(terms, t => t.Include( i => i.Id, i => i.Name, i => i.TermSet, i => i.TermSet.Group, i => i.TermSet.Group.Name )); context.ExecuteQueryWithTrace(); result = terms.FirstOrDefault(t => t.TermSet.Group.Name == currenGroup.Name); if ((result == null) && (termSet != null)) // sometimes label match information does not return the term { var allTerms = termSet.GetAllTerms(); context.Load(allTerms, t => t.Include( i => i.Id, i => i.Name, i => i.TermSet, i => i.TermSet.Group, i => i.TermSet.Group.Name, i => i.Labels )); context.ExecuteQueryWithTrace(); result = allTerms.FirstOrDefault(t => (t.TermSet.Group.Name == currenGroup.Name) && (t.Labels.Any(l => l.Value == termModel.TermName && l.Language == termModel.TermLCID))); } } } else { if (termModel.TermId.HasValue) { var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { result = termStore.GetTerm(termModel.TermId.Value); context.Load(result); } using (scope.StartCatch()) { } } context.ExecuteQueryWithTrace(); } else if (!string.IsNullOrEmpty(termModel.TermName)) { var terms = termStore.GetTerms(new LabelMatchInformation(context) { Lcid = termModel.TermLCID, TermLabel = termModel.TermName, TrimUnavailable = false }); context.Load(terms); context.ExecuteQueryWithTrace(); result = terms.FirstOrDefault(); if ((result == null) && (termSet != null)) // sometimes label match information does not return the termset { var allTerms = termSet.GetAllTerms(); context.Load(allTerms, t => t.Include( i => i.Id, i => i.Name, i => i.TermSet, i => i.TermSet.Group, i => i.TermSet.Group.Name, i => i.Labels )); context.ExecuteQueryWithTrace(); result = allTerms.FirstOrDefault( t => (t.Labels.Any(l => l.Value == termModel.TermName && l.Language == termModel.TermLCID))); } } } if (result != null && result.ServerObjectIsNull == false) { context.Load(result); context.ExecuteQueryWithTrace(); return(result); } return(null); }
public static TermSet LookupTermSet(ClientRuntimeContext context, TermStore termStore, Site site, string termGroupName, Guid?termGroupId, bool?isSiteCollectionGroup, string termSetName, Guid?termSetId, int termSetLCID) { var storeContext = context; TermGroup currenGroup = null; if (!string.IsNullOrEmpty(termGroupName)) { currenGroup = termStore.Groups.GetByName(termGroupName); storeContext.Load(currenGroup); storeContext.ExecuteQueryWithTrace(); } else if (termGroupId != null && termGroupId.HasGuidValue()) { currenGroup = termStore.Groups.GetById(termGroupId.Value); storeContext.Load(currenGroup); storeContext.ExecuteQueryWithTrace(); } else if (isSiteCollectionGroup == true) { currenGroup = termStore.GetSiteCollectionGroup(site, false); storeContext.Load(currenGroup); storeContext.ExecuteQueryWithTrace(); } if (!string.IsNullOrEmpty(termSetName)) { if (currenGroup != null && (currenGroup.ServerObjectIsNull == false)) { TermSet termSet = null; var scope = new ExceptionHandlingScope(storeContext); using (scope.StartScope()) { using (scope.StartTry()) { termSet = currenGroup.TermSets.GetByName(termSetName); storeContext.Load(termSet); } using (scope.StartCatch()) { } } storeContext.ExecuteQueryWithTrace(); if (termSet != null && termSet.ServerObjectIsNull == false) { storeContext.Load(termSet, g => g.Id); storeContext.ExecuteQueryWithTrace(); return(termSet); } } else { var termSets = termStore.GetTermSetsByName(termSetName, termSetLCID); storeContext.Load(termSets); storeContext.ExecuteQueryWithTrace(); return(termSets.FirstOrDefault()); } } if (termSetId.HasGuidValue()) { if (currenGroup != null && (currenGroup.ServerObjectIsNull == false)) { TermSet termSet = null; var scope = new ExceptionHandlingScope(storeContext); using (scope.StartScope()) { using (scope.StartTry()) { termSet = currenGroup.TermSets.GetById(termSetId.Value); storeContext.Load(termSet); } using (scope.StartCatch()) { } } storeContext.ExecuteQueryWithTrace(); if (termSet != null && termSet.ServerObjectIsNull == false) { storeContext.Load(termSet, g => g.Id); storeContext.ExecuteQueryWithTrace(); return(termSet); } } else { TermSet termSet = null; var scope = new ExceptionHandlingScope(storeContext); using (scope.StartScope()) { using (scope.StartTry()) { termSet = termStore.GetTermSet(termSetId.Value); storeContext.Load(termSet); } using (scope.StartCatch()) { } } storeContext.ExecuteQueryWithTrace(); if (termSet != null && termSet.ServerObjectIsNull == false) { storeContext.Load(termSet, g => g.Id); storeContext.ExecuteQueryWithTrace(); return(termSet); } } } return(null); }
private Field DeployWebField(WebModelHost webModelHost, FieldDefinition fieldDefinition) { var id = fieldDefinition.Id; var web = webModelHost.HostWeb; TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "FindExistingWebField with Id: [{0}]", id); var context = web.Context; var scope = new ExceptionHandlingScope(context); Field field = null; using (scope.StartScope()) { using (scope.StartTry()) { web.Fields.GetById(id); } using (scope.StartCatch()) { } } TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()"); context.ExecuteQueryWithTrace(); if (!scope.HasException) { field = web.Fields.GetById(id); context.Load(field); PreloadProperties(field); TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Found site field with Id: [{0}]", id); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()"); context.ExecuteQueryWithTrace(); } else { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Cannot find site field with Id: [{0}]", id); } return EnsureField(context, field, web.Fields, fieldDefinition); }
public void EnsureConfigurationListInTenant(string hostWebUrl) { //get the base tenant admin urls var tenantStr = hostWebUrl.ToLower().Replace("-my", "").Substring(8); //remove my if it exists... tenantStr = tenantStr.Substring(0, tenantStr.IndexOf(".")); //create site collection using the Tenant object var tenantRootUri = new Uri(String.Format("https://{0}.sharepoint.com", tenantStr)); string realm = TokenHelper.GetRealmFromTargetUrl(tenantRootUri); var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantRootUri.Authority, realm).AccessToken; using (var adminContext = TokenHelper.GetClientContextWithAccessToken(tenantRootUri.ToString(), token)) { //Check if config list exists and if not, create the list and SubSiteAppUrl item. //Using ExceptionHandlingScope for this so that only one call is made to the server instead of multiple calls. ExceptionHandlingScope scope = new ExceptionHandlingScope(adminContext); using (scope.StartScope()) { using (scope.StartTry()) { List configList = adminContext.Web.Lists.GetByTitle(ConfigList); configList.Update(); } using (scope.StartCatch()) { ListCreationInformation listCreationInfo = new ListCreationInformation(); listCreationInfo.Title = ConfigList; listCreationInfo.TemplateType = (int)ListTemplateType.GenericList; List configList = adminContext.Web.Lists.Add(listCreationInfo); Field oField = configList.Fields.AddFieldAsXml("<Field DisplayName='Value' Type='Text' />", true, AddFieldOptions.DefaultValue); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem item = configList.AddItem(itemCreateInfo); item["Title"] = "SubSiteAppUrl"; item["Value"] = "https://localhost:44323"; item.Update(); } } adminContext.ExecuteQuery(); } }
public static Term LookupTerm(SiteModelHost currentSiteModelHost, TermStore termStore, TaxonomyFieldDefinition termModel) { var context = currentSiteModelHost.HostClientContext; Term result = null; if (termModel.TermId.HasValue) { var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { result = termStore.GetTerm(termModel.TermId.Value); context.Load(result); } using (scope.StartCatch()) { } } context.ExecuteQueryWithTrace(); } else if (!string.IsNullOrEmpty(termModel.TermName)) { var terms = termStore.GetTerms(new LabelMatchInformation(context) { Lcid = termModel.TermLCID, TermLabel = termModel.TermName, TrimUnavailable = false }); context.Load(terms); context.ExecuteQueryWithTrace(); result = terms.FirstOrDefault(); } if (result != null && result.ServerObjectIsNull == false) { context.Load(result); context.ExecuteQueryWithTrace(); return result; } return null; }
private object ExecuteObjectSearch(string serverRelativePath, Web web) { var ctx = web.Context; File file; Folder folder; var scope = new ExceptionHandlingScope(ctx); var tryFileFirst = serverRelativePath.Split(PathSeparator.ToCharArray()).Last().Contains("."); if (tryFileFirst) { using (scope.StartScope()) { using (scope.StartTry()) { file = web.GetFileByServerRelativeUrl(serverRelativePath); ctx.Load(file); } using (scope.StartCatch()) { folder = web.GetFolderByServerRelativeUrl(serverRelativePath); ctx.Load(folder); } } } else { using (scope.StartScope()) { using (scope.StartTry()) { folder = web.GetFolderByServerRelativeUrl(serverRelativePath); ctx.Load(folder); } using (scope.StartCatch()) { file = web.GetFileByServerRelativeUrl(serverRelativePath); ctx.Load(file); } } } try { ctx.ExecuteQueryRetry(); } catch (Exception e) { return e; } //Check if we got data if (IsPropertyAvailable(file, "Name")) { return file; } else if (IsPropertyAvailable(folder, "Name")) { return folder; } return null; }
private string TryRecycleList(String listTitle, SPRemoteEventProperties properties) { string errorMessage = String.Empty; using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, useAppWeb: false)) { if (clientContext != null) { // Get references to all the objects you are going to need. ListCollection allLists = clientContext.Web.Lists; IEnumerable<List> matchingLists = clientContext.LoadQuery(allLists.Where(list => list.Title == listTitle)); RecycleBinItemCollection bin = clientContext.Web.RecycleBin; IEnumerable<RecycleBinItem> matchingRecycleBinItems = clientContext.LoadQuery(bin.Where(item => item.Title == listTitle)); clientContext.ExecuteQuery(); List foundList = matchingLists.FirstOrDefault(); RecycleBinItem recycledList = matchingRecycleBinItems.FirstOrDefault(); // Delegate the rollback logic to the SharePoint server. ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext); using (scope.StartScope()) { using (scope.StartTry()) { // Check to see that a user hasn't already recycled the list in the SharePoint UI. // If it is still there, recycle it. ConditionalScope condScope = new ConditionalScope(clientContext, () => foundList.ServerObjectIsNull.Value == false, true); using (condScope.StartScope()) { // Looks crazy to test for nullity inside a test for nullity, // but without this inner test, foundList.Recycle() throws a null reference // exception when the client side runtime is creating the XML to // send to the server. if (foundList != null) { foundList.Recycle(); } } // To test that your StartCatch block runs, uncomment the following two lines // and put them somewhere in the StartTry block. //List fakeList = clientContext.Web.Lists.GetByTitle("NoSuchList"); //clientContext.Load(fakeList); } using (scope.StartCatch()) { // Check to see that the list is in the Recycle Bin. // A user might have manually deleted the list from the Recycle Bin, // or StartTry block may have errored before it recycled the list. // If it is in the Recycle Bin, restore it. ConditionalScope condScope = new ConditionalScope(clientContext, () => recycledList.ServerObjectIsNull.Value == false, true); using (condScope.StartScope()) { // Another test within a test to avoid a null reference. if (recycledList != null) { recycledList.Restore(); } } } using (scope.StartFinally()) { } } clientContext.ExecuteQuery(); if (scope.HasException) { errorMessage = String.Format("{0}: {1}; {2}; {3}; {4}; {5}", scope.ServerErrorTypeName, scope.ErrorMessage, scope.ServerErrorDetails, scope.ServerErrorValue, scope.ServerStackTrace, scope.ServerErrorCode); } } } return errorMessage; }
protected Field FindExistingListField(List list, FieldDefinition fieldModel) { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "FindListField with Id: [{0}]", fieldModel.Id); var context = list.Context; Field field; var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { field = list.Fields.GetById(fieldModel.Id); context.Load(field); } using (scope.StartCatch()) { field = null; //context.Load(field); } } context.ExecuteQueryWithTrace(); if (!scope.HasException) { field = list.Fields.GetById(fieldModel.Id); context.Load(field); TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Found list field with Id: [{0}]", fieldModel.Id); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()"); context.ExecuteQueryWithTrace(); } else { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Cannot find list field with Id: [{0}]", fieldModel.Id); } return field; }
protected TermGroup FindGroup(TermStoreModelHost storeModelHost, TaxonomyTermGroupDefinition groupModel) { var termStore = storeModelHost.HostTermStore; var context = termStore.Context; TermGroup currentGroup = null; if (groupModel.IsSiteCollectionGroup) { currentGroup = FindSiteCollectionGroup(storeModelHost, groupModel); return(currentGroup); } if (groupModel.Id.HasValue) { var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { currentGroup = termStore.Groups.GetById(groupModel.Id.Value); context.Load(currentGroup); } using (scope.StartCatch()) { } } } else if (!string.IsNullOrEmpty(groupModel.Name)) { var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { currentGroup = termStore.Groups.GetByName(groupModel.Name); context.Load(currentGroup); } using (scope.StartCatch()) { } } } context.ExecuteQueryWithTrace(); if (currentGroup != null && currentGroup.ServerObjectIsNull.HasValue && currentGroup.ServerObjectIsNull == false) { context.Load(currentGroup, g => g.Id); context.Load(currentGroup, g => g.Name); context.ExecuteQueryWithTrace(); return(currentGroup); } return(null); }
static public void CreateAnnouncementsList(ClientContext clientContext) { string listTitle = "Announcements"; // delete list if it exists ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext); using (scope.StartScope()) { using (scope.StartTry()) { clientContext.Web.Lists.GetByTitle(listTitle).DeleteObject(); } using (scope.StartCatch()) { } } // create and initialize ListCreationInformation object ListCreationInformation listInformation = new ListCreationInformation(); listInformation.Title = listTitle; listInformation.Url = "Lists/Announcements"; listInformation.QuickLaunchOption = QuickLaunchOptions.On; listInformation.TemplateType = (int)ListTemplateType.Announcements; // Add ListCreationInformation to lists collection and return list object List list = clientContext.Web.Lists.Add(listInformation); // modify additional list properties and update list.OnQuickLaunch = true; list.EnableAttachments = false; list.Update(); // send command to server to create list clientContext.ExecuteQuery(); clientContext.Load(list); clientContext.ExecuteQuery(); string urlEventReceiver = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + @"/Services/AnnouncementsEventReceiver.svc"; EventReceiverDefinitionCreationInformation erci1 = new EventReceiverDefinitionCreationInformation(); erci1.ReceiverName = "ItemAdding"; erci1.EventType = EventReceiverType.ItemAdding; erci1.ReceiverUrl = urlEventReceiver; erci1.SequenceNumber = 1000; EventReceiverDefinition er1 = list.EventReceivers.Add(erci1); er1.Update(); EventReceiverDefinitionCreationInformation erci2 = new EventReceiverDefinitionCreationInformation(); erci2.ReceiverName = "ItemUpdating"; erci2.EventType = EventReceiverType.ItemUpdating; erci2.ReceiverUrl = urlEventReceiver; erci2.SequenceNumber = 1000; EventReceiverDefinition er2 = list.EventReceivers.Add(erci2); er2.Update(); clientContext.ExecuteQuery(); ListItemCreationInformation lici = new ListItemCreationInformation(); var item1 = list.AddItem(lici); item1["Title"] = "SharePoint introduces new app model"; item1["Body"] = "<div>Developers wonder what happened to solutions.</div>"; item1["Expires"] = DateTime.Today.AddYears(10); item1.Update(); var item2 = list.AddItem(lici); item2["Title"] = "All SharePoint developers must now learn JavaScript"; item2["Body"] = "<div>Some developers are more excited than others.</div>"; item2["Expires"] = DateTime.Today.AddYears(1); item2.Update(); var item3 = list.AddItem(lici); item3["Title"] = "CSOM programming is super fun"; item3["Body"] = "<div>Just ask my mom.</div>"; item3["Expires"] = DateTime.Today.AddDays(7); item3.Update(); clientContext.ExecuteQuery(); }
protected TermGroup FindGroup(TermStoreModelHost storeModelHost, TaxonomyTermGroupDefinition groupModel) { var termStore = storeModelHost.HostTermStore; var context = termStore.Context; TermGroup currentGroup = null; if (groupModel.IsSiteCollectionGroup) { currentGroup = FindSiteCollectionGroup(storeModelHost, groupModel); return currentGroup; } if (groupModel.Id.HasValue) { var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { currentGroup = termStore.Groups.GetById(groupModel.Id.Value); context.Load(currentGroup); } using (scope.StartCatch()) { } } } else if (!string.IsNullOrEmpty(groupModel.Name)) { var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { currentGroup = termStore.Groups.GetByName(groupModel.Name); context.Load(currentGroup); } using (scope.StartCatch()) { } } } context.ExecuteQueryWithTrace(); if (currentGroup != null && currentGroup.ServerObjectIsNull == false) { context.Load(currentGroup, g => g.Id); context.Load(currentGroup, g => g.Name); context.ExecuteQueryWithTrace(); return currentGroup; } return null; }
protected Web GetExistingWeb(Site site, Web parentWeb, string currentWebUrl) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Entering GetExistingWeb()"); var result = false; var srcUrl = currentWebUrl.ToLower().Trim('/').Trim('\\'); // for self-hosting and '/' if (parentWeb.Url.ToLower().Trim('/').Trim('\\').EndsWith(srcUrl)) return parentWeb; var context = parentWeb.Context; Web web = null; var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { web = site.OpenWeb(currentWebUrl); } using (scope.StartCatch()) { } } TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()"); context.ExecuteQueryWithTrace(); if (!scope.HasException && web != null && web.ServerObjectIsNull == false) { TraceService.InformationFormat((int)LogEventId.ModelProvisionCoreCall, "Found web with URL: [{0}]", currentWebUrl); context.Load(web); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()"); context.ExecuteQueryWithTrace(); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Exciting GetExistingWeb()"); return web; } TraceService.InformationFormat((int)LogEventId.ModelProvisionCoreCall, "Can't find web with URL: [{0}]. Returning NULL.", currentWebUrl); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Exciting GetExistingWeb()"); return null; }
private static List LoadCurrentList(Web web, ListDefinition listModel) { var context = web.Context; List currentList = null; var listUrl = UrlUtility.CombineUrl(web.ServerRelativeUrl, listModel.GetListUrl()); Folder folder = null; var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { folder = web.GetFolderByServerRelativeUrl(listUrl); context.Load(folder); } using (scope.StartCatch()) { } } context.ExecuteQueryWithTrace(); if (!scope.HasException && folder != null && folder.ServerObjectIsNull != true) { folder = web.GetFolderByServerRelativeUrl(listUrl); context.Load(folder.Properties); context.ExecuteQueryWithTrace(); var listId = new Guid(folder.Properties["vti_listname"].ToString()); var list = web.Lists.GetById(listId); context.Load(list); context.ExecuteQueryWithTrace(); currentList = list; } return currentList; }
public void DeleteListItems(string listName, int[] ids, IProgress <string> progress = null) // Action<string, long, long> reportProgress = null, { if (string.IsNullOrEmpty(listName)) { throw new ArgumentException(string.Format("{0} is null or empty", listName), "listName"); } if (ids == null) { throw new ArgumentException("the ids is null", "ids"); } var scopes = new Dictionary <int, ExceptionHandlingScope>(); var oList = _ctx.Web.Lists.GetByTitle(listName); _ctx.Load(oList); _ctx.Load(oList.Fields, fields => fields .Include(f => f.CanBeDeleted, f => f.InternalName, f => f.StaticName, f => f.FieldTypeKind, f => f.Title) .Where(f => f.FieldTypeKind != FieldType.Attachments && f.CanBeDeleted)); _ctx.ExecuteQuery(); if (oList != null && oList.ItemCount > 0) { var index = 0; foreach (var id in ids) { ExceptionHandlingScope scope = new ExceptionHandlingScope(_ctx); scopes.Add(id, scope); using (scope.StartScope()) { using (scope.StartTry()) { index++; var oListItem = oList.GetItemById(id); oListItem.DeleteObject(); } using (scope.StartCatch()) { } } if (index % 100 == 0) { _ctx.ExecuteQuery(); if (progress != null) { string message = string.Format("Lista:{0}\nPor favor! Aguarde enquanto os registros são deletados.\n{1} registros deletados de {2} ", oList.Title, index, oList.ItemCount); progress.Report(message); } } } _ctx.ExecuteQuery(); var query = scopes.Where(s => s.Value.ServerErrorCode != -1); foreach (var q in query) { if (progress != null) { string message = string.Format("Um erro ocorreu no item ({0})\r\nErrorCode:{1}\r\nError:{2}", q.Key, q.Value.ServerErrorCode, q.Value.ErrorMessage); progress.Report(message); } } } //try //{ // var oList = _ctx.Web.Lists.GetByTitle(listName); // _ctx.Load(oList); // _ctx.Load(oList.Fields, fields => fields // .Include(f => f.CanBeDeleted, // f => f.InternalName, f => f.StaticName, f => f.FieldTypeKind, f => f.Title) // .Where(f => f.FieldTypeKind != FieldType.Attachments && f.CanBeDeleted)); // _ctx.ExecuteQuery(); // if (oList != null && oList.ItemCount > 0) // { // var index = 0; // foreach (var id in ids) // { // index++; // var oListItem = oList.GetItemById(id); // oListItem.DeleteObject(); // if (index % 25 == 0) // { // _ctx.ExecuteQuery(); // if (progress != null) // { // string message = string.Format("Lista:{0}\nPor favor! Aguarde enquanto os registros são deletados.\n{1} registros deletados de {2} ", oList.Title, index, oList.ItemCount); // progress.Report(message); // } // } // } // _ctx.ExecuteQuery(); // } //} //catch (Exception ex) //{ // throw ex; //} }
public async Task DeleteListItemsAsync(string listName, string query = null, IProgress <string> progress = null) { await Task.Run(() => { ListItemCollectionPosition licp = null; var oList = _ctx.Web.Lists.GetByTitle(listName); _ctx.Load(oList); _ctx.Load(oList.Fields, fields => fields .Include(f => f.CanBeDeleted, f => f.InternalName, f => f.StaticName, f => f.FieldTypeKind, f => f.Title) .Where(f => f.FieldTypeKind != FieldType.Attachments && f.CanBeDeleted)); _ctx.ExecuteQuery(); var scopes = new Dictionary <int, ExceptionHandlingScope>(); if (oList != null && oList.ItemCount > 0) { var itemCount = oList.ItemCount; var currentCount = 0; do { var camlQuery = new CamlQuery(); camlQuery.ViewXml = string.IsNullOrEmpty(query) ? @"<View><ViewFields><FieldRef Name='ID'/></ViewFields><RowLimit>100</RowLimit></View>" : query; camlQuery.ListItemCollectionPosition = licp; var items = oList.GetItems(camlQuery); _ctx.Load(items, its => its.Include(item => item["ID"], item => item["Created"], item => item["Modified"])); _ctx.ExecuteQuery(); licp = items.ListItemCollectionPosition; currentCount += items.Count; foreach (var item in items.ToList()) { var scope = new ExceptionHandlingScope(_ctx); scopes.Add(Convert.ToInt32(item["ID"].ToString()), scope); using (scope.StartScope()) { using (scope.StartTry()) { item.DeleteObject(); } using (scope.StartCatch()) { } } if (progress != null) { string message = string.Format("Lista:{0}\nPor favor! Aguarde enquanto os registros são deletados.\n{1} registros deletados de {2} ", oList.Title, currentCount, itemCount); progress.Report(message); } } _ctx.ExecuteQuery(); var erros = scopes.Where(s => s.Value.ServerErrorCode != -1); foreach (var erro in erros) { if (progress != null) { string message = string.Format("Um erro ocorreu no item ({0})\r\nErrorCode:{1}\r\nError:{2}", erro.Key, erro.Value.ServerErrorCode, erro.Value.ErrorMessage); progress.Report(message); } } } while (licp != null); } //try //{ // ListItemCollectionPosition licp = null; // var oList = _ctx.Web.Lists.GetByTitle(listName); // _ctx.Load(oList); // _ctx.Load(oList.Fields, fields => fields // .Include(f => f.CanBeDeleted, // f => f.InternalName, f => f.StaticName, f => f.FieldTypeKind, f => f.Title) // .Where(f => f.FieldTypeKind != FieldType.Attachments && f.CanBeDeleted)); // _ctx.ExecuteQuery(); // if (oList != null && oList.ItemCount > 0) // { // var itemCount = oList.ItemCount; // var currentCount = 0; // do // { // var camlQuery = new CamlQuery(); // camlQuery.ViewXml = string.IsNullOrEmpty(query) ? @"<View><ViewFields><FieldRef Name='ID'/></ViewFields><RowLimit>100</RowLimit></View>" : query; // camlQuery.ListItemCollectionPosition = licp; // var items = oList.GetItems(camlQuery); // _ctx.Load(items, its => its.Include(item => item["ID"], item => item["Created"], item => item["Modified"])); // _ctx.ExecuteQuery(); // licp = items.ListItemCollectionPosition; // currentCount += items.Count; // foreach (var item in items.ToList()) // { // item.DeleteObject(); // } // _ctx.ExecuteQuery(); // if (progress != null) // { // string message = string.Format("Lista:{0}\nPor favor! Aguarde enquanto os registros são deletados.\n{1} registros deletados de {2} ", oList.Title, currentCount, itemCount); // progress.Report(message); // } // } while (licp != null); // } //} //catch (Exception ex) //{ // throw ex; //} }); }
public static Term LookupTerm(ClientContext clientContext, TermStore termStore, TermSet termSet, TaxonomyFieldDefinition termModel) { var context = clientContext; var site = clientContext.Site; Term result = null; TermGroup currenGroup = null; var termGroupName = termModel.TermGroupName; var termGroupId = termModel.TermGroupId; var isSiteCollectionGroup = termModel.IsSiteCollectionGroup; if (!string.IsNullOrEmpty(termGroupName)) { currenGroup = termStore.Groups.GetByName(termGroupName); context.Load(currenGroup); context.ExecuteQueryWithTrace(); } else if (termGroupId != null && termGroupId.HasGuidValue()) { currenGroup = termStore.Groups.GetById(termGroupId.Value); context.Load(currenGroup); context.ExecuteQueryWithTrace(); } else if (isSiteCollectionGroup == true) { currenGroup = termStore.GetSiteCollectionGroup(site, false); context.Load(currenGroup); context.ExecuteQueryWithTrace(); } if (currenGroup != null) { if (termModel.TermId.HasValue) { // by ID, the only one match var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { result = termStore.GetTerm(termModel.TermId.Value); context.Load(result); } using (scope.StartCatch()) { } } context.ExecuteQueryWithTrace(); } else if (!string.IsNullOrEmpty(termModel.TermName)) { var terms = termStore.GetTerms(new LabelMatchInformation(context) { Lcid = termModel.TermLCID, TermLabel = termModel.TermName, TrimUnavailable = false }); context.Load(terms, t => t.Include( i => i.Id, i => i.Name, i => i.TermSet, i => i.TermSet.Group, i => i.TermSet.Group.Name )); context.ExecuteQueryWithTrace(); result = terms.FirstOrDefault(t => t.TermSet.Group.Name == currenGroup.Name); if ( (result == null) && (termSet != null )) // sometimes label match information does not return the term { var allTerms = termSet.GetAllTerms(); context.Load(allTerms, t => t.Include( i => i.Id, i => i.Name, i => i.TermSet, i => i.TermSet.Group, i => i.TermSet.Group.Name, i => i.Labels )); context.ExecuteQueryWithTrace(); result = allTerms.FirstOrDefault(t => (t.TermSet.Group.Name == currenGroup.Name) && (t.Labels.Any(l=>l.Value == termModel.TermName && l.Language == termModel.TermLCID))); } } } else { if (termModel.TermId.HasValue) { var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { result = termStore.GetTerm(termModel.TermId.Value); context.Load(result); } using (scope.StartCatch()) { } } context.ExecuteQueryWithTrace(); } else if (!string.IsNullOrEmpty(termModel.TermName)) { var terms = termStore.GetTerms(new LabelMatchInformation(context) { Lcid = termModel.TermLCID, TermLabel = termModel.TermName, TrimUnavailable = false }); context.Load(terms); context.ExecuteQueryWithTrace(); result = terms.FirstOrDefault(); if ((result == null) && (termSet != null)) // sometimes label match information does not return the termset { var allTerms = termSet.GetAllTerms(); context.Load(allTerms, t => t.Include( i => i.Id, i => i.Name, i => i.TermSet, i => i.TermSet.Group, i => i.TermSet.Group.Name, i => i.Labels )); context.ExecuteQueryWithTrace(); result = allTerms.FirstOrDefault( t => (t.Labels.Any(l=>l.Value == termModel.TermName && l.Language == termModel.TermLCID))); } } } if (result != null && result.ServerObjectIsNull == false) { context.Load(result); context.ExecuteQueryWithTrace(); return result; } return null; }
private object ExecuteObjectSearch(string serverRelativePath, Web web) { //Workaround for CSOM v15.0 to not get deleted items from object data web.ClearObjectData(); var ctx = web.Context; File file; Folder folder; var scope = new ExceptionHandlingScope(ctx); var tryFileFirst = serverRelativePath.Split(PathSeparator.ToCharArray()).Last().Contains("."); if (tryFileFirst) { using (scope.StartScope()) { using (scope.StartTry()) { file = web.GetFileByServerRelativeUrl(serverRelativePath); ctx.Load(file); } using (scope.StartCatch()) { folder = web.GetFolderByServerRelativeUrl(serverRelativePath); ctx.Load(folder); } } } else { using (scope.StartScope()) { using (scope.StartTry()) { folder = web.GetFolderByServerRelativeUrl(serverRelativePath); ctx.Load(folder); } using (scope.StartCatch()) { file = web.GetFileByServerRelativeUrl(serverRelativePath); ctx.Load(file); } } } try { ctx.ExecuteQueryRetry(); } catch (Exception e) { return(e); } //Check if we got data if (IsPropertyAvailable(file, "Name")) { return(file); } else if (IsPropertyAvailable(folder, "Name")) { return(folder); } return(null); }
protected File SearchFileByName(List list, Folder folder, string pageName) { var context = list.Context; if (folder != null) { if (!folder.IsPropertyAvailable("ServerRelativeUrl") // || !folder.IsPropertyAvailable("Properties")) ) { folder.Context.Load(folder, f => f.ServerRelativeUrl); //folder.Context.Load(folder, f => f.Properties); folder.Context.ExecuteQueryWithTrace(); } } // one more time.. var dQuery = new CamlQuery(); string QueryString = "<View><Query><Where>" + "<Eq>" + "<FieldRef Name=\"FileLeafRef\"/>" + "<Value Type=\"Text\">" + pageName + "</Value>" + "</Eq>" + "</Where></Query></View>"; dQuery.ViewXml = QueryString; if (folder != null) { dQuery.FolderServerRelativeUrl = folder.ServerRelativeUrl; } var collListItems = list.GetItems(dQuery); context.Load(collListItems); context.ExecuteQueryWithTrace(); var item = collListItems.FirstOrDefault(); if (item != null) { return(item.File); } //one more time // by full path var fileServerRelativePath = UrlUtility.CombineUrl(folder.ServerRelativeUrl, pageName); File file = null; var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { file = list.ParentWeb.GetFileByServerRelativeUrl(fileServerRelativePath); context.Load(file); } using (scope.StartCatch()) { } } context.ExecuteQueryWithTrace(); // Forms folder im the libraries // otherwise pure list items search if (!scope.HasException && file != null && file.ServerObjectIsNull != null) { context.Load(file); context.Load(file, f => f.Exists); context.ExecuteQueryWithTrace(); if (file.Exists) { return(file); } } return(null); }
static void DeleteAllTopNavNodes() { // delete all existing nodes for (int index = (TopNavNodes.Count - 1); index >= 0; index--) { ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext); using (scope.StartScope()) { using (scope.StartTry()) { TopNavNodes[index].DeleteObject(); } using (scope.StartCatch()) { } } clientContext.ExecuteQuery(); } clientContext.Load(TopNavNodes); clientContext.ExecuteQuery(); }
private static List LoadCurrentList(Web web, ListDefinition listModel) { var context = web.Context; List currentList = null; #pragma warning disable 618 var listUrl = UrlUtility.CombineUrl(web.ServerRelativeUrl, listModel.GetListUrl()); #pragma warning restore 618 Folder folder; var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { folder = web.GetFolderByServerRelativeUrl(listUrl); context.Load(folder); } using (scope.StartCatch()) { } } context.ExecuteQueryWithTrace(); if (!scope.HasException && folder != null && folder.ServerObjectIsNull != true) { #if !NET35 folder = web.GetFolderByServerRelativeUrl(listUrl); context.Load(folder.Properties); context.ExecuteQueryWithTrace(); var listId = new Guid(folder.Properties["vti_listname"].ToString()); var list = web.Lists.GetById(listId); context.Load(list); if (listModel.IndexedRootFolderPropertyKeys.Any()) { context.Load(list, l => l.RootFolder.Properties); } context.ExecuteQueryWithTrace(); currentList = list; #endif #if NET35 // SP2010 CSOM hack // http://impl.com/questions/4284722/sharepoint-2010-client-object-model-get-a-list-item-from-a-url var listQuery = from list in web.Lists where list.RootFolder.ServerRelativeUrl == listUrl select list; var queryResult = context.LoadQuery(listQuery); context.ExecuteQueryWithTrace(); var resultList = queryResult.FirstOrDefault(); currentList = resultList; #endif } return(currentList); }
public virtual Field GetField(FieldCollection fields, Guid?fieldId, string fieldInternalName, string fieldTitle) { var context = fields.Context; var scope = new ExceptionHandlingScope(context); Field field = null; if (fieldId.HasGuidValue()) { var id = fieldId.Value; using (scope.StartScope()) { using (scope.StartTry()) { field = fields.GetById(id); context.Load(field); } using (scope.StartCatch()) { } } context.ExecuteQueryWithTrace(); } else if (!string.IsNullOrEmpty(fieldInternalName)) { using (scope.StartScope()) { using (scope.StartTry()) { field = fields.GetByInternalNameOrTitle(fieldInternalName); context.Load(field); } using (scope.StartCatch()) { } } context.ExecuteQueryWithTrace(); } else if (!string.IsNullOrEmpty(fieldTitle)) { using (scope.StartScope()) { using (scope.StartTry()) { field = fields.GetByTitle(fieldTitle); context.Load(field); } using (scope.StartCatch()) { } } context.ExecuteQueryWithTrace(); } if (!scope.HasException && field != null && field.ServerObjectIsNull == false) { if (fieldId.HasGuidValue()) { var id = fieldId.Value; field = fields.GetById(id); } else if (!string.IsNullOrEmpty(fieldInternalName)) { field = fields.GetByInternalNameOrTitle(fieldInternalName); } else if (!string.IsNullOrEmpty(fieldTitle)) { field = fields.GetByTitle(fieldTitle); } context.Load(field); context.Load(field, f => f.SchemaXml); context.ExecuteQueryWithTrace(); } else { // falback on internal name var internalNameScope = new ExceptionHandlingScope(context); using (internalNameScope.StartScope()) { using (internalNameScope.StartTry()) { fields.GetByInternalNameOrTitle(fieldInternalName); } using (internalNameScope.StartCatch()) { } } context.ExecuteQueryWithTrace(); if (!internalNameScope.HasException) { var t = fields.GetByInternalNameOrTitle(fieldInternalName); context.Load(t); context.Load(t, f => f.SchemaXml); context.ExecuteQueryWithTrace(); return(t); } return(null); } return(field); }
private Field DeployListField(ListModelHost modelHost, FieldDefinition fieldModel) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Deploying list field"); var list = modelHost.HostList; var context = list.Context; var scope = new ExceptionHandlingScope(context); Field field; using (scope.StartScope()) { using (scope.StartTry()) { field = list.Fields.GetById(fieldModel.Id); context.Load(field); } using (scope.StartCatch()) { } } TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()"); context.ExecuteQueryWithTrace(); if (!scope.HasException) { field = list.Fields.GetById(fieldModel.Id); context.Load(field); TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Found site list with Id: [{0}]", fieldModel.Id); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()"); context.ExecuteQueryWithTrace(); return EnsureField(context, field, list.Fields, fieldModel); } TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Cannot find list field with Id: [{0}]", fieldModel.Id); return EnsureField(context, null, list.Fields, fieldModel); }
internal void LoadWebPartsInWikiContentFromServer(List <WebPartEntity> webparts, File wikiPage, List <WebPartPlaceHolder> webPartsToRetrieve) { // Load web part manager and use it to load each web part LimitedWebPartManager limitedWPManager = wikiPage.GetLimitedWebPartManager(PersonalizationScope.Shared); cc.Load(limitedWPManager); foreach (var webPartToRetrieve in webPartsToRetrieve) { // Check if the web part was loaded when we loaded the web parts collection via the web part manager if (!Guid.TryParse(webPartToRetrieve.Id, out Guid webPartToRetrieveGuid)) { // Skip since guid is not valid continue; } // Sometimes the returned wiki html contains web parts which are not anymore on the page...using the ExceptionHandlingScope // we can handle these errors server side while just doing a single roundtrip var scope = new ExceptionHandlingScope(cc); using (scope.StartScope()) { using (scope.StartTry()) { webPartToRetrieve.WebPartDefinition = limitedWPManager.WebParts.GetByControlId(webPartToRetrieve.ControlId); cc.Load(webPartToRetrieve.WebPartDefinition, wp => wp.Id, wp => wp.WebPart.ExportMode, wp => wp.WebPart.Title, wp => wp.WebPart.ZoneIndex, wp => wp.WebPart.IsClosed, wp => wp.WebPart.Hidden, wp => wp.WebPart.Properties); } using (scope.StartCatch()) { } } } cc.ExecuteQueryRetry(); // Load the web part XML for the web parts that do allow it bool isDirty = false; foreach (var webPartToRetrieve in webPartsToRetrieve) { // Important to only process the web parts that did not return an error in the previous server call if (webPartToRetrieve.WebPartDefinition != null && (webPartToRetrieve.WebPartDefinition.ServerObjectIsNull.HasValue && webPartToRetrieve.WebPartDefinition.ServerObjectIsNull.Value == false)) { // Retry to load the properties, sometimes they're not retrieved webPartToRetrieve.WebPartDefinition.EnsureProperty(wp => wp.Id); webPartToRetrieve.WebPartDefinition.WebPart.EnsureProperties(wp => wp.ExportMode, wp => wp.Title, wp => wp.ZoneIndex, wp => wp.IsClosed, wp => wp.Hidden, wp => wp.Properties); if (webPartToRetrieve.WebPartDefinition.WebPart.ExportMode == WebPartExportMode.All) { webPartToRetrieve.WebPartXml = limitedWPManager.ExportWebPart(webPartToRetrieve.WebPartDefinition.Id); isDirty = true; } } } if (isDirty) { cc.ExecuteQueryRetry(); } // Determine the web part type and store it in the web parts array foreach (var webPartToRetrieve in webPartsToRetrieve) { if (webPartToRetrieve.WebPartDefinition != null && (webPartToRetrieve.WebPartDefinition.ServerObjectIsNull.HasValue && webPartToRetrieve.WebPartDefinition.ServerObjectIsNull.Value == false)) { // Important to only process the web parts that did not return an error in the previous server call if (webPartToRetrieve.WebPartDefinition.WebPart.ExportMode != WebPartExportMode.All) { // Use different approach to determine type as we can't export the web part XML without indroducing a change webPartToRetrieve.WebPartType = GetTypeFromProperties(webPartToRetrieve.WebPartDefinition.WebPart.Properties); } else { webPartToRetrieve.WebPartType = GetType(webPartToRetrieve.WebPartXml.Value); } webparts.Add(new WebPartEntity() { Title = webPartToRetrieve.WebPartDefinition.WebPart.Title, Type = webPartToRetrieve.WebPartType, Id = webPartToRetrieve.WebPartDefinition.Id, ServerControlId = webPartToRetrieve.Id, Row = webPartToRetrieve.Row, Column = webPartToRetrieve.Column, Order = webPartToRetrieve.Order, ZoneId = "", ZoneIndex = (uint)webPartToRetrieve.WebPartDefinition.WebPart.ZoneIndex, IsClosed = webPartToRetrieve.WebPartDefinition.WebPart.IsClosed, Hidden = webPartToRetrieve.WebPartDefinition.WebPart.Hidden, Properties = Properties(webPartToRetrieve.WebPartDefinition.WebPart.Properties, webPartToRetrieve.WebPartType, webPartToRetrieve.WebPartXml == null ? "" : webPartToRetrieve.WebPartXml.Value), }); } } }
/// <summary> /// Analyses a wiki page /// </summary> /// <returns>Information about the analyzed wiki page</returns> public Tuple <PageLayout, List <WebPartEntity> > Analyze() { List <WebPartEntity> webparts = new List <WebPartEntity>(); //Load the page var wikiPageUrl = page[Constants.FileRefField].ToString(); var wikiPage = cc.Web.GetFileByServerRelativeUrl(wikiPageUrl); cc.Load(wikiPage); cc.ExecuteQueryRetry(); // Load wiki content in HTML parser if (page.FieldValues[Constants.WikiField] == null) { throw new Exception("WikiField contents was set to null, this is an invalid and empty wiki page."); } var pageContents = page.FieldValues[Constants.WikiField].ToString(); var htmlDoc = parser.Parse(pageContents); var layout = GetLayout(htmlDoc); if (string.IsNullOrEmpty(pageContents)) { layout = PageLayout.Wiki_OneColumn; } List <WebPartPlaceHolder> webPartsToRetrieve = new List <WebPartPlaceHolder>(); var rows = htmlDoc.All.Where(p => p.LocalName == "tr"); int rowCount = 0; foreach (var row in rows) { rowCount++; var columns = row.Children.Where(p => p.LocalName == "td" && p.Parent == row); int colCount = 0; foreach (var column in columns) { colCount++; var contentHost = column.Children.Where(p => p.LocalName == "div" && (p.ClassName != null && p.ClassName.Equals("ms-rte-layoutszone-outer", StringComparison.InvariantCultureIgnoreCase))).FirstOrDefault(); if (contentHost != null && contentHost.FirstElementChild != null) { var content = contentHost.FirstElementChild; // Drop elements which we anyhow can't transform and/or which are stripped out from RTE CleanHtml(content, htmlDoc); StringBuilder textContent = new StringBuilder(); int order = 0; foreach (var node in content.ChildNodes) { // Do we find a web part inside... if (((node as IHtmlElement) != null) && ContainsWebPart(node as IHtmlElement)) { var extraText = StripWebPart(node as IHtmlElement); string extraTextAfterWebPart = null; string extraTextBeforeWebPart = null; if (!string.IsNullOrEmpty(extraText)) { // Should be, but checking anyhow int webPartMarker = extraText.IndexOf(webPartMarkerString); if (webPartMarker > -1) { extraTextBeforeWebPart = extraText.Substring(0, webPartMarker); extraTextAfterWebPart = extraText.Substring(webPartMarker + webPartMarkerString.Length); // there could have been multiple web parts in a row (we don't support text inbetween them for now)...strip the remaining markers extraTextBeforeWebPart = extraTextBeforeWebPart.Replace(webPartMarkerString, ""); extraTextAfterWebPart = extraTextAfterWebPart.Replace(webPartMarkerString, ""); } } if (!string.IsNullOrEmpty(extraTextBeforeWebPart)) { textContent.AppendLine(extraTextBeforeWebPart); } // first insert text part (if it was available) if (!string.IsNullOrEmpty(textContent.ToString())) { order++; webparts.Add(CreateWikiTextPart(textContent.ToString(), rowCount, colCount, order)); textContent.Clear(); } // then process the web part order++; Regex regexClientIds = new Regex(@"id=\""div_(?<ControlId>(\w|\-)+)"); if (regexClientIds.IsMatch((node as IHtmlElement).OuterHtml)) { foreach (Match webPartMatch in regexClientIds.Matches((node as IHtmlElement).OuterHtml)) { // Store the web part we need, will be retrieved afterwards to optimize performance string serverSideControlId = webPartMatch.Groups["ControlId"].Value; var serverSideControlIdToSearchFor = $"g_{serverSideControlId.Replace("-", "_")}"; webPartsToRetrieve.Add(new WebPartPlaceHolder() { ControlId = serverSideControlIdToSearchFor, Id = serverSideControlId, Row = rowCount, Column = colCount, Order = order }); } } // Process the extra text that was positioned after the web part (if any) if (!string.IsNullOrEmpty(extraTextAfterWebPart)) { textContent.AppendLine(extraTextAfterWebPart); } } else { if (!string.IsNullOrEmpty(node.TextContent.Trim()) && node.TextContent.Trim() == "\n") { // ignore, this one is typically added after a web part } else { if (node.HasChildNodes) { textContent.AppendLine((node as IHtmlElement).OuterHtml); } else { if (!string.IsNullOrEmpty(node.TextContent.Trim())) { textContent.AppendLine(node.TextContent); } else { if (node.NodeName.Equals("br", StringComparison.InvariantCultureIgnoreCase)) { textContent.AppendLine("<BR>"); } // given that wiki html can contain embedded images and videos while not having child nodes we need include these. // case: img/iframe tag as "only" element to evaluate (e.g. first element in the contenthost) else if (node.NodeName.Equals("img", StringComparison.InvariantCultureIgnoreCase) || node.NodeName.Equals("iframe", StringComparison.InvariantCultureIgnoreCase)) { textContent.AppendLine((node as IHtmlElement).OuterHtml); } } } } } } // there was only one text part if (!string.IsNullOrEmpty(textContent.ToString())) { // insert text part to the web part collection order++; webparts.Add(CreateWikiTextPart(textContent.ToString(), rowCount, colCount, order)); } } } } // Bulk load the needed web part information if (webPartsToRetrieve.Count > 0) { // Load web part manager and use it to load each web part LimitedWebPartManager limitedWPManager = wikiPage.GetLimitedWebPartManager(PersonalizationScope.Shared); cc.Load(limitedWPManager); foreach (var webPartToRetrieve in webPartsToRetrieve) { // Check if the web part was loaded when we loaded the web parts collection via the web part manager if (!Guid.TryParse(webPartToRetrieve.Id, out Guid webPartToRetrieveGuid)) { // Skip since guid is not valid continue; } // Sometimes the returned wiki html contains web parts which are not anymore on the page...using the ExceptionHandlingScope // we can handle these errors server side while just doing a single roundtrip var scope = new ExceptionHandlingScope(cc); using (scope.StartScope()) { using (scope.StartTry()) { webPartToRetrieve.WebPartDefinition = limitedWPManager.WebParts.GetByControlId(webPartToRetrieve.ControlId); cc.Load(webPartToRetrieve.WebPartDefinition, wp => wp.Id, wp => wp.WebPart.ExportMode, wp => wp.WebPart.Title, wp => wp.WebPart.ZoneIndex, wp => wp.WebPart.IsClosed, wp => wp.WebPart.Hidden, wp => wp.WebPart.Properties); } using (scope.StartCatch()) { } } } cc.ExecuteQueryRetry(); // Load the web part XML for the web parts that do allow it bool isDirty = false; foreach (var webPartToRetrieve in webPartsToRetrieve) { // Important to only process the web parts that did not return an error in the previous server call if (webPartToRetrieve.WebPartDefinition != null && (webPartToRetrieve.WebPartDefinition.ServerObjectIsNull.HasValue && webPartToRetrieve.WebPartDefinition.ServerObjectIsNull.Value == false)) { // Retry to load the properties, sometimes they're not retrieved webPartToRetrieve.WebPartDefinition.EnsureProperty(wp => wp.Id); webPartToRetrieve.WebPartDefinition.WebPart.EnsureProperties(wp => wp.ExportMode, wp => wp.Title, wp => wp.ZoneIndex, wp => wp.IsClosed, wp => wp.Hidden, wp => wp.Properties); if (webPartToRetrieve.WebPartDefinition.WebPart.ExportMode == WebPartExportMode.All) { webPartToRetrieve.WebPartXml = limitedWPManager.ExportWebPart(webPartToRetrieve.WebPartDefinition.Id); isDirty = true; } } } if (isDirty) { cc.ExecuteQueryRetry(); } // Determine the web part type and store it in the web parts array foreach (var webPartToRetrieve in webPartsToRetrieve) { if (webPartToRetrieve.WebPartDefinition != null && (webPartToRetrieve.WebPartDefinition.ServerObjectIsNull.HasValue && webPartToRetrieve.WebPartDefinition.ServerObjectIsNull.Value == false)) { // Important to only process the web parts that did not return an error in the previous server call if (webPartToRetrieve.WebPartDefinition.WebPart.ExportMode != WebPartExportMode.All) { // Use different approach to determine type as we can't export the web part XML without indroducing a change webPartToRetrieve.WebPartType = GetTypeFromProperties(webPartToRetrieve.WebPartDefinition.WebPart.Properties); } else { webPartToRetrieve.WebPartType = GetType(webPartToRetrieve.WebPartXml.Value); } webparts.Add(new WebPartEntity() { Title = webPartToRetrieve.WebPartDefinition.WebPart.Title, Type = webPartToRetrieve.WebPartType, Id = webPartToRetrieve.WebPartDefinition.Id, ServerControlId = webPartToRetrieve.Id, Row = webPartToRetrieve.Row, Column = webPartToRetrieve.Column, Order = webPartToRetrieve.Order, ZoneId = "", ZoneIndex = (uint)webPartToRetrieve.WebPartDefinition.WebPart.ZoneIndex, IsClosed = webPartToRetrieve.WebPartDefinition.WebPart.IsClosed, Hidden = webPartToRetrieve.WebPartDefinition.WebPart.Hidden, Properties = Properties(webPartToRetrieve.WebPartDefinition.WebPart.Properties, webPartToRetrieve.WebPartType, webPartToRetrieve.WebPartXml == null ? "" : webPartToRetrieve.WebPartXml.Value), }); } } #region old approach /* * // Load web parts on wiki page * var limitedWPManager = wikiPage.GetLimitedWebPartManager(PersonalizationScope.Shared); * cc.Load(limitedWPManager); * var webParts = limitedWPManager.WebParts; * cc.Load(webParts, p => p.Include(wp => wp.Id, wp => wp.WebPart.ExportMode, wp => wp.WebPart.Title, wp => wp.WebPart.ZoneIndex, wp => wp.WebPart.IsClosed, wp => wp.WebPart.Hidden, wp => wp.WebPart.Properties)); * cc.ExecuteQueryRetry(); * * foreach (var webPartToRetrieve in webPartsToRetrieve) * { * try * { * // Check if the web part was loaded when we loaded the web parts collection via the web part manager * Guid webPartToRetrieveGuid; * if (!Guid.TryParse(webPartToRetrieve.Id, out webPartToRetrieveGuid)) * { * // Skip since guid is not valid * continue; * } * * var foundWebPart = webParts.Where(p => p.Id.Equals(webPartToRetrieveGuid)).FirstOrDefault(); * if (foundWebPart == null) * { * // If not found then try to retrieve the webpart via the GetByControlId method * foundWebPart = limitedWPManager.WebParts.GetByControlId(webPartToRetrieve.ControlId); * cc.Load(foundWebPart, wp => wp.Id, wp => wp.WebPart.ExportMode, wp => wp.WebPart.Title, wp => wp.WebPart.ZoneIndex, wp => wp.WebPart.IsClosed, wp => wp.WebPart.Hidden, wp => wp.WebPart.Properties); * cc.ExecuteQueryRetry(); * } * * if (foundWebPart != null) * { * // Retry to load the properties, sometimes they're not retrieved * foundWebPart.EnsureProperty(wp => wp.Id); * foundWebPart.WebPart.EnsureProperties(wp => wp.ExportMode, wp => wp.Title, wp => wp.ZoneIndex, wp => wp.IsClosed, wp => wp.Hidden, wp => wp.Properties); * * //var changed = false; * string webPartXml = ""; * string webPartType = ""; * var exportMode = foundWebPart.WebPart.ExportMode; * if (foundWebPart.WebPart.ExportMode != WebPartExportMode.All) * { * // Use different approach to determine type as we can't export the web part XML without indroducing a change * webPartType = GetTypeFromProperties(foundWebPart.WebPart.Properties); * } * else * { * * var result = limitedWPManager.ExportWebPart(foundWebPart.Id); * cc.ExecuteQueryRetry(); * webPartXml = result.Value; * webPartType = GetType(webPartXml); * } * * webparts.Add(new WebPartEntity() * { * Title = foundWebPart.WebPart.Title, * Type = webPartType, * Id = foundWebPart.Id, * ServerControlId = webPartToRetrieve.Id, * Row = webPartToRetrieve.Row, * Column = webPartToRetrieve.Column, * Order = webPartToRetrieve.Order, * ZoneId = "", * ZoneIndex = (uint)foundWebPart.WebPart.ZoneIndex, * IsClosed = foundWebPart.WebPart.IsClosed, * Hidden = foundWebPart.WebPart.Hidden, * Properties = Properties(foundWebPart.WebPart.Properties, webPartType, webPartXml), * }); * } * } * catch (ServerException) * { * //Eat exception because we've found a WebPart ID which is not available on the server-side * } * } */ #endregion } // Somehow the wiki was not standard formatted, so lets wrap its contents in a text block if (webparts.Count == 0 && !String.IsNullOrEmpty(htmlDoc.Source.Text)) { webparts.Add(CreateWikiTextPart(htmlDoc.Source.Text, 1, 1, 1)); } return(new Tuple <PageLayout, List <WebPartEntity> >(layout, webparts)); }
private Field FindField(FieldCollection fields, ContentTypeFieldLinkDefinition listFieldLinkModel) { var context = fields.Context; var scope = new ExceptionHandlingScope(context); Field field = null; if (listFieldLinkModel.FieldId.HasGuidValue()) { var id = listFieldLinkModel.FieldId.Value; using (scope.StartScope()) { using (scope.StartTry()) { fields.GetById(id); } using (scope.StartCatch()) { } } } else if (!string.IsNullOrEmpty(listFieldLinkModel.FieldInternalName)) { var fieldInternalName = listFieldLinkModel.FieldInternalName; using (scope.StartScope()) { using (scope.StartTry()) { fields.GetByInternalNameOrTitle(fieldInternalName); } using (scope.StartCatch()) { } } } context.ExecuteQueryWithTrace(); if (!scope.HasException) { if (listFieldLinkModel.FieldId.HasGuidValue()) { field = fields.GetById(listFieldLinkModel.FieldId.Value); } else if (!string.IsNullOrEmpty(listFieldLinkModel.FieldInternalName)) { field = fields.GetByInternalNameOrTitle(listFieldLinkModel.FieldInternalName); } context.Load(field); context.Load(field, f => f.SchemaXml); context.ExecuteQueryWithTrace(); } return field; }
public static SharePointList CreateCustomersList() { ClientContext ctx = GetClientContext(); ctx.Load(ctx.Web); ctx.ExecuteQuery(); string listTitle = "Customers"; // delete list if it exists ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx); using (scope.StartScope()) { using (scope.StartTry()) { ctx.Web.Lists.GetByTitle(listTitle).DeleteObject(); } using (scope.StartCatch()) { } } // create and initialize ListCreationInformation object ListCreationInformation listInformation = new ListCreationInformation(); listInformation.Title = listTitle; listInformation.Url = "Lists/Customers"; listInformation.QuickLaunchOption = QuickLaunchOptions.On; listInformation.TemplateType = (int)ListTemplateType.Contacts; // Add ListCreationInformation to lists collection and return list object List list = ctx.Web.Lists.Add(listInformation); // modify additional list properties and update list.OnQuickLaunch = true; list.EnableAttachments = false; list.Update(); // send command to server to create list ctx.Load(list, l => l.Id, l => l.Title, l => l.DefaultViewUrl); ctx.ExecuteQuery(); // add an item to the list ListItemCreationInformation lici1 = new ListItemCreationInformation(); var item1 = list.AddItem(lici1); item1["Title"] = "Lennon"; item1["FirstName"] = "John"; item1.Update(); // add a second item ListItemCreationInformation lici2 = new ListItemCreationInformation(); var item2 = list.AddItem(lici2); item2["Title"] = "McCartney"; item2["FirstName"] = "Paul"; item2.Update(); // send add commands to server ctx.ExecuteQuery(); string urlAuthority = "https://" + (new Uri(siteUrl)).Authority; SharePointList newList = new SharePointList { Id = list.Id.ToString(), Title = list.Title, DefaultViewUrl = urlAuthority + list.DefaultViewUrl }; ctx.Dispose(); return(newList); }
public static TermSet LookupTermSet(ClientRuntimeContext context, TermStore termStore, Site site, string termGroupName, Guid? termGroupId, bool? isSiteCollectionGroup, string termSetName, Guid? termSetId, int termSetLCID) { var storeContext = context; TermGroup currenGroup = null; if (!string.IsNullOrEmpty(termGroupName)) { currenGroup = termStore.Groups.GetByName(termGroupName); storeContext.Load(currenGroup); storeContext.ExecuteQueryWithTrace(); } else if (termGroupId != null && termGroupId.HasGuidValue()) { currenGroup = termStore.Groups.GetById(termGroupId.Value); storeContext.Load(currenGroup); storeContext.ExecuteQueryWithTrace(); } else if (isSiteCollectionGroup == true) { currenGroup = termStore.GetSiteCollectionGroup(site, false); storeContext.Load(currenGroup); storeContext.ExecuteQueryWithTrace(); } if (!string.IsNullOrEmpty(termSetName)) { if (currenGroup != null && (currenGroup.ServerObjectIsNull == false)) { TermSet termSet = null; var scope = new ExceptionHandlingScope(storeContext); using (scope.StartScope()) { using (scope.StartTry()) { termSet = currenGroup.TermSets.GetByName(termSetName); storeContext.Load(termSet); } using (scope.StartCatch()) { } } storeContext.ExecuteQueryWithTrace(); if (termSet != null && termSet.ServerObjectIsNull == false) { storeContext.Load(termSet, g => g.Id); storeContext.ExecuteQueryWithTrace(); return termSet; } } else { var termSets = termStore.GetTermSetsByName(termSetName, termSetLCID); storeContext.Load(termSets); storeContext.ExecuteQueryWithTrace(); return termSets.FirstOrDefault(); } } if (termSetId.HasGuidValue()) { if (currenGroup != null && (currenGroup.ServerObjectIsNull == false)) { TermSet termSet = null; var scope = new ExceptionHandlingScope(storeContext); using (scope.StartScope()) { using (scope.StartTry()) { termSet = currenGroup.TermSets.GetById(termSetId.Value); storeContext.Load(termSet); } using (scope.StartCatch()) { } } storeContext.ExecuteQueryWithTrace(); if (termSet != null && termSet.ServerObjectIsNull == false) { storeContext.Load(termSet, g => g.Id); storeContext.ExecuteQueryWithTrace(); return termSet; } } else { TermSet termSet = null; var scope = new ExceptionHandlingScope(storeContext); using (scope.StartScope()) { using (scope.StartTry()) { termSet = termStore.GetTermSet(termSetId.Value); storeContext.Load(termSet); } using (scope.StartCatch()) { } } storeContext.ExecuteQueryWithTrace(); if (termSet != null && termSet.ServerObjectIsNull == false) { storeContext.Load(termSet, g => g.Id); storeContext.ExecuteQueryWithTrace(); return termSet; } } } return null; }
public void UpdateListItemByCaml(string listName, string query, IDictionary <string, string> fieldsValues) { var oList = _ctx.Web.Lists.GetByTitle(listName); _ctx.Load(oList); _ctx.Load(oList.Fields, fields => fields.Include(f => f.CanBeDeleted) .Where(f => f.FieldTypeKind != FieldType.Attachments && f.CanBeDeleted)); _ctx.ExecuteQuery(); var scopes = new Dictionary <int, ExceptionHandlingScope>(); var infoErro = string.Empty; if (oList != null && oList.ItemCount > 0) { var caml = new CamlQuery(); if (!string.IsNullOrEmpty(query)) { caml.ViewXml = query; } var spListItem = oList.GetItems(caml); _ctx.Load(spListItem); _ctx.ExecuteQuery(); var count = 0; foreach (var item in spListItem) { var scope = new ExceptionHandlingScope(_ctx); scopes.Add(Convert.ToInt32(item["ID"].ToString()), scope); using (scope.StartScope()) { using (scope.StartTry()) { ++count; foreach (var f in fieldsValues.Keys) { if (item[f] != null) { if (!string.IsNullOrEmpty(item[f].ToString())) { item[f] = fieldsValues[f]; } } } item.Update(); } using (scope.StartCatch()) { } } if (count % 25 == 0) { _ctx.ExecuteQuery(); } } _ctx.ExecuteQuery(); } //try //{ // var oList = _ctx.Web.Lists.GetByTitle(listName); // _ctx.Load(oList); // _ctx.Load(oList.Fields, fields => fields.Include(f => f.CanBeDeleted) // .Where(f => f.FieldTypeKind != FieldType.Attachments && f.CanBeDeleted)); // _ctx.ExecuteQuery(); // if (oList != null && oList.ItemCount > 0) // { // var caml = new CamlQuery(); // if (!string.IsNullOrEmpty(query)) // { // caml.ViewXml = query; // } // var spCListItem = oList.GetItems(caml); // _ctx.Load(spCListItem); // _ctx.ExecuteQuery(); // var count = 0; // foreach (var item in spCListItem) // { // ++count; // foreach (var f in fieldsValues.Keys) // { // if (item[f] != null) // { // if (!string.IsNullOrEmpty(item[f].ToString())) // { // item[f] = fieldsValues[f]; // } // } // } // item.Update(); // if (count % 20 == 0) // _ctx.ExecuteQuery(); // } // _ctx.ExecuteQuery(); // } //} //catch (Exception ex) //{ // throw ex; //} }
private string TryCreateList(String listTitle, SPRemoteEventProperties properties) { string errorMessage = String.Empty; using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, useAppWeb: false)) { if (clientContext != null) { // Get references to the objects needed later. ListCollection allLists = clientContext.Web.Lists; IEnumerable<List> matchingLists = clientContext.LoadQuery(allLists.Where(list => list.Title == listTitle)); clientContext.ExecuteQuery(); var foundList = matchingLists.FirstOrDefault(); List createdList = null; // Delegate the rollback logic to the SharePoint server. ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext); using (scope.StartScope()) { using (scope.StartTry()) { // SharePoint might be retrying the event after a time-out, so // check to see if there's already a list with that name. // If there isn't, create it. ConditionalScope condScope = new ConditionalScope(clientContext, () => foundList.ServerObjectIsNull.Value == true, true); using (condScope.StartScope()) { ListCreationInformation listInfo = new ListCreationInformation(); listInfo.Title = listTitle; listInfo.TemplateType = (int)ListTemplateType.GenericList; listInfo.Url = listTitle; createdList = clientContext.Web.Lists.Add(listInfo); } // To test that your StartCatch block runs, uncomment the following two lines // and put them somewhere in the StartTry block. //List fakeList = clientContext.Web.Lists.GetByTitle("NoSuchList"); //clientContext.Load(fakeList); } using (scope.StartCatch()) { // Check to see if the try code got far enough to create the list before it errored. // If it did, roll this change back by deleting the list. ConditionalScope condScope = new ConditionalScope(clientContext, () => createdList.ServerObjectIsNull.Value != true, true); using (condScope.StartScope()) { createdList.DeleteObject(); } } using (scope.StartFinally()) { } } clientContext.ExecuteQuery(); if (scope.HasException) { errorMessage = String.Format("{0}: {1}; {2}; {3}; {4}; {5}", scope.ServerErrorTypeName, scope.ErrorMessage, scope.ServerErrorDetails, scope.ServerErrorValue, scope.ServerStackTrace, scope.ServerErrorCode); } } } return errorMessage; }
public static Term AddTermToTermset(Guid termSetId, string term, Guid termId, ClientContext clientContext) { Term t = null; var scope = new ExceptionHandlingScope(clientContext); using (scope.StartScope()) { using (scope.StartTry()) { TaxonomySession tSession = TaxonomySession.GetTaxonomySession(clientContext); TermStore ts = tSession.GetDefaultSiteCollectionTermStore(); TermSet tset = ts.GetTermSet(termSetId); t = tset.CreateTerm(term, 1033, termId); clientContext.Load(tSession); clientContext.Load(ts); clientContext.Load(tset); clientContext.Load(t); } using (scope.StartCatch()) { if (scope.HasException) { return null; } } } clientContext.ExecuteQuery(); return t; }