/// <summary> /// Add Calendar Web Part to client site /// </summary> /// <param name="clientContext">SharePoint Client Context</param> /// <param name="matter">Matter object containing Matter data</param> internal static void AddCalendarList(ClientContext clientContext, Matter matter) { string calendarName = string.Concat(matter.MatterName, ConfigurationManager.AppSettings["CalendarNameSuffix"]); try { Web web = clientContext.Web; clientContext.Load(web, item => item.ListTemplates); clientContext.ExecuteQuery(); ListTemplate listTemplate = null; foreach (var calendar in web.ListTemplates) { if (calendar.Name == Constants.CalendarName) { listTemplate = calendar; } } ListCreationInformation listCreationInformation = new ListCreationInformation(); listCreationInformation.TemplateType = listTemplate.ListTemplateTypeKind; listCreationInformation.Title = calendarName; // Added URL property for URL consolidation changes listCreationInformation.Url = Constants.TitleListPath + matter.MatterGuid + ConfigurationManager.AppSettings["CalendarNameSuffix"]; web.Lists.Add(listCreationInformation); web.Update(); clientContext.ExecuteQuery(); MatterProvisionHelperUtility.BreakPermission(clientContext, matter.MatterName, matter.CopyPermissionsFromParent, calendarName); } catch (Exception exception) { //// Generic Exception MatterProvisionHelper.DeleteMatter(clientContext, matter); DisplayAndLogError(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace); } }
public static List CreateSharePointRepositoryList(Web web, string title, string description, string url) { List _requestList = web.GetListByTitle(title); if(_requestList == null) //List Doesnt Existing { var _listCreation = new ListCreationInformation() { Title = title, TemplateType = (int)ListTemplateType.GenericList, Description = description, Url = url }; _requestList = web.Lists.Add(_listCreation); web.Context.Load(_requestList); web.Context.ExecuteQuery(); } var _fields = CreateListFields(web); var _contentID = CreateContentType(web, SiteRequestList.CONTENTTYPE_NAME, SiteRequestList.CONTENTTYPE_DESCRIPTION, SiteRequestList.DEFAULT_CTYPE_GROUP, SiteRequestList.CONTENTTYPE_ID); //add fields to CT BindFieldsToContentType(web, SiteRequestList.CONTENTTYPE_ID, _fields); AddContentTypeToList(web, SiteRequestList.CONTENTTYPE_ID, SiteRequestList.TITLE, _fields); return _requestList; }
public static List CreateList(string title, string description, string url, ListTemplateType templateType, Web web, QuickLaunchOptions quicklaunchOptions) { ClientContext clientContext = web.Context as ClientContext; ListCreationInformation createInfo = new ListCreationInformation(); createInfo.Title = title; createInfo.TemplateType = (int)templateType; createInfo.QuickLaunchOption = quicklaunchOptions; if (!string.IsNullOrEmpty(description)) { createInfo.Description = description; } if (!string.IsNullOrEmpty(url)) { createInfo.Url = url; } // clientContext.Load(web.Lists); List newList = web.Lists.Add(createInfo); clientContext.ExecuteQuery(); clientContext.Load(newList); clientContext.ExecuteQuery(); return newList; }
private static void CreateListInternal(this Web web, ListTemplateType listType, string listName, bool enableVersioning, bool updateAndExecuteQuery = true, string urlPath = "") { ListCollection listCol = web.Lists; ListCreationInformation lci = new ListCreationInformation(); lci.Title = listName; lci.TemplateType = (int)listType; if (!string.IsNullOrEmpty(urlPath)) lci.Url = urlPath; List newList = listCol.Add(lci); if (enableVersioning) { newList.EnableVersioning = true; newList.EnableMinorVersions = true; } if (updateAndExecuteQuery) { newList.Update(); web.Context.Load(listCol); web.Context.ExecuteQuery(); } }
public void Initialize() { Console.WriteLine("TaxonomyExtensionsTests.Initialise"); // Create some taxonomy groups and terms using (var clientContext = TestCommon.CreateClientContext()) { _termGroupName = "Test_Group_" + DateTime.Now.ToFileTime(); _termSetName = "Test_Termset_" + DateTime.Now.ToFileTime(); _termName = "Test_Term_" + DateTime.Now.ToFileTime(); // Termgroup var taxSession = TaxonomySession.GetTaxonomySession(clientContext); var termStore = taxSession.GetDefaultSiteCollectionTermStore(); var termGroup = termStore.CreateGroup(_termGroupName, _termGroupId); clientContext.Load(termGroup); clientContext.ExecuteQuery(); // Termset var termSet = termGroup.CreateTermSet(_termSetName, _termSetId, 1033); clientContext.Load(termSet); clientContext.ExecuteQuery(); // Term termSet.CreateTerm(_termName, 1033, _termId); clientContext.ExecuteQuery(); // List ListCreationInformation listCI = new ListCreationInformation(); listCI.TemplateType = (int)ListTemplateType.GenericList; listCI.Title = "Test_List_" + DateTime.Now.ToFileTime(); var list = clientContext.Web.Lists.Add(listCI); clientContext.Load(list); clientContext.ExecuteQuery(); _listId = list.Id; } }
/// <summary> /// Adds a list to a site /// </summary> /// <param name="properties">Site to operate on</param> /// <param name="listType">Type of the list</param> /// <param name="featureID">Feature guid that brings this list type</param> /// <param name="listName">Name of the list</param> /// <param name="enableVersioning">Enable versioning on the list</param> public static List AddList(ClientContext ctx, Web web, ListTemplateType listType, string listName) { ListCollection listCollection = web.Lists; ctx.Load(listCollection, lists => lists.Include(list => list.Title).Where(list => list.Title == listName)); ctx.ExecuteQuery(); if (listCollection.Count == 0) { ListCollection listCol = web.Lists; ListCreationInformation lci = new ListCreationInformation(); lci.Title = listName; lci.TemplateType = (int)listType; List newList = listCol.Add(lci); newList.Description = "Demo list for remote event receiver lab"; newList.Fields.AddFieldAsXml("<Field DisplayName='Description' Type='Text' />",true,AddFieldOptions.DefaultValue); newList.Fields.AddFieldAsXml("<Field DisplayName='AssignedTo' Type='Text' />",true,AddFieldOptions.DefaultValue); newList.Update(); return newList; //ctx.Load(listCol); //ctx.ExecuteQuery(); } else { return listCollection[0]; } }
public void CreateDefaultList(ClientContext context, Web web) { // Create a list var listInfo = new ListCreationInformation { Title = "Default List", TemplateType = (int)ListTemplateType.GenericList }; var list = web.Lists.Add(listInfo); list.Description = "A default list that is provisioned."; list.EnableVersioning = true; list.Update(); context.ExecuteQuery(); // Add a field var field = list.Fields.AddFieldAsXml("<Field DisplayName='My Number1' Type='Number' />", true, AddFieldOptions.DefaultValue); var numberField = context.CastTo<FieldNumber>(field); numberField.MaximumValue = 1000; numberField.MinimumValue = 10; numberField.Update(); // Add a second field var field2 = list.Fields.AddFieldAsXml("<Field DisplayName='My Number2' Type='Number' />", true, AddFieldOptions.DefaultValue); context.ExecuteQuery(); }
/// <summary> /// Adds a list to a site /// </summary> /// <param name="properties">Site to operate on</param> /// <param name="listType">Type of the list</param> /// <param name="featureID">Feature guid that brings this list type</param> /// <param name="listName">Name of the list</param> /// <param name="enableVersioning">Enable versioning on the list</param> public bool AddList(ClientContext ctx, Web web, int listType, Guid featureID, string listName, bool enableVersioning) { bool created = false; ListCollection listCollection = web.Lists; ctx.Load(listCollection, lists => lists.Include(list => list.Title).Where(list => list.Title == listName)); ctx.ExecuteQuery(); if (listCollection.Count == 0) { ListCreationInformation lci = new ListCreationInformation(); lci.Title = listName; lci.TemplateFeatureId = featureID; lci.TemplateType = listType; List newList = web.Lists.Add(lci); if (enableVersioning) { newList.EnableVersioning = true; newList.EnableMinorVersions = true; } newList.Update(); ctx.ExecuteQuery(); created = true; } return created; }
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"; } }
/// <summary> /// Adds a list to a site /// </summary> /// <param name="web">Site to be processed - can be root web or sub site</param> /// <param name="listType">Type of the list</param> /// <param name="listName">Name of the list</param> /// <param name="enableVersioning">Enable versioning on the list</param> /// <param name="updateAndExecuteQuery">Perform list update and executequery, defaults to true</param> public static void AddList(Web web, ListTemplateType listType, string listName) { ListCollection listCol = web.Lists; ListCreationInformation lci = new ListCreationInformation(); lci.Title = listName; lci.TemplateType = (int)listType; List newList = listCol.Add(lci); }
private void CreateSiteClassificationList(ClientContext ctx) { var _newList = new ListCreationInformation() { Title = SiteClassificationList.SiteClassificationListTitle, Description = SiteClassificationList.SiteClassificationDesc, TemplateType = (int)ListTemplateType.GenericList, Url = SiteClassificationList.SiteClassificationUrl, QuickLaunchOption = QuickLaunchOptions.Off }; if(!ctx.Web.ContentTypeExistsById(SiteClassificationContentType.SITEINFORMATION_CT_ID)) { //ct ContentType _contentType = ctx.Web.CreateContentType(SiteClassificationContentType.SITEINFORMATION_CT_NAME, SiteClassificationContentType.SITEINFORMATION_CT_DESC, SiteClassificationContentType.SITEINFORMATION_CT_ID, SiteClassificationContentType.SITEINFORMATION_CT_GROUP); FieldLink _titleFieldLink = _contentType.FieldLinks.GetById(new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")); _titleFieldLink.Required = false; _contentType.Update(false); //Key Field ctx.Web.CreateField(SiteClassificationFields.FLD_KEY_ID, SiteClassificationFields.FLD_KEY_INTERNAL_NAME, FieldType.Text, SiteClassificationFields.FLD_KEY_DISPLAY_NAME, SiteClassificationFields.FIELDS_GROUPNAME); //value field ctx.Web.CreateField(SiteClassificationFields.FLD_VALUE_ID, SiteClassificationFields.FLD_VALUE_INTERNAL_NAME, FieldType.Text, SiteClassificationFields.FLD_VALUE_DISPLAY_NAME, SiteClassificationFields.FIELDS_GROUPNAME); //Add Key Field to content type ctx.Web.AddFieldToContentTypeById(SiteClassificationContentType.SITEINFORMATION_CT_ID, SiteClassificationFields.FLD_KEY_ID.ToString(), true); //Add Value Field to content type ctx.Web.AddFieldToContentTypeById(SiteClassificationContentType.SITEINFORMATION_CT_ID, SiteClassificationFields.FLD_VALUE_ID.ToString(), true); } var _list = ctx.Web.Lists.Add(_newList); _list.Hidden = true; _list.ContentTypesEnabled = true; _list.Update(); ctx.Web.AddContentTypeToListById(SiteClassificationList.SiteClassificationListTitle, SiteClassificationContentType.SITEINFORMATION_CT_ID, true); this.CreateCustomPropertiesInList(_list); ctx.ExecuteQuery(); this.RemoveFromQuickLaunch(ctx, SiteClassificationList.SiteClassificationListTitle); }
/// <summary> /// Function to create document library for Matter and OneNote /// </summary> /// <param name="clientContext">Client Context</param> /// <param name="listInfo">List information</param> /// <returns>Success flag</returns> public static bool Create(ClientContext clientContext, ListInformation listInfo) { bool result = true; if (null != clientContext && null != listInfo && !string.IsNullOrWhiteSpace(listInfo.name)) { Web web = clientContext.Web; ListTemplateCollection listTemplates = web.ListTemplates; ListCreationInformation creationInfo = new ListCreationInformation(); creationInfo.Title = listInfo.name; creationInfo.Description = listInfo.description; // To determine changes in URL we specified below condition as this function is common if (!string.IsNullOrWhiteSpace(listInfo.Path)) { creationInfo.Url = listInfo.Path; } if (!string.IsNullOrWhiteSpace(listInfo.templateType)) { string templateType = listInfo.templateType; clientContext.Load(listTemplates, item => item.Include(currentTemplate => currentTemplate.Name, currentTemplate => currentTemplate.ListTemplateTypeKind).Where(selectedTemplate => selectedTemplate.Name == templateType)); clientContext.ExecuteQuery(); if (null != listTemplates && 0 < listTemplates.Count) { creationInfo.TemplateType = listTemplates.FirstOrDefault().ListTemplateTypeKind; } else { result = false; } } else { creationInfo.TemplateType = (int)ListTemplateType.DocumentLibrary; } if (result) { List list = web.Lists.Add(creationInfo); list.ContentTypesEnabled = listInfo.isContentTypeEnable; if (null != listInfo.folderNames && listInfo.folderNames.Count > 0) { list = Lists.AddFolders(clientContext, list, listInfo.folderNames); } if (null != listInfo.versioning) { list.EnableVersioning = listInfo.versioning.EnableVersioning; list.EnableMinorVersions = listInfo.versioning.EnableMinorVersions; list.ForceCheckout = listInfo.versioning.ForceCheckout; } list.Update(); clientContext.Load(list, l => l.DefaultViewUrl); clientContext.ExecuteQuery(); result = true; } } return result; }
private static void CreateList(ClientContext clientContext, string listName) { Web currentWeb = clientContext.Web; ListCreationInformation creationInfo = new ListCreationInformation(); creationInfo.Title = listName; creationInfo.TemplateType = (int)ListTemplateType.GenericList; List list = currentWeb.Lists.Add(creationInfo); list.Description = "My custom list"; list.Update(); clientContext.ExecuteQuery(); }
public void CreateDocLibrary(ClientContext ctx, string libraryName, string description) { // Create new list to the host web ListCreationInformation list = new ListCreationInformation(); list.Title = libraryName; list.TemplateType = (int)ListTemplateType.DocumentLibrary; list.Description = description; list.Url = libraryName; ctx.Web.Lists.Add(list); ctx.ExecuteQuery(); }
public List CreateDocumentLibrary(string DocLibName, string DocDesc) { Web web = Ctx.Web; ListCreationInformation creationInfo = new ListCreationInformation(); creationInfo.Title = DocLibName; creationInfo.TemplateType = (int)ListTemplateType.DocumentLibrary; List list = web.Lists.Add(creationInfo); list.Description = DocDesc; list.Update(); Ctx.ExecuteQuery(); return list; }
internal static void CreateOrderList(ClientContext ctx) { ListCreationInformation lci = new ListCreationInformation(); lci.Title = "Order"; lci.TemplateType = 100; if (!ctx.Web.ListExists("Order")) { var OrderList = ctx.Web.Lists.Add(lci); OrderList.AddContentTypeToList(ctx.Web.GetContentTypeById(Constants.GUID.OrderCT.OrderCTGUID), true); OrderList.Update(); ctx.ExecuteQuery(); } }
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; }
public static List CreateList(ClientContext ctx, int templateType, string title, string url, QuickLaunchOptions quickLaunchOptions) { ListCreationInformation listCreationInfo = new ListCreationInformation { TemplateType = templateType, Title = title, Url = url, QuickLaunchOption = quickLaunchOptions }; List spList = ctx.Web.Lists.Add(listCreationInfo); ctx.Load(spList); ctx.ExecuteQuery(); return spList; }
public void CreateDocLibrary(ClientContext ctx, string libraryName, string requestor) { // Create new list to the host web ListCreationInformation newList = new ListCreationInformation(); newList.Title = libraryName; newList.TemplateType = (int)ListTemplateType.GenericList; newList.Description = requestor; newList.Url = libraryName; List list = ctx.Web.Lists.Add(newList); ListItemCreationInformation newItem = new ListItemCreationInformation(); ListItem item = list.AddItem(newItem); item["Title"] = requestor; item.Update(); ctx.ExecuteQuery(); }
static void CreateProductImagesLibrary() { Console.WriteLine(); Console.WriteLine("Creating Product Images library..."); ListCreationInformation listInformationProductImages = new ListCreationInformation(); listInformationProductImages.Title = "Product Images"; listInformationProductImages.Url = "ProductImages"; listInformationProductImages.QuickLaunchOption = QuickLaunchOptions.On; listInformationProductImages.TemplateType = (int)ListTemplateType.PictureLibrary; listProductImages = site.Lists.Add(listInformationProductImages); listProductImages.OnQuickLaunch = true; listProductImages.Update(); clientContext.Load(listProductImages); clientContext.Load(listProductImages.RootFolder); clientContext.ExecuteQuery(); listProductImagesUrl = listProductImages.RootFolder.ServerRelativeUrl; }
public static void CreateCustomerList(ClientContext ctx) { ListCreationInformation lci = new ListCreationInformation(); lci.Title = "Customer"; lci.TemplateType = 100; //var CustomerList = ctx.Web.Lists.GetByTitle("Customer"); //ctx.Load(CustomerList); //ctx.ExecuteQuery(); if (!ctx.Web.ListExists("Customer")) { var CustomerList = ctx.Web.Lists.Add(lci); CustomerList.AddContentTypeToList(ctx.Web.GetContentTypeById(Constants.GUID.CustomerCT.CustomerCTGUID), true); CustomerList.Update(); ctx.ExecuteQuery(); } if (ctx.Web.ListExists("Customer")) { ConnectCustomerLookUpField(ctx); } }
public ActionResult Add(string name = null) { var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); ViewBag.SPHostUrl = spContext.SPHostUrl; if (!string.IsNullOrEmpty(name)) { using (var clientContext = spContext.CreateUserClientContextForSPHost()) { ListCreationInformation creationInfo = new ListCreationInformation(); creationInfo.Title = name; creationInfo.TemplateType = (int)ListTemplateType.Announcements; List list = clientContext.Web.Lists.Add(creationInfo); list.Description = "Description"; list.Update(); clientContext.ExecuteQuery(); return RedirectToAction("Index", "Lists", new { SPHostUrl = spContext.SPHostUrl }); } } return RedirectToAction("Index", "Lists", new { SPHostUrl = spContext.SPHostUrl }); }
/// <summary> /// Creates a list with Description and AssignedTo fields /// </summary> /// <param name="context"></param> /// <returns></returns> internal List CreateJobsList(ClientContext context) { ListCreationInformation creationInfo = new ListCreationInformation(); creationInfo.Title = LIST_TITLE; creationInfo.TemplateType = (int)ListTemplateType.GenericList; List list = context.Web.Lists.Add(creationInfo); list.Description = "List of jobs and assignments"; list.Fields.AddFieldAsXml("<Field DisplayName='Description' Type='Text' />", true, AddFieldOptions.DefaultValue); list.Fields.AddFieldAsXml("<Field DisplayName='AssignedTo' Type='Text' />", true, AddFieldOptions.DefaultValue); list.Update(); //Do not execute the call. We simply create the list in the context, //it's up to the caller to call ExecuteQuery. return list; }
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 static bool AddList(this Web web, int listType, Guid featureID, string listName, bool enableVersioning, bool updateAndExecuteQuery = true, string urlPath = "") { bool created = false; ListCollection listCollection = web.Lists; web.Context.Load(listCollection, lists => lists.Include(list => list.Title).Where(list => list.Title == listName)); web.Context.ExecuteQuery(); if (listCollection.Count == 0) { ListCollection listCol = web.Lists; ListCreationInformation lci = new ListCreationInformation(); lci.Title = listName; lci.TemplateFeatureId = featureID; lci.TemplateType = listType; if (!string.IsNullOrEmpty(urlPath)) lci.Url = urlPath; List newList = listCol.Add(lci); if (enableVersioning) { newList.EnableVersioning = true; newList.EnableMinorVersions = true; } if (updateAndExecuteQuery) { newList.Update(); web.Context.Load(listCol); web.Context.ExecuteQuery(); } created = true; } return created; }
public void CreateDocLib2(string OutputFolder, string DocLib, string Desc, ClientContext cl) { try { if (!ListExistsNew(cl, DocLib)) { using (ClientContext clientCTX = cl) { ListCreationInformation lci = new ListCreationInformation(); lci.Description = Desc; lci.Title = DocLib; lci.TemplateType = 101; List newLib = clientCTX.Web.Lists.Add(lci); clientCTX.Load(newLib); clientCTX.ExecuteQuery(); } } } catch (Exception ex) { new GenerateTxt().GenerateTxtLogError(OutputFolder, ex.Message, "CreateDocLib2 - " + DocLib); } }
/// <summary> /// Creates a list with Description and AssignedTo fields /// </summary> /// <param name="context"></param> /// <returns></returns> internal List CreateJobsList(ClientContext context) { ListCreationInformation creationInfo = new ListCreationInformation(); creationInfo.Title = LIST_TITLE; creationInfo.TemplateType = (int)ListTemplateType.GenericList; List list = context.Web.Lists.Add(creationInfo); list.Description = "List of jobs and assignments"; list.Fields.AddFieldAsXml("<Field DisplayName='Description' Type='Text' />", true, AddFieldOptions.DefaultValue); list.Fields.AddFieldAsXml("<Field DisplayName='AssignedTo' Type='Text' />", true, AddFieldOptions.DefaultValue); list.Update(); //Do not execute the call. We simply create the list in the context, //it's up to the caller to call ExecuteQuery. return(list); }
private void button11_Click(object sender, EventArgs e) { using (var context = new ClientContext("https://thethread-qa.carpetright.co.uk/Facilities/")) { try { var web = context.Web; List list = null; var lci = new ListCreationInformation(); lci.Title = "Project Documents"; lci.QuickLaunchOption = QuickLaunchOptions.On; lci.TemplateType = (int)ListTemplateType.DocumentLibrary; list = web.Lists.Add(lci); FieldType fieldType = FieldType.Number; OfficeDevPnP.Core.Entities.FieldCreationInformation newFieldInfo = new OfficeDevPnP.Core.Entities.FieldCreationInformation(fieldType); newFieldInfo.DisplayName = "Year"; newFieldInfo.AddToDefaultView = true; newFieldInfo.InternalName = "Year"; newFieldInfo.Id = Guid.NewGuid(); list.CreateField(newFieldInfo, false); context.ExecuteQuery(); var status = "Field Created"; ResultsListBox.Items.Add(list.Title + status); } catch (Exception ex) { ResultsListBox.Items.Add(ex.Message); } } }
/// <summary> /// Generic handler for list instances /// </summary> /// <param name="clientContext">Context to apply the changes in</param> /// <param name="siteTemplate">XML configuration for the template</param> private void DeployLists(ClientContext clientContext, Web web, XElement siteTemplate) { XElement liststoCreate = siteTemplate.Element("Lists"); if (liststoCreate != null) { foreach (XElement listToCreate in liststoCreate.Elements()) { ListCreationInformation listInformation = new ListCreationInformation(); listInformation.Description = listToCreate.Attribute("Description").Value; if (!string.IsNullOrEmpty(listToCreate.Attribute("DocumentTemplate").Value)) { listInformation.DocumentTemplateType = Convert.ToInt32(listToCreate.Attribute("DocumentTemplate").Value); } if (!string.IsNullOrEmpty(listToCreate.Attribute("OnQuickLaunch").Value)) { if (Convert.ToBoolean(listToCreate.Attribute("OnQuickLaunch").Value)) { listInformation.QuickLaunchOption = QuickLaunchOptions.On; } else { listInformation.QuickLaunchOption = QuickLaunchOptions.Off; } } if (!string.IsNullOrEmpty(listToCreate.Attribute("TemplateType").Value)) { listInformation.TemplateType = Convert.ToInt32(listToCreate.Attribute("TemplateType").Value); } listInformation.Title = listToCreate.Attribute("Title").Value; listInformation.Url = listToCreate.Attribute("Url").Value; web.Lists.Add(listInformation); clientContext.ExecuteQuery(); } } }
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)) { Web rootWeb = adminContext.Web; adminContext.Load(rootWeb); ListCollection listCollection = rootWeb.Lists; adminContext.Load(listCollection, lists => lists.Include(list => list.Title).Where(list => list.Title == "OfficeAMSConfig")); adminContext.ExecuteQuery(); if (listCollection.Count == 0) { ListCreationInformation listCreationInfo = new ListCreationInformation(); listCreationInfo.Title = "OfficeAMSConfig"; listCreationInfo.TemplateType = (int)ListTemplateType.GenericList; List oList = rootWeb.Lists.Add(listCreationInfo); Field oField = oList.Fields.AddFieldAsXml("<Field DisplayName='Value' Type='Text' />", true, AddFieldOptions.DefaultValue); adminContext.ExecuteQuery(); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem item = oList.AddItem(itemCreateInfo); item["Title"] = "SubSiteAppUrl"; item["Value"] = "https://localhost:44323"; item.Update(); adminContext.ExecuteQuery(); } } }
public override void Provision() { if (_list != null && Model != null && Model.Context != null && Model.Context.Context != null) { var context = Model.Context.Context; Web web = context.Web; List list = _list.Url != null ? context.Web.GetList($"{ Model.Context.SiteUrl.TrimEnd('/')}/{_list.Url.TrimStart('/')}") : (_list.Title != null ? context.Web.Lists.GetByTitle(_list.Title) : null); context.Load(list); try { context.ExecuteQuery(); OnProvisioned?.Invoke(this, list); return; } catch (Exception) { list = null; } var newList = new ListCreationInformation() { Title = _list.Title, Url = _list.Url, TemplateType = (int)_list.Type }; list = web.Lists.Add(newList); OnProvisioning?.Invoke(this, list); list.Update(); context.Load(list); context.ExecuteQuery(); OnProvisioned?.Invoke(this, list); } }
static void CreateProductPlansLibrary() { Console.WriteLine("Creating Product Plans document library..."); ListCreationInformation infoProductPlans = new ListCreationInformation(); infoProductPlans.Title = "Product Plans"; infoProductPlans.Url = "ProductPlans"; infoProductPlans.QuickLaunchOption = QuickLaunchOptions.On; infoProductPlans.TemplateType = (int)ListTemplateType.DocumentLibrary; libraryProductPlans = site.Lists.Add(infoProductPlans); libraryProductPlans.OnQuickLaunch = true; libraryProductPlans.EnableVersioning = true; libraryProductPlans.Update(); clientContext.Load(libraryProductPlans); clientContext.Load(libraryProductPlans.ContentTypes); clientContext.ExecuteQuery(); libraryProductPlans.ContentTypesEnabled = true; ContentType listTypeDocumentSet = libraryProductPlans.ContentTypes.AddExistingContentType(ctypeProductPlanDocucmentSet); ContentType existing = libraryProductPlans.ContentTypes[0]; ; existing.DeleteObject(); libraryProductPlans.Update(); clientContext.Load(listTypeDocumentSet); clientContext.ExecuteQuery(); Console.WriteLine(); clientContext.Load(ctypeProductPlanDocucmentSet, ctype => ctype.Id); clientContext.ExecuteQuery(); CreateDocumentSetInstance("Mitt Ronmey Action Figure"); CreateDocumentSetInstance("Newt Ginrage Action Figure"); CreateDocumentSetInstance("George Bush Action Figure"); CreateDocumentSetInstance("Billy Clinton Action Figure"); CreateDocumentSetInstance("Barack Obama Action Figure"); }
public void CreateList(string listName) { try { ListCreationInformation creationInfo = new ListCreationInformation(); creationInfo.Title = listName; creationInfo.TemplateType = (int)ListTemplateType.Tasks; List list = web.Lists.Add(creationInfo); context.ExecuteQuery(); list.Update(); Field field = list.Fields.AddFieldAsXml("<Field DisplayName='Description' Type='Text' InternalName='Description' />", true, AddFieldOptions.DefaultValue); context.ExecuteQuery(); currentListName = listName; } catch (Exception) { output.Show("List already exists!"); return; } }
/// <summary> /// Create and update a SharePoint list /// </summary> /// <param name="context"></param> public static void CreateListOnSharePoint(ClientContext context) { ConsoleColor defaultForeground = Console.ForegroundColor; string title = Utils.GetInput("Give the new title for the list", false, defaultForeground); string description = Utils.GetInput("Give the new description for the list", false, defaultForeground); // The SharePoint web at the URL. Web web = context.Web; ListCreationInformation creationInfo = new ListCreationInformation(); creationInfo.Title = title; creationInfo.TemplateType = (int)ListTemplateType.GenericList; List list = web.Lists.Add(creationInfo); list.Description = description; list.Update(); context.ExecuteQuery(); RetrieveAllSharePointLists(context); Console.WriteLine( "--------------------------------- List created successfull on sharepoint website --------------------------------------------------"); }
public void CreateTable <T>() { Type entityType = typeof(T); string listName = EntityHelper.GetInternalNameFromEntityType(entityType); using (var clientContext = GetClientContext()) { try { ValidateBeforeListCreation(clientContext, listName); Dictionary <string, Guid> lookupTableIds = GetLookupTableIds(clientContext, entityType); ListCreationInformation listCreationInfo = BuildListCreationInformation(clientContext, entityType); var newList = clientContext.Web.Lists.Add(listCreationInfo); SetRating <T>(newList); SetVersioning <T>(newList); AddFieldsToTable(clientContext, newList, entityType.GetProperties(), lookupTableIds); foreach (var property in entityType.GetProperties().Where(q => q.GetCustomAttribute <IgnoreOnCreationAttribute>() != null && q.GetCustomAttribute <DisplayNameAttribute>() != null)) { // internal fields with custom displayname _awecsomeField.ChangeDisplaynameFromField(newList, property); } clientContext.ExecuteQuery(); } catch (Exception ex) { var outerException = new Exception("error creating list", ex); outerException.Data.Add("List", listName); _log.Error($"Failed creating list {listName}", ex); throw outerException; } } _log.Debug($"List '{listName}' created."); }
static void Main(string[] args) { var url = "http://sp2016/"; var spourl = "https://integrationsonline.sharepoint.com/sites/training"; var user = "******"; var skiponline = !true; //Using Explicit Credential - use for SPO if (skiponline) { using (var context = new ClientContext(spourl)) { var pwd = SecureStringExtensions.GetConsolePassword(); context.Credentials = new SharePointOnlineCredentials(user, pwd.ToSecureString()); context.Load(context.Web, w => w.Title); context.ExecuteQuery(); Console.WriteLine("Your site title is: " + context.Web.Title); } } //Using Credential Cache - use for SP2013, SP2016 using (var context = new ClientContext(url)) { var credentials = CredentialCache.DefaultNetworkCredentials; context.Credentials = credentials; //Get Web Title context.Load(context.Web, w => w.Title); context.ExecuteQuery(); Console.WriteLine("Your site title is: " + context.Web.Title); //Set Web Description Web web = context.Web; web.Description = "Changed by CSOM"; web.Update(); context.Load(context.Web, w => w.Description); context.ExecuteQuery(); Console.WriteLine("Your site description is: " + context.Web.Description); //Get Lists in Web ListCollection lists = web.Lists; //context.Load(lists); context.Load(lists, l => l.Include(item => item.Title, item => item.Created)); context.ExecuteQuery(); foreach (List list in lists) { Console.WriteLine(list.Title); } //Upload File var sourceFilePath = @"d:\Sample.docx"; var targetUrl = "/Documents"; var targetFileUrl = $"{targetUrl}/{Path.GetFileName(sourceFilePath)}"; using (var fs = new FileStream(sourceFilePath, FileMode.Open)) { File.SaveBinaryDirect(context, targetFileUrl, fs, true); } //Set document properties var uploadedFile = context.Web.GetFileByServerRelativeUrl(targetFileUrl); var listItem = uploadedFile.ListItemAllFields; listItem["Information"] = "Uploaded by CSOM"; listItem.Update(); context.ExecuteQuery(); Console.WriteLine("Upload done"); //Create List - Traditional ListCreationInformation listInfo = new ListCreationInformation { Title = "WithoutPnP", TemplateType = (int)ListTemplateType.GenericList }; List cl = web.Lists.Add(listInfo); cl.Update(); context.ExecuteQuery(); //Create List PnP - PnP var pnpl = context.Web.CreateList(ListTemplateType.GenericList, "WithPnP", false); Console.WriteLine("List created"); } Console.ReadLine(); }
public override void ProvisionObjects(Web web, ProvisioningTemplate template) { Log.Info(Constants.LOGGING_SOURCE_FRAMEWORK_PROVISIONING, CoreResources.Provisioning_ObjectHandlers_ListInstances); if (template.Lists.Any()) { //var parser = new TokenParser(web); if (!web.IsPropertyAvailable("ServerRelativeUrl")) { web.Context.Load(web, w => w.ServerRelativeUrl); web.Context.ExecuteQueryRetry(); } web.Context.Load(web.Lists, lc => lc.IncludeWithDefaultProperties(l => l.RootFolder.ServerRelativeUrl)); web.Context.ExecuteQueryRetry(); var existingLists = web.Lists.AsEnumerable <List>().Select(existingList => existingList.RootFolder.ServerRelativeUrl).ToList(); var serverRelativeUrl = web.ServerRelativeUrl; var createdLists = new List <ListInfo>(); #region Lists foreach (var list in template.Lists) { if (!existingLists.Contains(UrlUtility.Combine(serverRelativeUrl, list.Url))) { var listCreate = new ListCreationInformation(); listCreate.Description = list.Description; listCreate.TemplateType = list.TemplateType; listCreate.Title = list.Title; // the line of code below doesn't add the list to QuickLaunch // the OnQuickLaunch property is re-set on the Created List object listCreate.QuickLaunchOption = list.OnQuickLaunch ? QuickLaunchOptions.On : QuickLaunchOptions.Off; listCreate.Url = list.Url.ToParsedString(); listCreate.TemplateFeatureId = list.TemplateFeatureID; var createdList = web.Lists.Add(listCreate); createdList.Update(); web.Context.Load(createdList, l => l.BaseTemplate); web.Context.ExecuteQueryRetry(); if (!String.IsNullOrEmpty(list.DocumentTemplate)) { createdList.DocumentTemplateUrl = list.DocumentTemplate.ToParsedString(); } // EnableAttachments are not supported for DocumentLibraries and Surveys // TODO: the user should be warned if (createdList.BaseTemplate != (int)ListTemplateType.DocumentLibrary && createdList.BaseTemplate != (int)ListTemplateType.Survey) { createdList.EnableAttachments = list.EnableAttachments; } createdList.EnableModeration = list.EnableModeration; createdList.EnableVersioning = list.EnableVersioning; if (list.EnableVersioning) { createdList.MajorVersionLimit = list.MaxVersionLimit; if (createdList.BaseTemplate == (int)ListTemplateType.DocumentLibrary) { // Only supported on Document Libraries createdList.EnableMinorVersions = list.EnableMinorVersions; if (list.EnableMinorVersions) { createdList.MajorWithMinorVersionsLimit = list.MinorVersionLimit; // Set only if enabled, otherwise you'll get exception due setting value to zero. } } } createdList.OnQuickLaunch = list.OnQuickLaunch; createdList.EnableFolderCreation = list.EnableFolderCreation; createdList.Hidden = list.Hidden; createdList.ContentTypesEnabled = list.ContentTypesEnabled; createdList.Update(); web.Context.Load(createdList.Views); web.Context.Load(createdList, l => l.Id); web.Context.Load(createdList, l => l.RootFolder.ServerRelativeUrl); web.Context.Load(createdList.ContentTypes); web.Context.ExecuteQueryRetry(); // Remove existing content types only if there are custom content type bindings List <Microsoft.SharePoint.Client.ContentType> contentTypesToRemove = new List <Microsoft.SharePoint.Client.ContentType>(); if (list.RemoveExistingContentTypes && list.ContentTypeBindings.Count > 0) { foreach (var ct in createdList.ContentTypes) { contentTypesToRemove.Add(ct); } } ContentTypeBinding defaultCtBinding = null; foreach (var ctBinding in list.ContentTypeBindings) { createdList.AddContentTypeToListById(ctBinding.ContentTypeId, searchContentTypeInSiteHierarchy: true); if (ctBinding.Default) { defaultCtBinding = ctBinding; } } // default ContentTypeBinding should be set last because // list extension .SetDefaultContentTypeToList() re-sets // the list.RootFolder UniqueContentTypeOrder property // which may cause missing CTs from the "New Button" if (defaultCtBinding != null) { createdList.SetDefaultContentTypeToList(defaultCtBinding.ContentTypeId); } // Effectively remove existing content types, if any foreach (var ct in contentTypesToRemove) { ct.DeleteObject(); web.Context.ExecuteQueryRetry(); } createdLists.Add(new ListInfo { CreatedList = createdList, ListInstance = list }); TokenParser.AddToken(new ListIdToken(web, list.Title, createdList.Id)); TokenParser.AddToken(new ListUrlToken(web, list.Title, createdList.RootFolder.ServerRelativeUrl.Substring(web.ServerRelativeUrl.Length + 1))); } } #endregion #region Fields foreach (var listInfo in createdLists) { if (listInfo.ListInstance.Fields.Any()) { foreach (var field in listInfo.ListInstance.Fields) { XElement fieldElement = XElement.Parse(field.SchemaXml.ToParsedString()); var id = fieldElement.Attribute("ID").Value; Guid fieldGuid = Guid.Empty; if (Guid.TryParse(id, out fieldGuid)) { if (!listInfo.CreatedList.FieldExistsById(fieldGuid)) { var listIdentifier = fieldElement.Attribute("List") != null?fieldElement.Attribute("List").Value : null; if (listIdentifier != null) { // Temporary remove list attribute from fieldElement fieldElement.Attribute("List").Remove(); } var fieldXml = fieldElement.ToString(); listInfo.CreatedList.Fields.AddFieldAsXml(fieldXml, false, AddFieldOptions.DefaultValue); } } } } listInfo.CreatedList.Update(); web.Context.ExecuteQueryRetry(); } #endregion #region FieldRefs foreach (var listInfo in createdLists) { if (listInfo.ListInstance.FieldRefs.Any()) { foreach (var fieldRef in listInfo.ListInstance.FieldRefs) { var field = web.GetFieldById <Field>(fieldRef.Id); if (!listInfo.CreatedList.FieldExistsById(fieldRef.Id)) { var createdField = listInfo.CreatedList.Fields.Add(field); if (!string.IsNullOrEmpty(fieldRef.DisplayName)) { createdField.Title = fieldRef.DisplayName; } createdField.Hidden = fieldRef.Hidden; createdField.Required = fieldRef.Required; createdField.Update(); } } listInfo.CreatedList.Update(); web.Context.ExecuteQueryRetry(); } } #endregion #region Views foreach (var listInfo in createdLists) { var list = listInfo.ListInstance; var createdList = listInfo.CreatedList; if (list.Views.Any() && list.RemoveExistingViews) { while (createdList.Views.Any()) { createdList.Views[0].DeleteObject(); } web.Context.ExecuteQueryRetry(); } foreach (var view in list.Views) { var viewDoc = XDocument.Parse(view.SchemaXml); var displayNameXml = viewDoc.Root.Attribute("DisplayName"); if (displayNameXml == null) { throw new ApplicationException("Invalid View element, missing a valid value for the attribute DisplayName."); } var viewTitle = displayNameXml.Value; // Type var viewTypeString = viewDoc.Root.Attribute("Type") != null?viewDoc.Root.Attribute("Type").Value : "None"; viewTypeString = viewTypeString[0].ToString().ToUpper() + viewTypeString.Substring(1).ToLower(); var viewType = (ViewType)Enum.Parse(typeof(ViewType), viewTypeString); // Fields string[] viewFields = null; var viewFieldsElement = viewDoc.Descendants("ViewFields").FirstOrDefault(); if (viewFieldsElement != null) { viewFields = (from field in viewDoc.Descendants("ViewFields").Descendants("FieldRef") select field.Attribute("Name").Value).ToArray(); } // Default view var viewDefault = viewDoc.Root.Attribute("DefaultView") != null && Boolean.Parse(viewDoc.Root.Attribute("DefaultView").Value); // Row limit bool viewPaged = true; uint viewRowLimit = 30; var rowLimitElement = viewDoc.Descendants("RowLimit").FirstOrDefault(); if (rowLimitElement != null) { if (rowLimitElement.Attribute("Paged") != null) { viewPaged = bool.Parse(rowLimitElement.Attribute("Paged").Value); } viewRowLimit = uint.Parse(rowLimitElement.Value); } // Query var viewQuery = new StringBuilder(); foreach (var queryElement in viewDoc.Descendants("Query").Elements()) { viewQuery.Append(queryElement.ToString()); } var viewCI = new ViewCreationInformation { ViewFields = viewFields, RowLimit = viewRowLimit, Paged = viewPaged, Title = viewTitle, Query = viewQuery.ToString(), ViewTypeKind = viewType, PersonalView = false, SetAsDefaultView = viewDefault }; createdList.Views.Add(viewCI); createdList.Update(); web.Context.ExecuteQueryRetry(); } // Removing existing views set the OnQuickLaunch option to false and need to be re-set. if (list.OnQuickLaunch && list.RemoveExistingViews && list.Views.Count > 0) { createdList.RefreshLoad(); web.Context.ExecuteQueryRetry(); createdList.OnQuickLaunch = list.OnQuickLaunch; createdList.Update(); web.Context.ExecuteQueryRetry(); } } #endregion #region DataRows foreach (var listInfo in createdLists) { var listInstance = listInfo.ListInstance; if (listInstance.DataRows != null && listInstance.DataRows.Any()) { var list = listInfo.CreatedList; foreach (var dataRow in listInfo.ListInstance.DataRows) { ListItemCreationInformation listitemCI = new ListItemCreationInformation(); var listitem = list.AddItem(listitemCI); foreach (var dataValue in dataRow.Values) { listitem[dataValue.Key.ToParsedString()] = dataValue.Value.ToParsedString(); } listitem.Update(); web.Context.ExecuteQueryRetry(); // TODO: Run in batches? } } } #endregion } }
void ProvisionSample1(Web web) { //Delete list if it already exists ListCollection lists = web.Lists; IEnumerable <List> results = web.Context.LoadQuery <List>(lists.Where(list => list.Title == "CSR-Priority-Color")); web.Context.ExecuteQuery(); List existingList = results.FirstOrDefault(); if (existingList != null) { existingList.DeleteObject(); web.Context.ExecuteQuery(); } //Create list ListCreationInformation creationInfo = new ListCreationInformation(); creationInfo.Title = "CSR-Priority-Color"; creationInfo.TemplateType = (int)ListTemplateType.Tasks; List newlist = web.Lists.Add(creationInfo); newlist.Update(); web.Context.Load(newlist); web.Context.ExecuteQuery(); //Add items Microsoft.SharePoint.Client.ListItem item1 = newlist.AddItem(new ListItemCreationInformation()); item1["Title"] = "Task 1"; item1["StartDate"] = "2014-1-1"; item1["DueDate"] = "2014-2-1"; item1["Priority"] = "(1) High"; item1.Update(); Microsoft.SharePoint.Client.ListItem item2 = newlist.AddItem(new ListItemCreationInformation()); item2["Title"] = "Task 2"; item2["StartDate"] = "2014-1-1"; item2["DueDate"] = "2014-2-1"; item2["Priority"] = "(2) Normal"; item2.Update(); Microsoft.SharePoint.Client.ListItem item3 = newlist.AddItem(new ListItemCreationInformation()); item3["Title"] = "Task 3"; item3["StartDate"] = "2014-1-1"; item3["DueDate"] = "2014-2-1"; item3["Priority"] = "(3) Low"; item3.Update(); //Create sample view ViewCreationInformation sampleViewCreateInfo = new ViewCreationInformation(); sampleViewCreateInfo.Title = "CSR Sample View"; sampleViewCreateInfo.ViewFields = new string[] { "DocIcon", "LinkTitle", "StartDate", "DueDate", "Priority" }; sampleViewCreateInfo.SetAsDefaultView = true; Microsoft.SharePoint.Client.View sampleView = newlist.Views.Add(sampleViewCreateInfo); sampleView.Update(); web.Context.ExecuteQuery(); web.Context.Load(newlist, l => l.DefaultViewUrl); web.Context.ExecuteQuery(); //Register JS files via JSLink properties RegisterJStoWebPart(web, newlist.DefaultViewUrl, "~sitecollection/Style Library/JSLink-Samples/PriorityColor.js"); }
void ProvisionSample9(Web web) { // First list: Cars //Delete list if it already exists ListCollection lists = web.Lists; IEnumerable <List> results = web.Context.LoadQuery <List>(lists.Where(list => list.Title == "CSR-Dependent-Fields-Cars")); web.Context.ExecuteQuery(); List existingList = results.FirstOrDefault(); if (existingList != null) { existingList.DeleteObject(); web.Context.ExecuteQuery(); } //Create list ListCreationInformation creationInfo = new ListCreationInformation(); creationInfo.Title = "CSR-Dependent-Fields-Cars"; creationInfo.TemplateType = (int)ListTemplateType.GenericList; List carslist = web.Lists.Add(creationInfo); carslist.Update(); web.Context.Load(carslist); web.Context.ExecuteQuery(); //Add items Microsoft.SharePoint.Client.ListItem item1 = carslist.AddItem(new ListItemCreationInformation()); item1["Title"] = "BMW X5"; item1.Update(); Microsoft.SharePoint.Client.ListItem item2 = carslist.AddItem(new ListItemCreationInformation()); item2["Title"] = "Chevrolet Trax"; item2.Update(); Microsoft.SharePoint.Client.ListItem item3 = carslist.AddItem(new ListItemCreationInformation()); item3["Title"] = "Ford Kuga"; item3.Update(); Microsoft.SharePoint.Client.ListItem item4 = carslist.AddItem(new ListItemCreationInformation()); item4["Title"] = "Fiat 500L"; item4.Update(); Microsoft.SharePoint.Client.ListItem item5 = carslist.AddItem(new ListItemCreationInformation()); item5["Title"] = "Kia Soul"; item5.Update(); // Second list: Orders //Delete list if it already exists results = web.Context.LoadQuery <List>(lists.Where(list => list.Title == "CSR-Dependent-Fields")); web.Context.ExecuteQuery(); existingList = results.FirstOrDefault(); if (existingList != null) { existingList.DeleteObject(); web.Context.ExecuteQuery(); } //Create list creationInfo = new ListCreationInformation(); creationInfo.Title = "CSR-Dependent-Fields"; creationInfo.TemplateType = (int)ListTemplateType.GenericList; List newlist = web.Lists.Add(creationInfo); newlist.Update(); web.Context.Load(newlist); web.Context.ExecuteQuery(); //Add fields newlist.Fields.AddFieldAsXml("<Field Type=\"" + FieldType.Lookup + "\" Name=\"Car\" DisplayName=\"Car\" ID=\"" + Guid.NewGuid() + "\" Group=\"CSR Samples\" List=\"" + carslist.Id + "\" ShowField=\"Title\" />", false, AddFieldOptions.DefaultValue); newlist.Fields.AddFieldAsXml("<Field Type=\"" + FieldType.Choice + "\" Name=\"Color\" DisplayName=\"Color\" Format=\"" + ChoiceFormatType.RadioButtons + "\" ID=\"" + Guid.NewGuid() + "\" Group=\"CSR Samples\"><Default></Default><CHOICES><CHOICE>Black</CHOICE><CHOICE>White</CHOICE><CHOICE>Green</CHOICE><CHOICE>Blue</CHOICE><CHOICE>Red</CHOICE></CHOICES></Field>", false, AddFieldOptions.DefaultValue); newlist.Update(); web.Context.ExecuteQuery(); //Add items Microsoft.SharePoint.Client.ListItem newItem = newlist.AddItem(new ListItemCreationInformation()); newItem["Title"] = "Sample order"; newItem["Car"] = 1; newItem["Color"] = "Green"; newItem.Update(); //Create sample view ViewCreationInformation sampleViewCreateInfo = new ViewCreationInformation(); sampleViewCreateInfo.Title = "CSR Sample View"; sampleViewCreateInfo.ViewFields = new string[] { "LinkTitle", "Car", "Color" }; sampleViewCreateInfo.SetAsDefaultView = true; Microsoft.SharePoint.Client.View sampleView = newlist.Views.Add(sampleViewCreateInfo); sampleView.Update(); // Load information about default new and edit forms web.Context.Load(newlist, l => l.DefaultEditFormUrl, l => l.DefaultNewFormUrl); web.Context.ExecuteQuery(); //Register JS files via JSLink properties RegisterJStoWebPart(web, newlist.DefaultNewFormUrl, "~sitecollection/Style Library/JSLink-Samples/DependentFields.js"); RegisterJStoWebPart(web, newlist.DefaultEditFormUrl, "~sitecollection/Style Library/JSLink-Samples/DependentFields.js"); }
public ActionResult Index() { var model = new IndexAdvertisementViewModel(); var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); if (spContext != null) { Session["SpContext"] = spContext; Session["SpHostUrl"] = spContext.SPHostUrl; } else { spContext = Session["SpContext"] as SharePointContext; } using (var clientContext = spContext.CreateUserClientContextForSPHost()) { if (clientContext != null) { ListCollection listCol = clientContext.Web.Lists; TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext); User currentUser = clientContext.Web.CurrentUser; clientContext.Load(taxonomySession); clientContext.Load(listCol, y => y.Where(x => x.Title == "Annonser")); clientContext.Load(currentUser); clientContext.ExecuteQuery(); //List list = clientContext.Web.Lists.GetByTitle("Annonser"); Fungerar utan lista?? if (taxonomySession != null) { #region Create Category Taxonomy Session["TaxSession"] = taxonomySession; TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore(); TermGroupCollection termGroupCol = termStore.Groups; clientContext.Load(termGroupCol, t => t.Where(y => y.Name == "Advertisements")); clientContext.ExecuteQuery(); var termGroup = termGroupCol.FirstOrDefault(); if (termGroup == null) { TermGroup annonsKategorierGroup = termStore.CreateGroup("Advertisements", Guid.NewGuid()); clientContext.ExecuteQuery(); TermSet annonsKateGorierTermSet = annonsKategorierGroup.CreateTermSet("Categories", Guid.NewGuid(), 1033); clientContext.ExecuteQuery(); annonsKateGorierTermSet.CreateTerm("Electronics", 1033, Guid.NewGuid()); annonsKateGorierTermSet.CreateTerm("Appliances", 1033, Guid.NewGuid()); annonsKateGorierTermSet.CreateTerm("Clothing", 1033, Guid.NewGuid()); annonsKateGorierTermSet.CreateTerm("Books", 1033, Guid.NewGuid()); annonsKateGorierTermSet.CreateTerm("Office", 1033, Guid.NewGuid()); annonsKateGorierTermSet.CreateTerm("Other", 1033, Guid.NewGuid()); clientContext.ExecuteQuery(); termGroup = annonsKategorierGroup; } #endregion if (termGroup != null) { TermSet termSet = termGroup.TermSets.GetByName("Categories"); TermCollection terms = termSet.GetAllTerms(); clientContext.Load(termSet); clientContext.Load(terms); clientContext.ExecuteQuery(); foreach (Term term in terms) { SelectListItem newItem = new SelectListItem { Value = term.Id.ToString(), Text = term.Name }; model.Categories.Add(newItem); } } } var list = listCol.FirstOrDefault(); if (list == null) { #region Create Advertisement List ListCreationInformation listCreationInfo = new ListCreationInformation(); listCreationInfo.Title = "Annonser"; listCreationInfo.TemplateType = (int)ListTemplateType.GenericList; var newList = clientContext.Web.Lists.Add(listCreationInfo); FieldCollection fieldCol = newList.Fields; Field defaultTitleField = fieldCol.GetByTitle("Title"); clientContext.Load(fieldCol); clientContext.Load(defaultTitleField); clientContext.ExecuteQuery(); defaultTitleField.Hidden = true; defaultTitleField.SetShowInDisplayForm(false); defaultTitleField.SetShowInEditForm(false); defaultTitleField.SetShowInNewForm(false); defaultTitleField.Required = false; defaultTitleField.Update(); Field rubrikField = newList.Fields.AddFieldAsXml("<Field DisplayName='Rubrik' Type='Text' Name='Rubrik' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView); Field textField = newList.Fields.AddFieldAsXml("<Field DisplayName='Text' Type='Text' Name='Text' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView); Field prisField = newList.Fields.AddFieldAsXml("<Field DisplayName='Pris' Type='Number' Name='Pris' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView); Field datumField = newList.Fields.AddFieldAsXml("<Field DisplayName='Datum' Type='DateTime' Name='Datum' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView); //Field anvandareField = newList.Fields.AddFieldAsXml("<Field DisplayName='Användare' Type='User' Name='Anvandare' StaticName='Anvandare' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView); Field kategoriField = newList.Fields.AddFieldAsXml("<Field DisplayName='Kategori' Type='TaxonomyFieldType' Name='Kategori' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView); FieldNumber rubrikFieldNumber = clientContext.CastTo <FieldNumber>(rubrikField); FieldNumber textFieldNumber = clientContext.CastTo <FieldNumber>(textField); FieldNumber prisFieldNumber = clientContext.CastTo <FieldNumber>(prisField); FieldNumber datumFieldNumber = clientContext.CastTo <FieldNumber>(datumField); //FieldNumber anvandareFieldNumber = clientContext.CastTo<FieldNumber>(anvandareField); //FieldNumber kategoryFieldNumber = clientContext.CastTo<FieldNumber>(anvandareField); Guid termStoreId = Guid.Empty; Guid termSetId = Guid.Empty; GetTaxonomyFieldInfo(clientContext, out termStoreId, out termSetId, "Categories"); TaxonomyField kategoryFieldNumber = clientContext.CastTo <TaxonomyField>(kategoriField); kategoryFieldNumber.SspId = termStoreId; kategoryFieldNumber.TermSetId = termSetId; kategoryFieldNumber.TargetTemplate = String.Empty; kategoryFieldNumber.AnchorId = Guid.Empty; rubrikFieldNumber.Update(); textFieldNumber.Update(); prisFieldNumber.Update(); datumFieldNumber.Update(); //anvandareFieldNumber.Update(); kategoryFieldNumber.Update(); View view = newList.Views.GetByTitle("All Items"); clientContext.Load(view); clientContext.ExecuteQuery(); ViewFieldCollection viewFields = view.ViewFields; viewFields.Remove("LinkTitle"); view.Update(); clientContext.ExecuteQuery(); list = newList; #endregion } CamlQuery cQuery = new CamlQuery(); cQuery.ViewXml = @"<View> <Query> <Where> <Eq> <FieldRef Name='Author' LookupId='True'/> <Value Type='Lookup'>" + currentUser.Id + @"</Value> </Eq> </Where> </Query> </View>"; var listItems = list.GetItems(cQuery); clientContext.Load(listItems); clientContext.ExecuteQuery(); foreach (ListItem listItem in listItems) { AdvertisementViewModel tempObj = new AdvertisementViewModel { Title = listItem["Rubrik"].ToString(), Text = listItem["Text"].ToString(), Price = int.Parse(listItem["Pris"].ToString()), Date = DateTime.Parse(listItem["Datum"].ToString()), User = listItem["Author"] as FieldUserValue, Category = listItem["Kategori"] as TaxonomyFieldValue, ListItemId = listItem["ID"].ToString() }; model.Advertisements.Add(tempObj); } } return(View(model)); } }
private List CreateList(List sourceList, ClientContext sourceContext, FieldCollection fldcoll, ClientContext destContext, string strDestSite, string lstInternalName, List destinationList, string strListName) { // List listByTitleCS = GetListByTitleCS(destContext, strListName); List listByTitleCS = sourceContext.Web.Lists.GetByTitle(strListName);; Web web = destContext.Web; // if (listByTitleCS == null) // { ListCreationInformation parameters = new ListCreationInformation { Title = lstInternalName, TemplateType = 100 }; List clientObject = web.Lists.Add(parameters); clientObject.Description = lstInternalName + "Description"; destinationList = destContext.Web.Lists.GetByTitle(lstInternalName); destContext.Load <ViewCollection>(destinationList.Views, new Expression <Func <ViewCollection, object> > [0]); destContext.ExecuteQuery(); sourceContext.Load <ViewCollection>(sourceList.Views, new Expression <Func <ViewCollection, object> > [0]); sourceContext.ExecuteQuery(); Microsoft.SharePoint.Client.View view = sourceList.Views[0]; ViewFieldCollection viewFields = view.ViewFields; sourceContext.Load <ViewFieldCollection>(viewFields, new Expression <Func <ViewFieldCollection, object> > [0]); sourceContext.ExecuteQuery(); foreach (Field field in fldcoll) { if (!field.FromBaseType) { object[] objArray1 = new object[] { "<Field DisplayName= '", field.InternalName, "' Name='", field.InternalName, "' Type='", field.FieldTypeKind, "' />" }; clientObject.Fields.AddFieldAsXml(string.Concat(objArray1), true, AddFieldOptions.DefaultValue); } else if ((field.InternalName == "Created") && view.ViewFields.Contains <string>("Created")) { Microsoft.SharePoint.Client.View view2 = destinationList.Views[0]; view2.ViewFields.Add("Created"); view2.Update(); } else if ((field.InternalName == "Author") && view.ViewFields.Contains <string>("Author")) { Microsoft.SharePoint.Client.View view3 = destinationList.Views[0]; view3.ViewFields.Add("Created By"); view3.Update(); } else if ((field.InternalName == "Modified") && view.ViewFields.Contains <string>("Modified")) { Microsoft.SharePoint.Client.View view4 = destinationList.Views[0]; view4.ViewFields.Add("Modified"); view4.Update(); } else if ((field.InternalName == "Editor") && view.ViewFields.Contains <string>("Editor")) { Microsoft.SharePoint.Client.View view5 = destinationList.Views[0]; view5.ViewFields.Add("Modified By"); view5.Update(); } } destinationList = destContext.Web.Lists.GetByTitle(lstInternalName); destContext.Load <FieldCollection>(destinationList.Fields, new Expression <Func <FieldCollection, object> > [0]); destContext.ExecuteQuery(); clientObject.Title = strListName; clientObject.Update(); destContext.Load <List>(clientObject, new Expression <Func <List, object> > [0]); destContext.ExecuteQuery(); return(destinationList); // } destinationList = destContext.Web.Lists.GetByTitle(strListName); destContext.Load <FieldCollection>(destinationList.Fields, new Expression <Func <FieldCollection, object> > [0]); destContext.ExecuteQuery(); // this.DeleteAllListItems(destContext, destinationList); return(destinationList); }
private void bkWorkerProcess_DoWorkAsync(object sender, DoWorkEventArgs e) { try { // string siteUrl = txtSite.Text; string userName = txtUser.Text; string password = txtPassword.Text; string whiteList = txtWhiteList.Text; (sender as BackgroundWorker).ReportProgress(5, "The configuration process was started"); //if (siteUrl.Substring(siteUrl.Length - 1) == "/") //{ // siteUrl = siteUrl.Substring(0, siteUrl.Length - 1); //} OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager(); using (var clientContext = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteAdminUrl, userName, password)) { (sender as BackgroundWorker).ReportProgress(10, "Getting access to admin site"); Tenant adminSite = new Tenant(clientContext); var siteName = txtSite.Text; Regex pattern = new Regex("[&_,.;:/\"!@$%^+=\\|<>{}#~*? ]"); siteName = pattern.Replace(siteName, string.Empty); Microsoft.SharePoint.Client.Site site = null; if (adminSite.CheckIfSiteExists("https://jreckner.sharepoint.com/sites/" + siteName, "Active")) { throw new Exception("The site: " + txtSite.Text + ", already exists. Please choose another name."); } var siteCreationProperties = new SiteCreationProperties(); var sitedesign = new OfficeDevPnP.Core.Entities.SiteEntity(); string[] owners = { txtUser.Text }; (sender as BackgroundWorker).ReportProgress(15, "Creating site collection"); //CommunicationSiteCollectionCreationInformation modernteamSiteInfo = new CommunicationSiteCollectionCreationInformation //{ // Description = "", // Owner = txtUser.Text, // SiteDesignId = new Guid("6a3f7a23-031b-4072-bf24-4193c14af65f"), // Title = txtSite.Text, // Lcid = 1033, // AllowFileSharingForGuestUsers = false, // Url = "https://jreckner.sharepoint.com/sites/" + siteName //}; TeamSiteCollectionCreationInformation modernteamSiteInfo = new TeamSiteCollectionCreationInformation() { DisplayName = txtSite.Text, //Owners = owners, //Alias = "https://jreckner.sharepoint.com/sites/" + siteName, Alias = siteName, Lcid = 1033, IsPublic = true, Description = "" }; var result = Task.Run(async() => { return(await clientContext.CreateSiteAsync(modernteamSiteInfo)); }).Result; siteUrl = result.Url; var properties = adminSite.GetSitePropertiesByUrl(siteUrl, true); clientContext.Load(properties); site = adminSite.GetSiteByUrl(siteUrl); Web web = site.RootWeb; clientContext.Load(web); ListCreationInformation doclist = new ListCreationInformation() { Title = "Document Library", TemplateType = 101, }; web.Lists.Add(doclist); (sender as BackgroundWorker).ReportProgress(20, "Creating Document Library"); clientContext.ExecuteQuery(); (sender as BackgroundWorker).ReportProgress(30, "Configuring WhiteList"); properties.SharingDomainRestrictionMode = SharingDomainRestrictionModes.AllowList; properties.SharingAllowedDomainList = whiteList; properties.SharingCapability = SharingCapabilities.ExternalUserSharingOnly; properties.Update(); clientContext.ExecuteQuery(); } using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password)) { (sender as BackgroundWorker).ReportProgress(40, "Copy disclaimer file"); callResponseFlow(siteUrl, userName, userName); (sender as BackgroundWorker).ReportProgress(50, "Getting access to site collection"); Web web = ctx.Web; ctx.Load(web); ctx.ExecuteQueryRetry(); var page2 = ctx.Web.AddClientSidePage("HomePageDisclaimer.aspx", true); page2.AddSection(CanvasSectionTemplate.OneColumn, 5); CanvasSection section = new CanvasSection(page2, CanvasSectionTemplate.OneColumn, page2.Sections.Count + 1); page2.Sections.Add(section); page2.PageTitle = "Disclaimer"; page2.LayoutType = ClientSidePageLayoutType.Home; page2.DisableComments(); page2.PromoteAsHomePage(); page2.PageHeader.LayoutType = ClientSidePageHeaderLayoutType.NoImage; page2.Save(); (sender as BackgroundWorker).ReportProgress(60, "Generating disclaimer Page"); // Check if file exists //Microsoft.SharePoint.Client.Folder folder = ctx.Web.GetFolderByServerRelativeUrl(ctx.Web.ServerRelativeUrl + "/" + library); var documentFile = ctx.Web.GetFileByServerRelativeUrl(ctx.Web.ServerRelativeUrl + "/" + library + "/" + fileName); web.Context.Load(documentFile, f => f.Exists); // Only load the Exists property web.Context.ExecuteQuery(); if (documentFile.Exists) { Console.WriteLine("File exists!!!!"); //} ctx.Load(documentFile); ctx.Load(documentFile, w => w.SiteId); ctx.Load(documentFile, w => w.WebId); ctx.Load(documentFile, w => w.ListId); ctx.Load(documentFile, w => w.UniqueId); ctx.ExecuteQuery(); //if (documentFile != null) //{ //si el documento existe var pdfWebPart = page2.InstantiateDefaultWebPart(DefaultClientSideWebParts.DocumentEmbed); var url = new Uri(ctx.Web.Url + "/" + library + "/" + fileName); pdfWebPart.Properties["siteId"] = documentFile.SiteId; pdfWebPart.Properties["webId"] = documentFile.WebId; pdfWebPart.Properties["listId"] = documentFile.ListId; pdfWebPart.Properties["uniqueId"] = documentFile.UniqueId; pdfWebPart.Properties["file"] = url.AbsoluteUri; pdfWebPart.Properties["serverRelativeUrl"] = documentFile.ServerRelativeUrl; pdfWebPart.Properties["wopiurl"] = String.Format("{0}/_layouts/15/{1}?sourcedoc=%7b{2}%7d&action=interactivepreview", web.Url, "WopiFrame.aspx", documentFile.UniqueId.ToString("D")); pdfWebPart.Properties["startPage"] = 1; page2.AddControl(pdfWebPart, section.Columns[0]); (sender as BackgroundWorker).ReportProgress(80, "Configuring webpart"); page2.Save(); page2.Publish(); } else { throw (new Exception("We can't not find the disclaimer file, please upload it to the site at Document library as 'Disclaimer.pdf' and apply the configuration again.")); } } (sender as BackgroundWorker).ReportProgress(100, "All configuration was applied correctly!!!"); //MessageBox.Show("All configuration was applied correctly!!!"); } catch (Exception ex) { string errormessage = ""; errormessage = ex.Message; if (ex.InnerException != null) { errormessage = ex.InnerException.Message; } (sender as BackgroundWorker).ReportProgress(0, "Error: " + ex.Message); } finally { finishprocess = true; } }
public void Initialize() { if (!TestCommon.AppOnlyTesting()) { Console.WriteLine("TaxonomyExtensionsTests.Initialise"); // Create some taxonomy groups and terms using (var clientContext = TestCommon.CreateClientContext()) { _termGroupName = "Test_Group_" + DateTime.Now.ToFileTime(); _termSetName = "Test_Termset_" + DateTime.Now.ToFileTime(); _termName = "Test_Term_" + DateTime.Now.ToFileTime(); var taxSession = TaxonomySession.GetTaxonomySession(clientContext); var termStore = taxSession.GetDefaultSiteCollectionTermStore(); // Termgroup // Does the termgroup exist? var termGroup = termStore.GetGroup(_termGroupId); clientContext.Load(termGroup, g => g.Id); clientContext.ExecuteQueryRetry(); // Create if non existant if (termGroup.ServerObjectIsNull.Value) { termGroup = termStore.CreateGroup(_termGroupName, _termGroupId); clientContext.Load(termGroup); clientContext.ExecuteQueryRetry(); } // Termset // Does the termset exist? var termSet = termStore.GetTermSet(_termSetId); clientContext.Load(termSet, ts => ts.Id); clientContext.ExecuteQueryRetry(); // Create if non existant if (termSet.ServerObjectIsNull.Value) { termSet = termGroup.CreateTermSet(_termSetName, _termSetId, 1033); clientContext.Load(termSet); clientContext.ExecuteQueryRetry(); } // Term // Does the term exist? var term = termStore.GetTerm(_termId); clientContext.Load(term, t => t.Id); clientContext.ExecuteQueryRetry(); // Create if non existant if (term.ServerObjectIsNull.Value) { term = termSet.CreateTerm(_termName, 1033, _termId); clientContext.ExecuteQueryRetry(); } else { var label = term.GetDefaultLabel(1033); clientContext.ExecuteQueryRetry(); _termName = label.Value; } // List ListCreationInformation listCI = new ListCreationInformation(); listCI.TemplateType = (int)ListTemplateType.GenericList; listCI.Title = "Test_List_" + DateTime.Now.ToFileTime(); var list = clientContext.Web.Lists.Add(listCI); clientContext.Load(list); clientContext.ExecuteQueryRetry(); _listId = list.Id; } } else { Assert.Inconclusive("Taxonomy tests are not supported when testing using app-only"); } }
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 SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties) { SPRemoteEventResult result = new SPRemoteEventResult(); //get the host web url Uri hostUrl = properties.AppEventProperties.HostWebFullUrl; //get the operation context so we can figure out the host URL for this service, from //which we can get the Authority for a client context System.ServiceModel.OperationContext oc = System.ServiceModel.OperationContext.Current; Uri localUrl = null; //UPDATE: THIS CODE WORKED FINE FOR WHEN YOU USE THE WEB APP CREATED BY VS.NET //FOR THE SHAREPOINT APP, BUT IT BREAKS WHEN YOU DEPLOY TO A REAL IIS SERVER //BECAUSE YOU END UP GETTING TWO BASEADDRESSES, BUT NOT WITH THE RIGHT SCHEME. //FOR EXAMPLE, THE FIRST ONE IS THE ADDRESS OF THIS HOST BUT WITH THE HTTP SCHEME. //THE SECOND ONE IS HTTPS, BUT THE HOST NAME IS THE FQDN OF THE SERVER. SINCE //SHAREPOINT DOESN'T RECOGNIZE THAT AS THE ENDPOINT IT TRUSTS FOR THIS CODE, IT BLOWS //UP WHEN RUNNING THE CODE BELOW AND THE WHOLE THING FAILS #region Code That Breaks In IIS ////now enumerate through the Host base addresses and look for the SSL connection //foreach (Uri u in oc.Host.BaseAddresses) //{ // if (u.Scheme.ToLower() == "https") // { // localUrl = u; // break; // } //} #endregion //assume first base address is ours, which it has been so far if (oc.Host.BaseAddresses.Count > 0) { localUrl = oc.Host.BaseAddresses[0]; } //make sure we found our local URL if (localUrl != null) { //using (ClientContext ctx = TokenHelper.CreateAppEventClientContext(properties, false)) using (ClientContext ctx = TokenHelper.GetClientContextWithContextToken(hostUrl.ToString(), properties.ContextToken, localUrl.Authority)) { if (ctx != null) { //try to retrieve the list first to see if it exists List l = ctx.Web.Lists.GetByTitle(LIST_NAME); ctx.Load(l); //have to put in a try block because of course it throw an exception if //list doesn't exist try { ctx.ExecuteQuery(); } catch (Exception noListEx) { //look to see if the exception is that the list doesn't exist if (noListEx.Message.ToLower().Contains("does not exist")) { //code here to create list Web web = ctx.Web; ListCreationInformation ci = new ListCreationInformation(); ci.Title = LIST_NAME; ci.TemplateType = (int)ListTemplateType.GenericList; ci.QuickLaunchOption = QuickLaunchOptions.Off; l = web.Lists.Add(ci); l.Description = "List for tracking events with the Event Planner Social App"; Field fldEventName = l.Fields.AddFieldAsXml("<Field DisplayName='EventName' Type='Text' />", true, AddFieldOptions.DefaultValue); Field fldSiteUrl = l.Fields.AddFieldAsXml("<Field DisplayName='SiteUrl' Type='Text' />", true, AddFieldOptions.DefaultValue); Field fldTwitterTags = l.Fields.AddFieldAsXml("<Field DisplayName='TwitterTags' Type='Text' />", true, AddFieldOptions.DefaultValue); Field fldEventDate = l.Fields.AddFieldAsXml("<Field DisplayName='EventDate' Type='DateTime' />", true, AddFieldOptions.DefaultValue); FieldDateTime dtEventDate = ctx.CastTo <FieldDateTime>(fldEventDate); dtEventDate.DisplayFormat = DateTimeFieldFormatType.DateOnly; dtEventDate.Update(); Field fldGraphID = l.Fields.AddFieldAsXml("<Field DisplayName='ObjectGraphID' Type='Text' />", true, AddFieldOptions.DefaultValue); FieldText txtGraphID = ctx.CastTo <FieldText>(fldGraphID); txtGraphID.Indexed = true; txtGraphID.Update(); l.Hidden = true; l.Update(); try { //this creates the list ctx.ExecuteQuery(); //all of the rest of this is to remove the list from the "Recent" list that appears //in sites by default, which is really a set of navigation links //get the site and root web, where the navigation lives Site s = ctx.Site; Web rw = s.RootWeb; //get the QuickLaunch navigation, which is where the Recent nav lives ctx.Load(rw, x => x.Navigation, x => x.Navigation.QuickLaunch); ctx.ExecuteQuery(); //now extract the Recent navigation node from the collection var vNode = from NavigationNode nn in rw.Navigation.QuickLaunch where nn.Title == "Recent" select nn; NavigationNode nNode = vNode.First <NavigationNode>(); //now we need to get the child nodes of Recent, that's where our list should be found ctx.Load(nNode.Children); ctx.ExecuteQuery(); var vcNode = from NavigationNode cn in nNode.Children where cn.Title == LIST_NAME select cn; //now that we have the node representing our list, delete it NavigationNode cNode = vcNode.First <NavigationNode>(); cNode.DeleteObject(); ctx.ExecuteQuery(); } catch (Exception newListFailEx) { Debug.WriteLine("Creation of new list failed: " + newListFailEx.Message); } } } //okay, so if we're here then the list should exist, and we should be good to go at this point } } } #region OOB Template Code //using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, false)) //{ // if (clientContext != null) // { // clientContext.Load(clientContext.Web); // clientContext.ExecuteQuery(); // } //} #endregion return(result); }
/// <summary> /// Provision Site Columns /// Provision Site Content Type /// Provision List /// Associate Content Type to List /// Provision List Views /// </summary> public void InstallComponentsToHostWeb(SiteProvisionerModel siteDefinition) { // obtain CSOM object for host web this.ClientContext.Load(this.ClientContext.Web, hw => hw.SiteGroups, hw => hw.Title, hw => hw.ContentTypes); this.ClientContext.ExecuteQuery(); // creates groups siteGroups.AddRange(this.ClientContext.Web.GetOrCreateSiteGroups(siteDefinition.Groups)); var fileJsonLocation = string.Format("{0}\\Content\\", this.SiteContent); foreach (var listDef in siteDefinition.Lists) { // Content Type var listName = listDef.ListName; var listDescription = listDef.ListDescription; // Site Columns FieldCollection fields = this.ClientContext.Web.Fields; this.ClientContext.Load(fields, f => f.Include(inc => inc.InternalName, inc => inc.JSLink, inc => inc.Title, inc => inc.Id)); this.ClientContext.ExecuteQuery(); // Create List Columns foreach (var fieldDef in listDef.FieldDefinitions) { var column = this.ClientContext.Web.CreateColumn(fieldDef, LogVerbose, LogError, siteGroups, fileJsonLocation); if (column == null) { LogWarning("Failed to create column {0}.", fieldDef.InternalName); } else { siteColumns.Add(new SPFieldDefinitionModel() { InternalName = column.InternalName, DisplayName = column.Title, FieldGuid = column.Id }); } } foreach (var contentDef in listDef.ContentTypes) { var contentTypeName = contentDef.Name; var contentTypeId = contentDef.ContentTypeId; if (!this.ClientContext.Web.ContentTypeExistsById(contentTypeId)) { this.ClientContext.Web.CreateContentType(contentTypeName, contentTypeId, contentDef.ContentTypeGroup); } foreach (var fieldDef in contentDef.FieldLinkRefs) { var siteColumn = listDef.FieldDefinitions.FirstOrDefault(f => f.InternalName == fieldDef); var convertedInternalName = siteColumn.DisplayNameMasked; if (!this.ClientContext.Web.FieldExistsByNameInContentType(contentTypeName, fieldDef) && !this.ClientContext.Web.FieldExistsByNameInContentType(contentTypeName, convertedInternalName)) { var column = this.siteColumns.FirstOrDefault(f => f.InternalName == fieldDef); this.ClientContext.Web.AddFieldToContentTypeByName(contentTypeName, column.FieldGuid, siteColumn.Required); } } // check to see if Picture library named Photos already exists ListCollection allLists = this.ClientContext.Web.Lists; IEnumerable <List> foundLists = this.ClientContext.LoadQuery(allLists.Where(list => list.Title == listName)); this.ClientContext.ExecuteQuery(); List accessRequest = foundLists.FirstOrDefault(); if (accessRequest == null) { // create Picture library named Photos if it does not already exist ListCreationInformation accessRequestInfo = new ListCreationInformation(); accessRequestInfo.Title = listName; accessRequestInfo.Description = listDescription; accessRequestInfo.QuickLaunchOption = listDef.QuickLaunch; accessRequestInfo.TemplateType = (int)listDef.ListTemplate; accessRequestInfo.Url = listName; accessRequest = this.ClientContext.Web.Lists.Add(accessRequestInfo); this.ClientContext.ExecuteQuery(); if (listDef.ContentTypeEnabled) { List list = this.ClientContext.Web.GetListByTitle(listName); list.ContentTypesEnabled = true; list.Update(); this.ClientContext.Web.Context.ExecuteQuery(); } } if (listDef.ContentTypeEnabled) { if (!this.ClientContext.Web.ContentTypeExistsByName(listName, contentTypeName)) { this.ClientContext.Web.AddContentTypeToListByName(listName, contentTypeName, true); } // Set the content type as default content type to the TestLib list //this.ClientContext.Web.SetDefaultContentTypeToList(listName, contentTypeId); } // Views ViewCollection views = accessRequest.Views; this.ClientContext.Load(views, f => f.Include(inc => inc.Id, inc => inc.Hidden, inc => inc.Title, inc => inc.DefaultView)); this.ClientContext.ExecuteQuery(); foreach (var viewDef in listDef.Views) { try { if (views.Any(v => v.Title == viewDef.Title)) { LogVerbose("View {0} found in list {1}", viewDef.Title, listName); continue; } var view = accessRequest.CreateView(viewDef.InternalName, viewDef.ViewCamlType, viewDef.FieldRefName, viewDef.RowLimit, viewDef.DefaultView, viewDef.QueryXml); this.ClientContext.Load(view, v => v.Title, v => v.Id, v => v.ServerRelativeUrl); this.ClientContext.ExecuteQuery(); view.Title = viewDef.Title; view.Update(); this.ClientContext.ExecuteQuery(); } catch (Exception ex) { LogError(ex, "Failed to create view {0} with XML:{1}", viewDef.Title, viewDef.QueryXml); } } } } }
/// <summary> /// Provision a list to the specified web using the list definition /// </summary> /// <param name="web">Client Context web</param> /// <param name="listDef">Hydrated list definition from JSON or Object</param> /// <param name="loggerVerbose">TODO: convert to static logger</param> /// <param name="loggerWarning">TODO: convert to static logger</param> /// <param name="loggerError">TODO: convert to static logger</param> /// <param name="SiteGroups">Collection of provisioned SharePoint group for field definitions</param> /// <param name="JsonFilePath">(OPTIONAL) file path to JSON folder</param> public static void CreateListFromDefinition(this Web web, SPListDefinition listDef, Action <string, string[]> loggerVerbose, Action <string, string[]> loggerWarning, Action <Exception, string, string[]> loggerError, List <SPGroupDefinitionModel> SiteGroups = null, string JsonFilePath = null) { var webContext = web.Context; var siteColumns = new List <SPFieldDefinitionModel>(); var afterProvisionChanges = false; // Content Type var listName = listDef.ListName; var listDescription = listDef.ListDescription; // check to see if Picture library named Photos already exists ListCollection allLists = web.Lists; IEnumerable <List> foundLists = webContext.LoadQuery(allLists.Where(list => list.Title == listName) .Include(arl => arl.Title, arl => arl.Id, arl => arl.ContentTypes, ol => ol.RootFolder, ol => ol.EnableVersioning, ol => ol.EnableFolderCreation, ol => ol.ContentTypesEnabled)); webContext.ExecuteQueryRetry(); List listToProvision = foundLists.FirstOrDefault(); if (listToProvision == null) { ListCreationInformation listToProvisionInfo = listDef.ToCreationObject(); listToProvision = web.Lists.Add(listToProvisionInfo); webContext.Load(listToProvision, arl => arl.Title, arl => arl.Id, arl => arl.ContentTypes, ol => ol.RootFolder, ol => ol.EnableVersioning, ol => ol.EnableFolderCreation, ol => ol.ContentTypesEnabled); webContext.ExecuteQuery(); } if (listDef.Versioning && !listToProvision.EnableVersioning) { afterProvisionChanges = true; listToProvision.EnableVersioning = true; if (listDef.ListTemplate == ListTemplateType.DocumentLibrary) { listToProvision.EnableMinorVersions = true; } } if (listDef.ContentTypeEnabled && !listToProvision.ContentTypesEnabled) { afterProvisionChanges = true; listToProvision.ContentTypesEnabled = true; } if (listDef.EnableFolderCreation && !listToProvision.EnableFolderCreation) { afterProvisionChanges = true; listToProvision.EnableFolderCreation = true; } if (afterProvisionChanges) { listToProvision.Update(); webContext.Load(listToProvision); webContext.ExecuteQueryRetry(); } webContext.Load(listToProvision, arl => arl.Title, arl => arl.Id, arl => arl.ContentTypes, ol => ol.RootFolder, ol => ol.EnableVersioning, ol => ol.EnableFolderCreation, ol => ol.ContentTypesEnabled); webContext.ExecuteQuery(); if (listDef.ContentTypeEnabled && listDef.HasContentTypes) { foreach (var contentDef in listDef.ContentTypes) { if (!listToProvision.ContentTypeExistsByName(contentDef.Name)) { var ctypeInfo = contentDef.ToCreationObject(); var accessContentType = listToProvision.ContentTypes.Add(ctypeInfo); listToProvision.Update(); webContext.Load(accessContentType, tycp => tycp.Id, tycp => tycp.Name); webContext.ExecuteQueryRetry(); if (contentDef.DefaultContentType) { listToProvision.SetDefaultContentTypeToList(accessContentType); } } } } // Site Columns foreach (var fieldDef in listDef.FieldDefinitions) { var column = listToProvision.CreateListColumn(fieldDef, loggerVerbose, loggerWarning, SiteGroups, JsonFilePath); if (column == null) { loggerWarning("Failed to create column {0}.", new string[] { fieldDef.InternalName }); } else { siteColumns.Add(new SPFieldDefinitionModel() { InternalName = column.InternalName, DisplayName = column.Title, FieldGuid = column.Id }); } } if (listDef.ContentTypeEnabled && listDef.HasContentTypes) { foreach (var contentDef in listDef.ContentTypes) { var contentTypeName = contentDef.Name; var accessContentTypes = listToProvision.ContentTypes; IEnumerable <ContentType> allContentTypes = webContext.LoadQuery(accessContentTypes.Where(f => f.Name == contentTypeName).Include(tcyp => tcyp.Id, tcyp => tcyp.Name)); webContext.ExecuteQueryRetry(); if (allContentTypes != null) { var accessContentType = allContentTypes.FirstOrDefault(); foreach (var fieldInternalName in contentDef.FieldLinkRefs) { var column = siteColumns.FirstOrDefault(f => f.InternalName == fieldInternalName); if (column != null) { var fieldLinks = accessContentType.FieldLinks; webContext.Load(fieldLinks, cf => cf.Include(inc => inc.Id, inc => inc.Name)); webContext.ExecuteQueryRetry(); var convertedInternalName = column.DisplayNameMasked; if (!fieldLinks.Any(a => a.Name == column.InternalName || a.Name == convertedInternalName)) { loggerVerbose("Content Type {0} Adding Field {1}", new string[] { contentTypeName, column.InternalName }); var siteColumn = listToProvision.GetFieldById <Field>(column.FieldGuid); webContext.ExecuteQueryRetry(); var flink = new FieldLinkCreationInformation(); flink.Field = siteColumn; var flinkstub = accessContentType.FieldLinks.Add(flink); //if(fieldDef.Required) flinkstub.Required = fieldDef.Required; accessContentType.Update(false); webContext.ExecuteQueryRetry(); } } else { loggerWarning("Failed to create column {0}.", new string[] { fieldInternalName }); } } } } } // Views if (listDef.Views != null && listDef.Views.Count() > 0) { ViewCollection views = listToProvision.Views; webContext.Load(views, f => f.Include(inc => inc.Id, inc => inc.Hidden, inc => inc.Title, inc => inc.DefaultView)); webContext.ExecuteQueryRetry(); foreach (var viewDef in listDef.Views) { try { if (views.Any(v => v.Title.Equals(viewDef.Title, StringComparison.CurrentCultureIgnoreCase))) { loggerVerbose("View {0} found in list {1}", new string[] { viewDef.Title, listName }); continue; } var view = listToProvision.CreateView(viewDef.InternalName, viewDef.ViewCamlType, viewDef.FieldRefName, viewDef.RowLimit, viewDef.DefaultView, viewDef.QueryXml, viewDef.PersonalView, viewDef.PagedView); webContext.Load(view, v => v.Title, v => v.Id, v => v.ServerRelativeUrl); webContext.ExecuteQueryRetry(); view.Title = viewDef.Title; if (viewDef.HasJsLink) { view.JSLink = viewDef.JsLink; } view.Update(); webContext.ExecuteQueryRetry(); } catch (Exception ex) { loggerError(ex, "Failed to create view {0} with XML:{1}", new string[] { viewDef.Title, viewDef.QueryXml }); } } } // List Data upload if (listDef.ListItems != null && listDef.ListItems.Count() > 0) { foreach (var listItem in listDef.ListItems) { // Process the record into the notification email list var itemCreateInfo = new ListItemCreationInformation(); var newSPListItem = listToProvision.AddItem(itemCreateInfo); newSPListItem["Title"] = listItem.Title; foreach (var listItemData in listItem.ColumnValues) { newSPListItem[listItemData.FieldName] = listItemData.FieldValue; } newSPListItem.Update(); webContext.ExecuteQueryRetry(); } } }
public override void DeployModel(object modelHost, DefinitionBase model) { var webModelHost = modelHost.WithAssertAndCast <WebModelHost>("modelHost", value => value.RequireNotNull()); var web = webModelHost.HostWeb; var listModel = model.WithAssertAndCast <ListDefinition>("model", value => value.RequireNotNull()); var context = web.Context; context.Load(web, w => w.ServerRelativeUrl); context.ExecuteQueryWithTrace(); List currentList = null; var loadedList = LoadCurrentList(web, listModel); if (loadedList != null) { currentList = loadedList; } InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = null, ObjectType = typeof(List), ObjectDefinition = model, ModelHost = modelHost }); // gosh! //currentList = FindListByUrl(lists, listModel.GetListUrl()); if (currentList == null) { TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new list"); // no support for the TemplateName yet var listInfo = new ListCreationInformation { Title = listModel.Title, Description = listModel.Description ?? string.Empty, #pragma warning disable 618 Url = listModel.GetListUrl() #pragma warning restore 618 }; if (listModel.TemplateType > 0) { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Creating list by TemplateType: [{0}]", listModel.TemplateType); listInfo.TemplateType = listModel.TemplateType; } else if (!string.IsNullOrEmpty(listModel.TemplateName)) { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Creating list by TemplateName: [{0}]", listModel.TemplateName); var listTemplate = ResolveListTemplate(webModelHost, listModel); listInfo.TemplateFeatureId = listTemplate.FeatureId; listInfo.TemplateType = listTemplate.ListTemplateTypeKind; } else { TraceService.Error((int)LogEventId.ModelProvisionCoreCall, "Either TemplateType or TemplateName has to be specified. Throwing SPMeta2Exception"); throw new SPMeta2Exception("Either TemplateType or TemplateName has to be specified."); } var newList = web.Lists.Add(listInfo); currentList = newList; currentList.Update(); context.ExecuteQueryWithTrace(); currentList = LoadCurrentList(web, listModel); } else { TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing list"); } MapListProperties(modelHost, currentList, listModel); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentList, ObjectType = typeof(List), ObjectDefinition = model, ModelHost = modelHost }); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling currentList.Update()"); currentList.Update(); context.ExecuteQueryWithTrace(); }
private Tuple<List, TokenParser> CreateList(Web web, ListInstance list, TokenParser parser, PnPMonitoredScope scope, bool isNoScriptSite = false) { List createdList; if (list.Url.Equals("SiteAssets") && list.TemplateType == (int)ListTemplateType.DocumentLibrary) { //Ensure that the Site Assets library is created using the out of the box creation mechanism //Site Assets that are created using the EnsureSiteAssetsLibrary method slightly differ from //default Document Libraries. See issue 512 (https://github.com/OfficeDev/PnP-Sites-Core/issues/512) //for details about the issue fixed by this approach. createdList = web.Lists.EnsureSiteAssetsLibrary(); //Check that Title and Description have the correct values web.Context.Load(createdList, l => l.Title, l => l.Description); web.Context.ExecuteQueryRetry(); var isDirty = false; if (!string.Equals(createdList.Description, list.Description)) { createdList.Description = list.Description; isDirty = true; } if (!string.Equals(createdList.Title, list.Title)) { createdList.Title = list.Title; isDirty = true; } if (isDirty) { createdList.Update(); web.Context.ExecuteQueryRetry(); } } else { var listCreate = new ListCreationInformation(); listCreate.Description = list.Description; listCreate.TemplateType = list.TemplateType; listCreate.Title = parser.ParseString(list.Title); // the line of code below doesn't add the list to QuickLaunch // the OnQuickLaunch property is re-set on the Created List object listCreate.QuickLaunchOption = list.OnQuickLaunch ? QuickLaunchOptions.On : QuickLaunchOptions.Off; listCreate.Url = parser.ParseString(list.Url); listCreate.TemplateFeatureId = list.TemplateFeatureID; createdList = web.Lists.Add(listCreate); createdList.Update(); } web.Context.Load(createdList, l => l.BaseTemplate); web.Context.ExecuteQueryRetry(); #if !SP2013 if (list.Title.ContainsResourceToken()) { createdList.TitleResource.SetUserResourceValue(list.Title, parser); } if (list.Description.ContainsResourceToken()) { createdList.DescriptionResource.SetUserResourceValue(list.Description, parser); } #endif if (!String.IsNullOrEmpty(list.DocumentTemplate)) { createdList.DocumentTemplateUrl = parser.ParseString(list.DocumentTemplate); } // EnableAttachments are not supported for DocumentLibraries, Survey and PictureLibraries // TODO: the user should be warned if (createdList.BaseTemplate != (int)ListTemplateType.DocumentLibrary && createdList.BaseTemplate != (int)ListTemplateType.Survey && createdList.BaseTemplate != (int)ListTemplateType.PictureLibrary) { createdList.EnableAttachments = list.EnableAttachments; } createdList.EnableModeration = list.EnableModeration; createdList.ForceCheckout = list.ForceCheckout; // Done for all other lists than for Survey - With Surveys versioning configuration will cause an exception if (createdList.BaseTemplate != (int)ListTemplateType.Survey) { createdList.EnableVersioning = list.EnableVersioning; if (list.EnableVersioning) { #if !SP2013 createdList.MajorVersionLimit = list.MaxVersionLimit; #endif // DraftVisibilityType.Approver is available only when the EnableModeration option of the list is true if (DraftVisibilityType.Approver == (DraftVisibilityType)list.DraftVersionVisibility) { if (list.EnableModeration) { createdList.DraftVersionVisibility = (DraftVisibilityType)list.DraftVersionVisibility; } else { scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ListInstances_DraftVersionVisibility_not_applied_because_EnableModeration_is_not_set_to_true); WriteWarning(CoreResources.Provisioning_ObjectHandlers_ListInstances_DraftVersionVisibility_not_applied_because_EnableModeration_is_not_set_to_true, ProvisioningMessageType.Warning); } } else { createdList.DraftVersionVisibility = (DraftVisibilityType)list.DraftVersionVisibility; } if (createdList.BaseTemplate == (int)ListTemplateType.DocumentLibrary) { // Only supported on Document Libraries createdList.EnableMinorVersions = list.EnableMinorVersions; createdList.DraftVersionVisibility = (DraftVisibilityType)list.DraftVersionVisibility; if (list.EnableMinorVersions) { createdList.MajorWithMinorVersionsLimit = list.MinorVersionLimit; // Set only if enabled, otherwise you'll get exception due setting value to zero. } } } } createdList.OnQuickLaunch = list.OnQuickLaunch; if (createdList.BaseTemplate != (int)ListTemplateType.DiscussionBoard && createdList.BaseTemplate != (int)ListTemplateType.Events) { createdList.EnableFolderCreation = list.EnableFolderCreation; } createdList.Hidden = list.Hidden; if (createdList.BaseTemplate != (int)ListTemplateType.Survey) { createdList.ContentTypesEnabled = list.ContentTypesEnabled; } createdList.Update(); web.Context.Load(createdList.Views); web.Context.Load(createdList, l => l.Id); web.Context.Load(createdList, l => l.RootFolder.ServerRelativeUrl); web.Context.Load(createdList.ContentTypes); web.Context.ExecuteQueryRetry(); if (createdList.BaseTemplate != (int)ListTemplateType.Survey) { // Remove existing content types only if there are custom content type bindings var contentTypesToRemove = new List<ContentType>(); if (list.RemoveExistingContentTypes && list.ContentTypeBindings.Count > 0) { contentTypesToRemove.AddRange(createdList.ContentTypes); } ContentTypeBinding defaultCtBinding = null; foreach (var ctBinding in list.ContentTypeBindings) { var tempCT = web.GetContentTypeById(ctBinding.ContentTypeId, searchInSiteHierarchy: true); if (tempCT != null) { // Get the name of the existing CT var name = tempCT.EnsureProperty(ct => ct.Name); // If the CT does not exist in the target list, and we don't have to remove it if (!createdList.ContentTypeExistsByName(name) && !ctBinding.Remove) { // Then add it to the target list createdList.AddContentTypeToListById(ctBinding.ContentTypeId, searchContentTypeInSiteHierarchy: true); } // Else if the CT exists in the target list, and we have to remove it else if (createdList.ContentTypeExistsByName(name) && ctBinding.Remove) { // Then remove it from the target list createdList.RemoveContentTypeByName(name); } if (ctBinding.Default) { defaultCtBinding = ctBinding; } } } // default ContentTypeBinding should be set last because // list extension .SetDefaultContentTypeToList() re-sets // the list.RootFolder UniqueContentTypeOrder property // which may cause missing CTs from the "New Button" if (defaultCtBinding != null) { createdList.SetDefaultContentTypeToList(defaultCtBinding.ContentTypeId); } // Effectively remove existing content types, if any foreach (var ct in contentTypesToRemove) { var shouldDelete = true; shouldDelete &= (createdList.BaseTemplate != (int)ListTemplateType.DocumentLibrary || !ct.StringId.StartsWith(BuiltInContentTypeId.Folder + "00")); if (shouldDelete) { ct.DeleteObject(); web.Context.ExecuteQueryRetry(); } } } // Add any custom action if (list.UserCustomActions.Any()) { if (!isNoScriptSite) { foreach (var userCustomAction in list.UserCustomActions) { CreateListCustomAction(createdList, parser, userCustomAction); } web.Context.ExecuteQueryRetry(); } else { scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ListInstances_SkipAddingOrUpdatingCustomActions); } } if (list.Security != null) { createdList.SetSecurity(parser, list.Security); } return Tuple.Create(createdList, parser); }
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); }
protected override void DeployModelInternal(object modelHost, DefinitionBase model) { var webModelHost = modelHost.WithAssertAndCast<WebModelHost>("modelHost", value => value.RequireNotNull()); var web = webModelHost.HostWeb; var listModel = model.WithAssertAndCast<ListDefinition>("model", value => value.RequireNotNull()); var context = web.Context; context.Load(web, w => w.Lists); context.Load(web, w => w.ServerRelativeUrl); context.ExecuteQuery(); List currentList = null; InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = null, ObjectType = typeof(List), ObjectDefinition = model, ModelHost = modelHost }); InvokeOnModelEvent<ListDefinition, List>(currentList, ModelEventType.OnUpdating); // gosh! currentList = FindListByTitle(web.Lists, listModel.Title); if (currentList == null) { // no support for the TemplateName yet var listInfo = new ListCreationInformation { Title = listModel.Title, Description = listModel.Description ?? string.Empty, Url = listModel.GetListUrl() }; if (listModel.TemplateType > 0) { listInfo.TemplateType = listModel.TemplateType; } else if (!string.IsNullOrEmpty(listModel.TemplateName)) { context.Load(web, tmpWeb => tmpWeb.ListTemplates); context.ExecuteQuery(); // gosh.. var listTemplate = FindListTemplateByName(web.ListTemplates, listModel.TemplateName); listInfo.TemplateFeatureId = listTemplate.FeatureId; listInfo.TemplateType = listTemplate.ListTemplateTypeKind; } else { throw new ArgumentException("Either TemplateType or TemplateName has to bbe specified."); } currentList = web.Lists.Add(listInfo); } currentList.Title = listModel.Title; currentList.Description = listModel.Description ?? string.Empty; currentList.ContentTypesEnabled = listModel.ContentTypesEnabled; InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentList, ObjectType = typeof(List), ObjectDefinition = model, ModelHost = modelHost }); InvokeOnModelEvent<ListDefinition, List>(currentList, ModelEventType.OnUpdated); currentList.Update(); context.ExecuteQuery(); }
static void CreateProductsList() { Console.WriteLine("Creating Products list..."); ListCreationInformation listInformationProducts = new ListCreationInformation(); listInformationProducts.Title = "Products"; listInformationProducts.Url = "Lists/Products"; listInformationProducts.QuickLaunchOption = QuickLaunchOptions.On; listInformationProducts.TemplateType = (int)ListTemplateType.GenericList; listProducts = site.Lists.Add(listInformationProducts); listProducts.OnQuickLaunch = true; listProducts.Update(); clientContext.Load(listProducts); clientContext.Load(listProducts.ContentTypes); clientContext.ExecuteQuery(); listProducts.ContentTypesEnabled = true; listProducts.ContentTypes.AddExistingContentType(ctypeProduct); ContentType existing = listProducts.ContentTypes[0];; existing.DeleteObject(); listProducts.Update(); clientContext.ExecuteQuery(); View viewProducts = listProducts.DefaultView; viewProducts.ViewFields.Add("ProductCode"); viewProducts.ViewFields.Add("ProductListPrice"); viewProducts.ViewFields.Add("ProductColor"); viewProducts.Update(); clientContext.ExecuteQuery(); string fieldXML = @"<Field Type=""Calculated"" Name=""AgeRange"" DisplayName=""Age Range"" EnforceUniqueValues=""FALSE"" Indexed=""FALSE"" ResultType=""Text"" > <Formula>=IF(AND(ISBLANK([Minimum Age]),ISBLANK([Maximum Age])),"All ages",IF(ISBLANK([Maximum Age]),"Ages "&[Minimum Age]&" and older",IF(ISBLANK([Minimum Age]),"Ages "&[Maximum Age]&" and younger","Ages "&[Minimum Age]&" to "&[Maximum Age])))</Formula> <FieldRefs> <FieldRef Name=""MinimumAge""/> <FieldRef Name=""MaximumAge""/> </FieldRefs> </Field>"; listProducts.Fields.AddFieldAsXml(fieldXML, true, AddFieldOptions.DefaultValue); clientContext.ExecuteQuery(); viewProducts.Update(); clientContext.ExecuteQuery(); viewProducts.ViewFields.Add("ProductDescription"); viewProducts.ViewFields.Add("ProductImageUrl"); viewProducts.Update(); clientContext.ExecuteQuery(); }
public static void ListRemoteEventReceiver(SPRemoteEventProperties properties) { // This code works only if OAuth on the server that's running SharePoint is set up with an ACS token. // Code that works with S2S setup is similar, but some changes are required. string logListTitle = "EventLog"; // Return if the event is from the EventLog list. Otherwise, it may go into an infinite loop. if (string.Equals(properties.ItemEventProperties.ListTitle, logListTitle, StringComparison.OrdinalIgnoreCase)) { return; } // Get the token from the request header. HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)OperationContext.Current.IncomingMessageProperties[HttpRequestMessageProperty.Name]; string contextTokenString = requestProperty.Headers["X-SP-ContextToken"]; // If there is a valid token, continue. if (contextTokenString != null) { SharePointContextToken contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, requestProperty.Headers[HttpRequestHeader.Host]); Uri sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); string accessToken = TokenHelper.GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; bool exists = false; // Retrieve the log list "EventLog" and add the name of the event that occurred to it with a date/time stamp. using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken)) { clientContext.Load(clientContext.Web); clientContext.ExecuteQuery(); List logList = clientContext.Web.Lists.GetByTitle(logListTitle); try { clientContext.Load(logList); clientContext.ExecuteQuery(); exists = true; } catch (Microsoft.SharePoint.Client.ServerUnauthorizedAccessException) { // If the user doesn't have permissions to access the server that's running SharePoint, return. return; } catch (Microsoft.SharePoint.Client.ServerException) { // If an error occurs on the server that's running SharePoint, return. exists = false; } // Create a log list called "EventLog" if it doesn't already exist. if (!exists) { ListCreationInformation listInfo = new ListCreationInformation(); listInfo.Title = logListTitle; // Create a generic custom list. listInfo.TemplateType = 100; clientContext.Web.Lists.Add(listInfo); clientContext.Web.Context.ExecuteQuery(); } // Add the event entry to the EventLog list. string itemTitle = "Event: " + properties.EventType.ToString() + " occurred on: " + DateTime.Now.ToString(" yyyy/MM/dd/HH:mm:ss:fffffff"); ListCollection lists = clientContext.Web.Lists; List selectedList = lists.GetByTitle(logListTitle); clientContext.Load <ListCollection>(lists); clientContext.Load <List>(selectedList); ListItemCreationInformation listItemCreationInfo = new ListItemCreationInformation(); var listItem = selectedList.AddItem(listItemCreationInfo); listItem["Title"] = itemTitle; listItem.Update(); clientContext.ExecuteQuery(); } } }
public void ReorderContentTypesTest() { using (var clientContext = TestCommon.CreateClientContext()) { var web = clientContext.Web; clientContext.Load(web, w => w.ContentTypes); clientContext.ExecuteQuery(); // create content types var documentCtype = web.ContentTypes.FirstOrDefault(ct => ct.Name == "Document"); var newCtypeInfo1 = new ContentTypeCreationInformation() { Name = "Test_ContentType1", ParentContentType = documentCtype, Group = "Test content types", Description = "This is a test content type" }; var newCtypeInfo2 = new ContentTypeCreationInformation() { Name = "Test_ContentType2", ParentContentType = documentCtype, Group = "Test content types", Description = "This is a test content type" }; var newCtypeInfo3 = new ContentTypeCreationInformation() { Name = "Test_ContentType3", ParentContentType = documentCtype, Group = "Test content types", Description = "This is a test content type" }; var newCtype1 = web.ContentTypes.Add(newCtypeInfo1); var newCtype2 = web.ContentTypes.Add(newCtypeInfo2); var newCtype3 = web.ContentTypes.Add(newCtypeInfo3); clientContext.Load(newCtype1); clientContext.Load(newCtype2); clientContext.Load(newCtype3); clientContext.ExecuteQuery(); var newList = new ListCreationInformation() { TemplateType = (int)ListTemplateType.DocumentLibrary, Title = DOC_LIB_TITLE, Url = "TestLibrary" }; var doclib = clientContext.Web.Lists.Add(newList); doclib.ContentTypesEnabled = true; doclib.ContentTypes.AddExistingContentType(newCtype1); doclib.ContentTypes.AddExistingContentType(newCtype2); doclib.ContentTypes.AddExistingContentType(newCtype3); doclib.Update(); clientContext.Load(doclib.ContentTypes); clientContext.ExecuteQuery(); var expectedIds = new string[] { newCtype3.Name, newCtype1.Name, newCtype2.Name, documentCtype.Name }; doclib.ReorderContentTypes(expectedIds); var reorderedCtypes = clientContext.LoadQuery(doclib.ContentTypes); clientContext.ExecuteQuery(); var actualIds = reorderedCtypes.Except( // remove the folder content type reorderedCtypes.Where(ct => ct.Id.StringValue.StartsWith("0x012000")) ).Select(ct => ct.Name).ToArray(); CollectionAssert.AreEqual(expectedIds, actualIds); } }
void ProvisionSample3(Web web) { //Delete list if it already exists ListCollection lists = web.Lists; IEnumerable <List> results = web.Context.LoadQuery <List>(lists.Where(list => list.Title == "CSR-Confidential-Documents")); web.Context.ExecuteQuery(); List existingList = results.FirstOrDefault(); if (existingList != null) { existingList.DeleteObject(); web.Context.ExecuteQuery(); } //Create list ListCreationInformation creationInfo = new ListCreationInformation(); creationInfo.Title = "CSR-Confidential-Documents"; creationInfo.TemplateType = (int)ListTemplateType.DocumentLibrary; List newlist = web.Lists.Add(creationInfo); newlist.Update(); web.Context.Load(newlist); web.Context.Load(newlist.Fields); web.Context.ExecuteQuery(); //Add field FieldCollection fields = web.Fields; web.Context.Load(fields, fc => fc.Include(f => f.InternalName)); web.Context.ExecuteQuery(); Field field = fields.FirstOrDefault(f => f.InternalName == "Confidential"); if (field == null) { field = newlist.Fields.AddFieldAsXml("<Field Type=\"YES/NO\" Name=\"Confidential\" DisplayName=\"Confidential\" ID=\"" + Guid.NewGuid() + "\" Group=\"CSR Samples\" />", false, AddFieldOptions.DefaultValue); web.Update(); web.Context.ExecuteQuery(); } newlist.Fields.Add(field); newlist.Update(); web.Context.ExecuteQuery(); //Upload sample docs UploadTempDoc(newlist, "Doc1.doc"); UploadTempDoc(newlist, "Doc2.doc"); UploadTempDoc(newlist, "Doc3.ppt"); UploadTempDoc(newlist, "Doc4.ppt"); UploadTempDoc(newlist, "Doc5.xls"); UploadTempDoc(newlist, "Doc6.xls"); Microsoft.SharePoint.Client.ListItem item1 = newlist.GetItemById(1); item1["Confidential"] = 1; item1.Update(); Microsoft.SharePoint.Client.ListItem item2 = newlist.GetItemById(2); item2["Confidential"] = 1; item2.Update(); Microsoft.SharePoint.Client.ListItem item3 = newlist.GetItemById(3); item3["Confidential"] = 0; item3.Update(); Microsoft.SharePoint.Client.ListItem item4 = newlist.GetItemById(4); item4["Confidential"] = 1; item4.Update(); Microsoft.SharePoint.Client.ListItem item5 = newlist.GetItemById(5); item5["Confidential"] = 0; item5.Update(); Microsoft.SharePoint.Client.ListItem item6 = newlist.GetItemById(6); item6["Confidential"] = 1; item6.Update(); web.Context.ExecuteQuery(); //Create sample view ViewCreationInformation sampleViewCreateInfo = new ViewCreationInformation(); sampleViewCreateInfo.Title = "CSR Sample View"; sampleViewCreateInfo.ViewFields = new string[] { "DocIcon", "LinkFilename", "Modified", "Editor", "Confidential" }; sampleViewCreateInfo.SetAsDefaultView = true; Microsoft.SharePoint.Client.View sampleView = newlist.Views.Add(sampleViewCreateInfo); sampleView.Update(); web.Context.Load(newlist, l => l.DefaultViewUrl); web.Context.ExecuteQuery(); //Register JS files via JSLink properties RegisterJStoWebPart(web, newlist.DefaultViewUrl, "~sitecollection/Style Library/JSLink-Samples/ConfidentialDocuments.js"); }
public override void DeployModel(object modelHost, DefinitionBase model) { var webModelHost = modelHost.WithAssertAndCast<WebModelHost>("modelHost", value => value.RequireNotNull()); var web = webModelHost.HostWeb; var listModel = model.WithAssertAndCast<ListDefinition>("model", value => value.RequireNotNull()); var context = web.Context; context.Load(web, w => w.ServerRelativeUrl); context.ExecuteQueryWithTrace(); List currentList = null; var loadedList = LoadCurrentList(web, listModel); if (loadedList != null) currentList = loadedList; InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = null, ObjectType = typeof(List), ObjectDefinition = model, ModelHost = modelHost }); InvokeOnModelEvent<ListDefinition, List>(currentList, ModelEventType.OnUpdating); // gosh! //currentList = FindListByUrl(lists, listModel.GetListUrl()); if (currentList == null) { TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new list"); // no support for the TemplateName yet var listInfo = new ListCreationInformation { Title = listModel.Title, Description = listModel.Description ?? string.Empty, Url = listModel.GetListUrl() }; if (listModel.TemplateType > 0) { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Creating list by TemplateType: [{0}]", listModel.TemplateType); listInfo.TemplateType = listModel.TemplateType; } else if (!string.IsNullOrEmpty(listModel.TemplateName)) { TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Creating list by TemplateName: [{0}]", listModel.TemplateName); var listTemplate = ResolveListTemplate(webModelHost, listModel); listInfo.TemplateFeatureId = listTemplate.FeatureId; listInfo.TemplateType = listTemplate.ListTemplateTypeKind; } else { TraceService.Error((int)LogEventId.ModelProvisionCoreCall, "Either TemplateType or TemplateName has to be specified. Throwing SPMeta2Exception"); throw new SPMeta2Exception("Either TemplateType or TemplateName has to be specified."); } var newList = web.Lists.Add(listInfo); currentList = newList; currentList.Update(); context.ExecuteQueryWithTrace(); currentList = LoadCurrentList(web, listModel); } else { TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing list"); } MapListProperties(currentList, listModel); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentList, ObjectType = typeof(List), ObjectDefinition = model, ModelHost = modelHost }); InvokeOnModelEvent<ListDefinition, List>(currentList, ModelEventType.OnUpdated); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling currentList.Update()"); currentList.Update(); context.ExecuteQueryWithTrace(); }
void ProvisionSample4(Web web) { //Delete list if it already exists ListCollection lists = web.Lists; IEnumerable <List> results = web.Context.LoadQuery <List>(lists.Where(list => list.Title == "CSR-Tasks-Percent-Complete")); web.Context.ExecuteQuery(); List existingList = results.FirstOrDefault(); if (existingList != null) { existingList.DeleteObject(); web.Context.ExecuteQuery(); } //Create list ListCreationInformation creationInfo = new ListCreationInformation(); creationInfo.Title = "CSR-Tasks-Percent-Complete"; creationInfo.TemplateType = (int)ListTemplateType.Tasks; List newlist = web.Lists.Add(creationInfo); newlist.Update(); web.Context.Load(newlist); web.Context.ExecuteQuery(); //Add items Microsoft.SharePoint.Client.ListItem item1 = newlist.AddItem(new ListItemCreationInformation()); item1["Title"] = "Task 1"; item1["StartDate"] = "2014-1-1"; item1["DueDate"] = "2014-2-1"; item1["PercentComplete"] = "0.59"; item1.Update(); Microsoft.SharePoint.Client.ListItem item2 = newlist.AddItem(new ListItemCreationInformation()); item2["Title"] = "Task 2"; item2["StartDate"] = "2014-1-1"; item2["DueDate"] = "2014-2-1"; item2["PercentComplete"] = "0.40"; item2.Update(); Microsoft.SharePoint.Client.ListItem item3 = newlist.AddItem(new ListItemCreationInformation()); item3["Title"] = "Task 3"; item3["StartDate"] = "2014-1-1"; item3["DueDate"] = "2014-2-1"; item3["PercentComplete"] = "1.0"; item3.Update(); Microsoft.SharePoint.Client.ListItem item4 = newlist.AddItem(new ListItemCreationInformation()); item4["Title"] = "Task 4"; item4["StartDate"] = "2014-1-1"; item4["DueDate"] = "2014-2-1"; item4["PercentComplete"] = "0.26"; item4.Update(); Microsoft.SharePoint.Client.ListItem item5 = newlist.AddItem(new ListItemCreationInformation()); item5["Title"] = "Task 5"; item5["StartDate"] = "2014-1-1"; item5["DueDate"] = "2014-2-1"; item5["PercentComplete"] = "0.50"; item5.Update(); //Create sample view ViewCreationInformation sampleViewCreateInfo = new ViewCreationInformation(); sampleViewCreateInfo.Title = "CSR Sample View"; sampleViewCreateInfo.ViewFields = new string[] { "DocIcon", "LinkTitle", "DueDate", "AssignedTo", "PercentComplete" }; sampleViewCreateInfo.SetAsDefaultView = true; Microsoft.SharePoint.Client.View sampleView = newlist.Views.Add(sampleViewCreateInfo); sampleView.Update(); web.Context.Load(newlist, l => l.DefaultViewUrl, l => l.DefaultDisplayFormUrl, l => l.DefaultEditFormUrl, l => l.DefaultNewFormUrl); web.Context.ExecuteQuery(); //Register JS files via JSLink properties RegisterJStoWebPart(web, newlist.DefaultViewUrl, "~sitecollection/Style Library/JSLink-Samples/PercentComplete.js"); RegisterJStoWebPart(web, newlist.DefaultDisplayFormUrl, "~sitecollection/Style Library/JSLink-Samples/PercentComplete.js"); RegisterJStoWebPart(web, newlist.DefaultEditFormUrl, "~sitecollection/Style Library/JSLink-Samples/PercentComplete.js"); RegisterJStoWebPart(web, newlist.DefaultNewFormUrl, "~sitecollection/Style Library/JSLink-Samples/PercentComplete.js"); }
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(); }
void ProvisionSample5(Web web) { //Delete list if it already exists ListCollection lists = web.Lists; IEnumerable <List> results = web.Context.LoadQuery <List>(lists.Where(list => list.Title == "CSR-Accordion")); web.Context.ExecuteQuery(); List existingList = results.FirstOrDefault(); if (existingList != null) { existingList.DeleteObject(); web.Context.ExecuteQuery(); } //Create list ListCreationInformation creationInfo = new ListCreationInformation(); creationInfo.Title = "CSR-Accordion"; creationInfo.TemplateType = (int)ListTemplateType.GenericList; List newlist = web.Lists.Add(creationInfo); newlist.Update(); web.Context.Load(newlist); web.Context.ExecuteQuery(); //Add field newlist.Fields.AddFieldAsXml("<Field Type=\"" + FieldType.Note + "\" Name=\"Description\" DisplayName=\"Description\" ID=\"" + Guid.NewGuid() + "\" Group=\"CSR Samples\" />", false, AddFieldOptions.DefaultValue); newlist.Update(); web.Context.ExecuteQuery(); //Add items Microsoft.SharePoint.Client.ListItem item1 = newlist.AddItem(new ListItemCreationInformation()); item1["Title"] = "Accordion Item 1"; item1["Description"] = "Accordian description 1."; item1.Update(); Microsoft.SharePoint.Client.ListItem item2 = newlist.AddItem(new ListItemCreationInformation()); item2["Title"] = "Accordion Item 2"; item2["Description"] = "Accordian description 2. "; item2.Update(); Microsoft.SharePoint.Client.ListItem item3 = newlist.AddItem(new ListItemCreationInformation()); item3["Title"] = "Accordion Item 3"; item3["Description"] = "Accordian description 3."; item3.Update(); web.Context.ExecuteQuery(); //Create sample view ViewCreationInformation sampleViewCreateInfo = new ViewCreationInformation(); sampleViewCreateInfo.Title = "CSR Sample View"; sampleViewCreateInfo.ViewFields = new string[] { "LinkTitle", "Description" }; sampleViewCreateInfo.SetAsDefaultView = true; Microsoft.SharePoint.Client.View sampleView = newlist.Views.Add(sampleViewCreateInfo); sampleView.Update(); web.Context.Load(newlist, l => l.DefaultViewUrl); web.Context.ExecuteQuery(); //Register JS files via JSLink properties RegisterJStoWebPart(web, newlist.DefaultViewUrl, "~sitecollection/Style Library/JSLink-Samples/Accordion.js"); }