protected void SubmitButton_Click(object sender, EventArgs e) { try { List list = ViewAddEdit.isCtx.Web.Lists.GetByTitle(listtitle); // Get all the view for the custom list Microsoft.SharePoint.Client.ViewCollection viewColl = list.Views; List <string> SelectedValuesForCollectingUserId = new List <string>(); foreach (System.Web.UI.WebControls.ListItem item in FieldListBox.Items) { if (item.Selected) { SelectedValuesForCollectingUserId.Add(item.Value); } } //string[] viewFields = { "DocIcon", "LinkFilename", "_Author", "Modified", "Modified By" }; ViewCreationInformation creationInfo = new ViewCreationInformation(); creationInfo.Title = ViewTextBox.Text; creationInfo.RowLimit = 50; creationInfo.ViewFields = SelectedValuesForCollectingUserId.ToArray(); creationInfo.ViewTypeKind = ViewType.None; viewColl.Add(creationInfo); ViewAddEdit.isCtx.ExecuteQuery(); } catch (Exception ex) { Console.WriteLine("Exce :" + ex); } Response.Redirect("SiteContents.aspx"); }
/// <summary> /// Create view to existing list /// </summary> /// <param name="list"></param> /// <param name="viewName"></param> /// <param name="viewType"></param> /// <param name="viewFields"></param> /// <param name="rowLimit"></param> /// <param name="setAsDefault"></param> /// <param name="query"></param> /// <param name="personal"></param> public static void CreateListView(this List list, string viewName, ViewType viewType, string[] viewFields, uint rowLimit, bool setAsDefault, string query = null, bool personal = false) { if (string.IsNullOrEmpty(viewName)) { throw new ArgumentNullException("viewName"); } ViewCreationInformation viewCreationInformation = new ViewCreationInformation(); viewCreationInformation.Title = viewName; viewCreationInformation.ViewTypeKind = viewType; viewCreationInformation.RowLimit = rowLimit; viewCreationInformation.ViewFields = viewFields; viewCreationInformation.PersonalView = personal; viewCreationInformation.SetAsDefaultView = setAsDefault; if (!string.IsNullOrEmpty(query)) { viewCreationInformation.Query = query; } list.Views.Add(viewCreationInformation); list.Context.ExecuteQuery(); }
public static View CreateView(this List list, ViewCreationInformation viewCreationInformation) { View view = list.Views.Add(viewCreationInformation); list.Context.Load(view); list.Context.ExecuteQuery(); return(view); }
void ProvisionSample2(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-Substring-long-text")); web.Context.ExecuteQuery(); List existingList = results.FirstOrDefault(); if (existingList != null) { existingList.DeleteObject(); web.Context.ExecuteQuery(); } //Create list ListCreationInformation creationInfo = new ListCreationInformation(); creationInfo.Title = "CSR-Substring-long-text"; creationInfo.TemplateType = (int)ListTemplateType.Announcements; 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"] = "Announcement 1"; item1["Body"] = "Aaaaaa Bbbbbb Cccccc Dccccc Eeeeee Ffffff Gggggg Hhhhhh Iiiiii Jjjjjj Kkkkkk Llllll Mmmmmm Nnnnnn Oooooo Pppppp Qqqqqq Rrrrrr Ssssss Tttttt Uuuuuu Vvvvvv Wwwwww Xxxxx Yyyyyy Zzzzzz"; item1.Update(); Microsoft.SharePoint.Client.ListItem item2 = newlist.AddItem(new ListItemCreationInformation()); item2["Title"] = "Announcement 2"; item2["Body"] = "Aaaaaa Bbbbbb Cccccc Dccccc Eeeeee Ffffff Gggggg Hhhhhh Iiiiii Jjjjjj Kkkkkk Llllll Mmmmmm Nnnnnn Oooooo Pppppp Qqqqqq Rrrrrr Ssssss Tttttt Uuuuuu Vvvvvv Wwwwww Xxxxx Yyyyyy Zzzzzz"; item2.Update(); Microsoft.SharePoint.Client.ListItem item3 = newlist.AddItem(new ListItemCreationInformation()); item3["Title"] = "Announcement 3"; item3["Body"] = "Aaaaaa Bbbbbb Cccccc Dccccc Eeeeee Ffffff Gggggg Hhhhhh Iiiiii Jjjjjj Kkkkkk Llllll Mmmmmm Nnnnnn Oooooo Pppppp Qqqqqq Rrrrrr Ssssss Tttttt Uuuuuu Vvvvvv Wwwwww Xxxxx Yyyyyy Zzzzzz"; item3.Update(); //Create sample view ViewCreationInformation sampleViewCreateInfo = new ViewCreationInformation(); sampleViewCreateInfo.Title = "CSR Sample View"; sampleViewCreateInfo.ViewFields = new string[] { "Title", "Body" }; 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/SubstringLongText.js"); }
public void CreateListView(ClientContext clientContext, string documentLibName, string viewName) { if (null == clientContext) { throw new ArgumentNullException("clientContext"); } if (string.IsNullOrEmpty(documentLibName)) { throw new ArgumentNullException("documentLibName"); } if (string.IsNullOrEmpty(viewName)) { throw new ArgumentNullException("viewName"); } // See if we already have the document library. try { if (!ProcessDocumentLibrary(clientContext, documentLibName, list => { var viewCollection = list.Views; if (viewCollection.Count(v => v.Title == viewName) == 0) { string[] viewFields = { "Title", "FileLeafRef" }; var vci = new ViewCreationInformation { Title = viewName, RowLimit = 50, ViewFields = viewFields, ViewTypeKind = ViewType.None, SetAsDefaultView = false }; viewCollection.Add(vci); clientContext.ExecuteQuery(); if (null != CreatedView) { CreatedView(this, new EventArgs()); } } else { if (null != ViewExists) { ViewExists(this, new EventArgs()); } } })) { throw new Exception("Could not find document libarary " + documentLibName); } } catch (Exception ex) { Logger.LogError("Failed to create view {2} on document library {0}, details: {1}", documentLibName, ex.ToString(), viewName); } }
void ProvisionSample7(Web web) { //Delete list if it already exists ListCollection lists = web.Lists; web.Context.Load(web.CurrentUser, i => i.Id); IEnumerable <List> results = web.Context.LoadQuery <List>(lists.Where(list => list.Title == "CSR-Read-only-SP-Controls")); web.Context.ExecuteQuery(); List existingList = results.FirstOrDefault(); if (existingList != null) { existingList.DeleteObject(); web.Context.ExecuteQuery(); } //Create list ListCreationInformation creationInfo = new ListCreationInformation(); creationInfo.Title = "CSR-Read-only-SP-Controls"; 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["AssignedTo"] = new FieldLookupValue { LookupId = web.CurrentUser.Id }; item1.Update(); //Create sample view ViewCreationInformation sampleViewCreateInfo = new ViewCreationInformation(); sampleViewCreateInfo.Title = "CSR Sample View"; sampleViewCreateInfo.ViewFields = new string[] { "DocIcon", "LinkTitle", "DueDate", "AssignedTo" }; sampleViewCreateInfo.SetAsDefaultView = true; Microsoft.SharePoint.Client.View sampleView = newlist.Views.Add(sampleViewCreateInfo); sampleView.Update(); web.Context.Load(newlist, l => l.DefaultEditFormUrl); web.Context.ExecuteQuery(); //Register JS files via JSLink properties RegisterJStoWebPart(web, newlist.DefaultEditFormUrl, "~sitecollection/Style Library/JSLink-Samples/ReadOnlySPControls.js"); }
void ProvisionSample6(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-Email-Regex-Validator")); web.Context.ExecuteQuery(); List existingList = results.FirstOrDefault(); if (existingList != null) { existingList.DeleteObject(); web.Context.ExecuteQuery(); } //Create list ListCreationInformation creationInfo = new ListCreationInformation(); creationInfo.Title = "CSR-Email-Regex-Validator"; 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.Text + "\" Name=\"Email\" DisplayName=\"Email\" 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"] = "Email address"; item1["Email"] = "*****@*****.**"; item1.Update(); //Create sample view ViewCreationInformation sampleViewCreateInfo = new ViewCreationInformation(); sampleViewCreateInfo.Title = "CSR Sample View"; sampleViewCreateInfo.ViewFields = new string[] { "LinkTitle", "Email" }; sampleViewCreateInfo.SetAsDefaultView = true; Microsoft.SharePoint.Client.View sampleView = newlist.Views.Add(sampleViewCreateInfo); sampleView.Update(); web.Context.Load(newlist, l => l.DefaultNewFormUrl, l => l.DefaultEditFormUrl); web.Context.ExecuteQuery(); //Register JS files via JSLink properties RegisterJStoWebPart(web, newlist.DefaultNewFormUrl, "~sitecollection/Style Library/JSLink-Samples/RegexValidator.js"); RegisterJStoWebPart(web, newlist.DefaultEditFormUrl, "~sitecollection/Style Library/JSLink-Samples/RegexValidator.js"); }
public override void AddView(string viewName, IEnumerable <string> viewFields, string strQuery, uint rowLimit, bool paged, bool makeDefault) { var viewCreationInfo = new ViewCreationInformation(); viewCreationInfo.Title = viewName; viewCreationInfo.ViewFields = viewFields.ToArray(); viewCreationInfo.Paged = paged; viewCreationInfo.RowLimit = rowLimit; viewCreationInfo.Query = strQuery; viewCreationInfo.SetAsDefaultView = makeDefault; _list.Views.Add(viewCreationInfo); _context.ExecuteQuery(); }
public static void CreateView(ClientContext ctx) { List list = ctx.Web.GetListByTitle("CVs"); ViewCreationInformation info = new ViewCreationInformation(); info.ViewFields = new string[] { "title", "DAV_User", "DAV_Pic", "DAV_Active" }; info.Title = "Active CVs"; //Have to look on camlQuery more. info.Query = @"<Where><Eq><FieldRef Name='DAV_IsActive' /><Value Type='Integer'>1</Value></Eq></Where>"; list.Views.Add(info); list.Update(); ctx.ExecuteQuery(); }
public static View AddView(List list, string title, string camlQuery, string[] viewFields, ViewType viewType, uint rowLimit, bool personal, bool setAsDefault, ClientContext clientContext) { ViewCreationInformation vInfo = new ViewCreationInformation(); vInfo.Title = title; if (!string.IsNullOrEmpty(camlQuery)) vInfo.Query = camlQuery; vInfo.ViewFields = viewFields; vInfo.ViewTypeKind = viewType; vInfo.SetAsDefaultView = setAsDefault; vInfo.PersonalView = personal; vInfo.RowLimit = rowLimit; View view = list.Views.Add(vInfo); clientContext.Load(view, v => v.Id, v => v.ViewQuery, v => v.Title, v => v.ViewFields, v => v.ViewType, v => v.DefaultView, v => v.PersonalView, v => v.RowLimit); clientContext.ExecuteQuery(); return view; }
/// <summary> /// Create view to existing list /// </summary> /// <param name="list"></param> /// <param name="viewName"></param> /// <param name="viewType"></param> /// <param name="viewFields"></param> /// <param name="rowLimit"></param> /// <param name="setAsDefault"></param> /// <param name="query"></param> public static void CreateListView(this List list, string viewName, ViewType viewType, string[] viewFields, uint rowLimit, bool setAsDefault, string query = null) { ViewCreationInformation viewCreationInformation = new ViewCreationInformation(); viewCreationInformation.Title = viewName; viewCreationInformation.ViewTypeKind = viewType; viewCreationInformation.RowLimit = rowLimit; viewCreationInformation.ViewFields = viewFields; viewCreationInformation.SetAsDefaultView = setAsDefault; if (!string.IsNullOrEmpty(query)) { viewCreationInformation.Query = query; } list.Views.Add(viewCreationInformation); list.Context.ExecuteQuery(); }
private static void CreateMapView() { // Replace site URL and List Title with Valid values. ClientContext context = new ClientContext("<Site Url>"); List oList = context.Web.Lists.GetByTitle("<List Title>"); ViewCreationInformation viewCreationinfo = new ViewCreationInformation(); //Replace <View Name> with the name you want to give to your map view viewCreationinfo.Title = "<View Name>"; viewCreationinfo.ViewTypeKind = ViewType.Html; View oView = oList.Views.Add(viewCreationinfo); oView.JSLink = "mapviewtemplate.js"; oView.Update(); context.ExecuteQuery(); }
/// <summary> /// Creates Pages in the given web and Library using the passed client context /// </summary> /// <param name="context"></param> /// <param name="web"></param> /// <summary> /// creates a pages using a single definition file /// </summary> /// <param name="context"></param> /// <param name="def"></param> public override void Process(ClientContext context, bool add, string def) { XmlDocument doc = new XmlDocument(); doc.LoadXml(System.IO.File.ReadAllText(def)); XmlNodeList views = doc.SelectNodes("Views/View"); if (add) { foreach (XmlNode view in views) { //get the destination list name from ListName attribute List dest = context.Web.Lists.GetByTitle(view.Attributes[Constants.ViewAttributeNames.ListName].Value); ViewCreationInformation info = new ViewCreationInformation(); info.SetAsDefaultView = Boolean.Parse(view.Attributes[Constants.ViewAttributeNames.DefaultView].Value); info.Title = view.Attributes[Constants.ViewAttributeNames.Title].Value; info.ViewTypeKind = (ViewType)int.Parse(view.Attributes[Constants.ViewAttributeNames.ViewType].Value); info.ViewFields = view.Attributes[Constants.ViewAttributeNames.ViewFields].Value.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); View newView = dest.Views.Add(info); context.ExecuteQuery(); newView.Toolbar = view.Attributes[Constants.ViewAttributeNames.Toolbar].Value; newView.JSLink = view.Attributes[Constants.ViewAttributeNames.JSLink].Value; newView.Update(); context.ExecuteQuery(); } } else { foreach (XmlNode view in views) { //get the destination list name from ListName attribute List dest = context.Web.Lists.GetByTitle(view.Attributes[Constants.ViewAttributeNames.ListName].Value); ViewCollection listViews = dest.Views; context.Load(listViews); context.ExecuteQuery(); foreach (View viewItem in listViews) { if (viewItem.Title == view.Attributes[Constants.ViewAttributeNames.Toolbar].Value) { viewItem.DeleteObject(); } } } context.ExecuteQuery(); } }
public static View CreateView(this List list, string title, string[] viewFields, ViewType viewTypeKind, string query, uint rowLimit, bool paged, bool personalView, bool isDefault) { ViewCreationInformation viewCreationInformation = new ViewCreationInformation { Title = title, ViewFields = viewFields, ViewTypeKind = viewTypeKind, Query = query, RowLimit = rowLimit, Paged = paged, PersonalView = personalView, SetAsDefaultView = isDefault }; return(CreateView(list, viewCreationInformation)); }
public void CreateView(string listTitle, string viewTitle, string[] fields) { //Emp List targetList = _context.Web.Lists.GetByTitle(listTitle); ViewCollection viewCollection = targetList.Views; _context.Load(viewCollection); ViewCreationInformation viewCreationInformation = new ViewCreationInformation { Title = viewTitle, RowLimit = 10, SetAsDefaultView = true, ViewFields = fields }; View listView = viewCollection.Add(viewCreationInformation); listView.Update(); }
protected override void DeployModelInternal(object modelHost, DefinitionBase model) { var list = modelHost.WithAssertAndCast <List>("modelHost", value => value.RequireNotNull()); var listViewModel = model.WithAssertAndCast <ListViewDefinition>("model", value => value.RequireNotNull()); var currentView = FindViewByTitle(list.Views, listViewModel.Title); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = currentView, ObjectType = typeof(View), ObjectDefinition = listViewModel, ModelHost = modelHost }); if (currentView == null) { var newView = new ViewCreationInformation { Title = listViewModel.Title, RowLimit = (uint)listViewModel.RowLimit, SetAsDefaultView = listViewModel.IsDefault, Paged = listViewModel.IsPaged }; if (!string.IsNullOrEmpty(listViewModel.Query)) { newView.Query = listViewModel.Query; } if (listViewModel.Fields != null && listViewModel.Fields.Count() > 0) { newView.ViewFields = listViewModel.Fields.ToArray(); } currentView = list.Views.Add(newView); } else { currentView.Title = listViewModel.Title; currentView.RowLimit = (uint)listViewModel.RowLimit; currentView.DefaultView = listViewModel.IsDefault; currentView.Paged = listViewModel.IsPaged; if (!string.IsNullOrEmpty(listViewModel.Query)) { currentView.ViewQuery = listViewModel.Query; } if (listViewModel.Fields != null && listViewModel.Fields.Count() > 0) { currentView.ViewFields.RemoveAll(); foreach (var f in listViewModel.Fields) { currentView.ViewFields.Add(f); } } } InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentView, ObjectType = typeof(View), ObjectDefinition = listViewModel, ModelHost = modelHost }); currentView.Update(); list.Context.ExecuteQuery(); }
void ProvisionSample2(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-Substring-long-text")); web.Context.ExecuteQuery(); List existingList = results.FirstOrDefault(); if (existingList != null) { existingList.DeleteObject(); web.Context.ExecuteQuery(); } //Create list ListCreationInformation creationInfo = new ListCreationInformation(); creationInfo.Title = "CSR-Substring-long-text"; creationInfo.TemplateType = (int)ListTemplateType.Announcements; 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"] = "Announcement 1"; item1["Body"] = "Aaaaaa Bbbbbb Cccccc Dccccc Eeeeee Ffffff Gggggg Hhhhhh Iiiiii Jjjjjj Kkkkkk Llllll Mmmmmm Nnnnnn Oooooo Pppppp Qqqqqq Rrrrrr Ssssss Tttttt Uuuuuu Vvvvvv Wwwwww Xxxxx Yyyyyy Zzzzzz"; item1.Update(); Microsoft.SharePoint.Client.ListItem item2 = newlist.AddItem(new ListItemCreationInformation()); item2["Title"] = "Announcement 2"; item2["Body"] = "Aaaaaa Bbbbbb Cccccc Dccccc Eeeeee Ffffff Gggggg Hhhhhh Iiiiii Jjjjjj Kkkkkk Llllll Mmmmmm Nnnnnn Oooooo Pppppp Qqqqqq Rrrrrr Ssssss Tttttt Uuuuuu Vvvvvv Wwwwww Xxxxx Yyyyyy Zzzzzz"; item2.Update(); Microsoft.SharePoint.Client.ListItem item3 = newlist.AddItem(new ListItemCreationInformation()); item3["Title"] = "Announcement 3"; item3["Body"] = "Aaaaaa Bbbbbb Cccccc Dccccc Eeeeee Ffffff Gggggg Hhhhhh Iiiiii Jjjjjj Kkkkkk Llllll Mmmmmm Nnnnnn Oooooo Pppppp Qqqqqq Rrrrrr Ssssss Tttttt Uuuuuu Vvvvvv Wwwwww Xxxxx Yyyyyy Zzzzzz"; item3.Update(); //Create sample view ViewCreationInformation sampleViewCreateInfo = new ViewCreationInformation(); sampleViewCreateInfo.Title = "CSR Sample View"; sampleViewCreateInfo.ViewFields = new string[] { "Title", "Body" }; 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/SubstringLongText.js"); }
/// <summary> /// Create view to existing list /// </summary> /// <param name="list"></param> /// <param name="viewName"></param> /// <param name="viewType"></param> /// <param name="viewFields"></param> /// <param name="rowLimit"></param> /// <param name="setAsDefault"></param> /// <param name="query"></param> /// <param name="personal"></param> public static void CreateListView(this List list, string viewName, ViewType viewType, string[] viewFields, uint rowLimit, bool setAsDefault, string query = null, bool personal = false) { if (string.IsNullOrEmpty(viewName)) throw new ArgumentNullException("viewName"); ViewCreationInformation viewCreationInformation = new ViewCreationInformation(); viewCreationInformation.Title = viewName; viewCreationInformation.ViewTypeKind = viewType; viewCreationInformation.RowLimit = rowLimit; viewCreationInformation.ViewFields = viewFields; viewCreationInformation.PersonalView = personal; viewCreationInformation.SetAsDefaultView = setAsDefault; if (!string.IsNullOrEmpty(query)) { viewCreationInformation.Query = query; } list.Views.Add(viewCreationInformation); list.Context.ExecuteQuery(); }
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 override void DeployModel(object modelHost, DefinitionBase model) { var listMOdelHost = modelHost.WithAssertAndCast <ListModelHost>("modelHost", value => value.RequireNotNull()); var listViewModel = model.WithAssertAndCast <ListViewDefinition>("model", value => value.RequireNotNull()); var list = listMOdelHost.HostList; var currentView = FindView(list, listViewModel); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = currentView, ObjectType = typeof(View), ObjectDefinition = listViewModel, ModelHost = modelHost }); if (currentView == null) { TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new list view"); var newView = new ViewCreationInformation { Title = string.IsNullOrEmpty(listViewModel.Url) ? listViewModel.Title : GetSafeViewUrl(listViewModel.Url), RowLimit = (uint)listViewModel.RowLimit, SetAsDefaultView = listViewModel.IsDefault, Paged = listViewModel.IsPaged }; if (!string.IsNullOrEmpty(listViewModel.Query)) { newView.Query = listViewModel.Query; } if (listViewModel.Fields != null && listViewModel.Fields.Count() > 0) { newView.ViewFields = listViewModel.Fields.ToArray(); } currentView = list.Views.Add(newView); if (!string.IsNullOrEmpty(listViewModel.ContentTypeName)) { currentView.ContentTypeId = LookupListContentTypeByName(list, listViewModel.ContentTypeName); } if (!string.IsNullOrEmpty(listViewModel.ContentTypeId)) { currentView.ContentTypeId = LookupListContentTypeById(list, listViewModel.ContentTypeId); } currentView.JSLink = listViewModel.JSLink; if (listViewModel.DefaultViewForContentType.HasValue) { currentView.DefaultViewForContentType = listViewModel.DefaultViewForContentType.Value; } currentView.Hidden = listViewModel.Hidden; currentView.Title = listViewModel.Title; currentView.Update(); list.Context.ExecuteQueryWithTrace(); currentView = FindView(list, listViewModel); list.Context.Load(currentView); list.Context.ExecuteQueryWithTrace(); } else { list.Context.Load(currentView); list.Context.ExecuteQueryWithTrace(); TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing list view"); currentView.Hidden = listViewModel.Hidden; currentView.RowLimit = (uint)listViewModel.RowLimit; currentView.DefaultView = listViewModel.IsDefault; currentView.Paged = listViewModel.IsPaged; if (!string.IsNullOrEmpty(listViewModel.Query)) { currentView.ViewQuery = listViewModel.Query; } if (listViewModel.Fields != null && listViewModel.Fields.Count() > 0) { currentView.ViewFields.RemoveAll(); foreach (var f in listViewModel.Fields) { currentView.ViewFields.Add(f); } } if (!string.IsNullOrEmpty(listViewModel.ContentTypeName)) { currentView.ContentTypeId = LookupListContentTypeByName(list, listViewModel.ContentTypeName); } if (!string.IsNullOrEmpty(listViewModel.ContentTypeId)) { currentView.ContentTypeId = LookupListContentTypeById(list, listViewModel.ContentTypeId); } if (!string.IsNullOrEmpty(listViewModel.JSLink)) { currentView.JSLink = listViewModel.JSLink; } if (listViewModel.DefaultViewForContentType.HasValue) { currentView.DefaultViewForContentType = listViewModel.DefaultViewForContentType.Value; } currentView.Title = listViewModel.Title; } InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentView, ObjectType = typeof(View), ObjectDefinition = listViewModel, ModelHost = modelHost }); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling currentView.Update()"); currentView.Update(); list.Context.ExecuteQueryWithTrace(); }
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 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 } }
protected override void DeployModelInternal(object modelHost, DefinitionBase model) { var list = modelHost.WithAssertAndCast<List>("modelHost", value => value.RequireNotNull()); var listViewModel = model.WithAssertAndCast<ListViewDefinition>("model", value => value.RequireNotNull()); var currentView = FindViewByTitle(list.Views, listViewModel.Title); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = currentView, ObjectType = typeof(View), ObjectDefinition = listViewModel, ModelHost = modelHost }); if (currentView == null) { var newView = new ViewCreationInformation { Title = listViewModel.Title, RowLimit = (uint)listViewModel.RowLimit, SetAsDefaultView = listViewModel.IsDefault, Paged = listViewModel.IsPaged }; if (!string.IsNullOrEmpty(listViewModel.Query)) newView.Query = listViewModel.Query; if (listViewModel.Fields != null && listViewModel.Fields.Count() > 0) newView.ViewFields = listViewModel.Fields.ToArray(); currentView = list.Views.Add(newView); } else { currentView.Title = listViewModel.Title; currentView.RowLimit = (uint)listViewModel.RowLimit; currentView.DefaultView = listViewModel.IsDefault; currentView.Paged = listViewModel.IsPaged; if (!string.IsNullOrEmpty(listViewModel.Query)) currentView.ViewQuery = listViewModel.Query; if (listViewModel.Fields != null && listViewModel.Fields.Count() > 0) { currentView.ViewFields.RemoveAll(); foreach (var f in listViewModel.Fields) currentView.ViewFields.Add(f); } } InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentView, ObjectType = typeof(View), ObjectDefinition = listViewModel, ModelHost = modelHost }); currentView.Update(); list.Context.ExecuteQuery(); }
public override void DeployModel(object modelHost, DefinitionBase model) { var listMOdelHost = modelHost.WithAssertAndCast<ListModelHost>("modelHost", value => value.RequireNotNull()); var listViewModel = model.WithAssertAndCast<ListViewDefinition>("model", value => value.RequireNotNull()); var list = listMOdelHost.HostList; var currentView = FindView(list, listViewModel); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = currentView, ObjectType = typeof(View), ObjectDefinition = listViewModel, ModelHost = modelHost }); if (currentView == null) { TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new list view"); var newView = new ViewCreationInformation { Title = string.IsNullOrEmpty(listViewModel.Url) ? listViewModel.Title : GetSafeViewUrl(listViewModel.Url), RowLimit = (uint)listViewModel.RowLimit, SetAsDefaultView = listViewModel.IsDefault, Paged = listViewModel.IsPaged }; if (!string.IsNullOrEmpty(listViewModel.Query)) newView.Query = listViewModel.Query; if (listViewModel.Fields != null && listViewModel.Fields.Count() > 0) newView.ViewFields = listViewModel.Fields.ToArray(); if (!string.IsNullOrEmpty(listViewModel.Type)) { newView.ViewTypeKind = (ViewType)Enum.Parse(typeof(ViewType), string.IsNullOrEmpty(listViewModel.Type) ? BuiltInViewType.Html : listViewModel.Type); } currentView = list.Views.Add(newView); MapListViewProperties(list, currentView, listViewModel); currentView.Update(); list.Context.ExecuteQueryWithTrace(); currentView = FindView(list, listViewModel); list.Context.Load(currentView); list.Context.ExecuteQueryWithTrace(); } else { list.Context.Load(currentView); list.Context.ExecuteQueryWithTrace(); TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing list view"); MapListViewProperties(list, currentView, listViewModel); } ProcessLocalization(currentView, listViewModel); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentView, ObjectType = typeof(View), ObjectDefinition = listViewModel, ModelHost = modelHost }); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling currentView.Update()"); currentView.Update(); list.Context.ExecuteQueryWithTrace(); }
private void CreateView(Web web, View view, ViewCollection existingViews, List createdList) { var viewElement = XElement.Parse(view.SchemaXml); var displayNameElement = viewElement.Attribute("DisplayName"); if (displayNameElement == null) { throw new ApplicationException("Invalid View element, missing a valid value for the attribute DisplayName."); } var existingView = existingViews.FirstOrDefault(v => v.Title == displayNameElement.Value); if (existingView != null) { existingView.DeleteObject(); web.Context.ExecuteQueryRetry(); } var viewTitle = displayNameElement.Value; // Type var viewTypeString = viewElement.Attribute("Type") != null?viewElement.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 = viewElement.Descendants("ViewFields").FirstOrDefault(); if (viewFieldsElement != null) { viewFields = (from field in viewElement.Descendants("ViewFields").Descendants("FieldRef") select field.Attribute("Name").Value).ToArray(); } // Default view var viewDefault = viewElement.Attribute("DefaultView") != null && Boolean.Parse(viewElement.Attribute("DefaultView").Value); // Row limit var viewPaged = true; uint viewRowLimit = 30; var rowLimitElement = viewElement.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 viewElement.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, }; var createdView = createdList.Views.Add(viewCI); web.Context.Load(createdView, v => v.Scope, v => v.JSLink); web.Context.ExecuteQueryRetry(); // Scope var scope = viewElement.Attribute("Scope") != null?viewElement.Attribute("Scope").Value : null; ViewScope parsedScope = ViewScope.DefaultValue; if (!string.IsNullOrEmpty(scope) && Enum.TryParse <ViewScope>(scope, out parsedScope)) { createdView.Scope = parsedScope; createdView.Update(); } // JSLink var jslinkElement = viewElement.Descendants("JSLink").FirstOrDefault(); if (jslinkElement != null) { var jslink = jslinkElement.Value; if (createdView.JSLink != jslink) { createdView.JSLink = jslink; createdView.Update(); } } createdList.Update(); web.Context.ExecuteQueryRetry(); }
public virtual void ConfigureFieldsAndViews(ClientContext ctx) { RefreshList(ctx); if ((IndexFields != null && IndexFields.Count > 0) || (RequiredFields != null && RequiredFields.Count > 0) || EnforceUniqueFields != null && EnforceUniqueFields.Count > 0) { if (RequiredFields != null && RequiredFields.Count > 0) { foreach (var field in RequiredFields) { Utility.RequireField(List, field); } } if (IndexFields != null && IndexFields.Count > 0) { foreach (var field in IndexFields) { Utility.IndexField(List, field); } } if (EnforceUniqueFields != null && EnforceUniqueFields.Count > 0) { foreach (var field in EnforceUniqueFields) { Utility.EnforceUniqueField(List, field); } } ctx.ExecuteQueryRetry(); RefreshList(ctx); } if (HiddenFormFields != null && HiddenFormFields.Count > 0) { foreach (var fieldName in HiddenFormFields) { Utility.HideFieldOnAllForms(List, fieldName); } ctx.ExecuteQueryRetry(); RefreshList(ctx); } if (DisplayFormOnlyFields != null && DisplayFormOnlyFields.Count > 0) { foreach (var field in DisplayFormOnlyFields) { Utility.ShowOnDisplayFormOnly(List, field); } ctx.ExecuteQueryRetry(); RefreshList(ctx); } if (!string.IsNullOrEmpty(TitleFieldDisplayName)) { Utility.SetTitleFieldDisplayName(List, TitleFieldDisplayName); ctx.ExecuteQueryRetry(); RefreshList(ctx); } if (FieldDisplayNameOverrides != null && FieldDisplayNameOverrides.Count > 0) { foreach (var field in FieldDisplayNameOverrides.Keys) { Utility.SetFieldDisplayName(List, field, FieldDisplayNameOverrides[field]); } ctx.ExecuteQueryRetry(); RefreshList(ctx); } if (!string.IsNullOrEmpty(DefaultViewSchemaXml) || !string.IsNullOrEmpty(DefaultViewTitle)) { var defaultView = List.Views[0]; if (!string.IsNullOrEmpty(DefaultViewSchemaXml)) { defaultView.ListViewXml = DefaultViewSchemaXml; } if (!string.IsNullOrEmpty(DefaultViewTitle)) { defaultView.Title = DefaultViewTitle; } defaultView.Update(); ctx.ExecuteQueryRetry(); } if (ListViewSchemas != null) { foreach (var key in ListViewSchemas.Keys) { if (!ViewExists(key)) { var vcInfo = new ViewCreationInformation { Title = key }; var view = List.Views.Add(vcInfo); view.ListViewXml = ListViewSchemas[key]; view.Update(); } else { var view = List.Views.GetByTitle(key); view.ListViewXml = ListViewSchemas[key]; view.Update(); } } ctx.ExecuteQueryRetry(); } if (RemoveViewFields != null || AddToAllViewsFields != null) { foreach (var view in List.Views) { if (RemoveViewFields != null) { foreach (var field in RemoveViewFields) { if (view.ViewFields.SchemaXml.Contains(field)) { view.ViewFields.Remove(field); } } } if (AddToAllViewsFields != null) { foreach (var field in AddToAllViewsFields) { if (!view.ViewFields.SchemaXml.Contains(field)) { view.ViewFields.Add(field); } } } view.Update(); } ctx.ExecuteQueryRetry(); } }
public override void AddView(string viewName, IEnumerable<string> viewFields, string strQuery, uint rowLimit, bool paged, bool makeDefault) { var viewCreationInfo=new ViewCreationInformation(); viewCreationInfo.Title = viewName; viewCreationInfo.ViewFields = viewFields.ToArray(); viewCreationInfo.Paged = paged; viewCreationInfo.RowLimit = rowLimit; viewCreationInfo.Query = strQuery; viewCreationInfo.SetAsDefaultView = makeDefault; _list.Views.Add(viewCreationInfo); _context.ExecuteQuery(); }
private void CreateView(Web web, View view, ViewCollection existingViews, List createdList, PnPMonitoredScope monitoredScope) { try { var viewElement = XElement.Parse(view.SchemaXml); var displayNameElement = viewElement.Attribute("DisplayName"); if (displayNameElement == null) { throw new ApplicationException("Invalid View element, missing a valid value for the attribute DisplayName."); } monitoredScope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstances_Creating_view__0_, displayNameElement.Value); var existingView = existingViews.FirstOrDefault(v => v.Title == displayNameElement.Value); if (existingView != null) { existingView.DeleteObject(); web.Context.ExecuteQueryRetry(); } var viewTitle = displayNameElement.Value; // Type var viewTypeString = viewElement.Attribute("Type") != null ? viewElement.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 = viewElement.Descendants("ViewFields").FirstOrDefault(); if (viewFieldsElement != null) { viewFields = (from field in viewElement.Descendants("ViewFields").Descendants("FieldRef") select field.Attribute("Name").Value).ToArray(); } // Default view var viewDefault = viewElement.Attribute("DefaultView") != null && Boolean.Parse(viewElement.Attribute("DefaultView").Value); // Row limit var viewPaged = true; uint viewRowLimit = 30; var rowLimitElement = viewElement.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 viewElement.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, }; var createdView = createdList.Views.Add(viewCI); web.Context.Load(createdView, v => v.Scope, v => v.JSLink); web.Context.ExecuteQueryRetry(); // Scope var scope = viewElement.Attribute("Scope") != null ? viewElement.Attribute("Scope").Value : null; ViewScope parsedScope = ViewScope.DefaultValue; if (!string.IsNullOrEmpty(scope) && Enum.TryParse<ViewScope>(scope, out parsedScope)) { createdView.Scope = parsedScope; createdView.Update(); } // JSLink var jslinkElement = viewElement.Descendants("JSLink").FirstOrDefault(); if (jslinkElement != null) { var jslink = jslinkElement.Value; if (createdView.JSLink != jslink) { createdView.JSLink = jslink; createdView.Update(); } } createdList.Update(); web.Context.ExecuteQueryRetry(); } catch (Exception ex) { monitoredScope.LogError(CoreResources.Provisioning_ObjectHandlers_ListInstances_Creating_view_failed___0_____1_, ex.Message, ex.StackTrace); throw; } }
public override void DeployModel(object modelHost, DefinitionBase model) { var listMOdelHost = modelHost.WithAssertAndCast <ListModelHost>("modelHost", value => value.RequireNotNull()); var listViewModel = model.WithAssertAndCast <ListViewDefinition>("model", value => value.RequireNotNull()); var list = listMOdelHost.HostList; var currentView = FindView(list, listViewModel); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = currentView, ObjectType = typeof(View), ObjectDefinition = listViewModel, ModelHost = modelHost }); if (currentView == null) { TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new list view"); var newView = new ViewCreationInformation { Title = string.IsNullOrEmpty(listViewModel.Url) ? listViewModel.Title : GetSafeViewUrl(listViewModel.Url), RowLimit = (uint)listViewModel.RowLimit, SetAsDefaultView = listViewModel.IsDefault, Paged = listViewModel.IsPaged }; if (!string.IsNullOrEmpty(listViewModel.Query)) { newView.Query = listViewModel.Query; } if (listViewModel.Fields != null && listViewModel.Fields.Any()) { newView.ViewFields = listViewModel.Fields.ToArray(); } if (!string.IsNullOrEmpty(listViewModel.Type)) { newView.ViewTypeKind = (ViewType)Enum.Parse(typeof(ViewType), string.IsNullOrEmpty(listViewModel.Type) ? BuiltInViewType.Html : listViewModel.Type); } currentView = list.Views.Add(newView); MapListViewProperties(list, currentView, listViewModel); currentView.Update(); list.Context.ExecuteQueryWithTrace(); currentView = FindView(list, listViewModel); list.Context.Load(currentView); list.Context.ExecuteQueryWithTrace(); } else { list.Context.Load(currentView); list.Context.ExecuteQueryWithTrace(); TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing list view"); MapListViewProperties(list, currentView, listViewModel); } ProcessLocalization(currentView, listViewModel); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentView, ObjectType = typeof(View), ObjectDefinition = listViewModel, ModelHost = modelHost }); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling currentView.Update()"); currentView.Update(); list.Context.ExecuteQueryWithTrace(); }
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 ProvisionObjects(Web web, ProvisioningTemplate template) { Log.Info(Constants.LOGGING_SOURCE_FRAMEWORK_PROVISIONING, CoreResources.Provisioning_ObjectHandlers_ListInstances); if (template.Lists.Any()) { var rootWeb = (web.Context as ClientContext).Site.RootWeb; 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.FindIndex(x => x.Equals(UrlUtility.Combine(serverRelativeUrl, list.Url), StringComparison.OrdinalIgnoreCase)) == -1) { 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; createdList.DraftVersionVisibility = (DraftVisibilityType)list.DraftVersionVisibility; // TODO: User should be notified that MinorVersionLimit and DraftVersionVisibility will not be applied if (list.EnableMinorVersions) { createdList.MajorWithMinorVersionsLimit = list.MinorVersionLimit; // Set only if enabled, otherwise you'll get exception due setting value to zero. // 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 { // TODO: User should be notified that DraftVersionVisibility is not applied because .EnableModeration is false } } else { createdList.DraftVersionVisibility = (DraftVisibilityType)list.DraftVersionVisibility; } } } } createdList.OnQuickLaunch = list.OnQuickLaunch; if (createdList.BaseTemplate != (int)ListTemplateType.DiscussionBoard) { 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 FieldRefs foreach (var listInfo in createdLists) { if (listInfo.ListInstance.FieldRefs.Any()) { foreach (var fieldRef in listInfo.ListInstance.FieldRefs) { var field = rootWeb.GetFieldById<Field>(fieldRef.Id); if (field != null) { 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 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 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 } }
private static void CreateView(Web web, View view, Microsoft.SharePoint.Client.ViewCollection existingViews, List createdList) { try { //have to maintain raw displayNameElement for displayNameElement.Value.ContainsResourceToken() at Line 717 var viewElementRaw = XElement.Parse(view.ListViewXml); //var displayNameElement = viewElementRaw.Attribute("DisplayName"); var displayNameElement = "XluoTest"; if (displayNameElement == null) { throw new ApplicationException("Invalid View element, missing a valid value for the attribute DisplayName."); } //for all other functions need Parsed SchemaXML var viewElement = XElement.Parse(view.ListViewXml); //WriteSubProgress($"Views for list {createdList.Title}", displayNameElement.Value, currentViewIndex, total); //monitoredScope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstances_Creating_view__0_, displayNameElement.Value); //get from resource file var viewTitle = displayNameElement; //var existingView = existingViews.FirstOrDefault(v => v.Title == viewTitle); //if (existingView != null) //{ // existingView.DeleteObject(); // web.Context.ExecuteQueryRetry(); //} // Type var viewTypeString = viewElement.Attribute("Type") != null?viewElement.Attribute("Type").Value : "None"; viewTypeString = viewTypeString[0].ToString().ToUpper() + viewTypeString.Substring(1).ToLower(); var viewType = (ViewType)Enum.Parse(typeof(ViewType), viewTypeString); // Fix the calendar recurrence if (viewType == ViewType.Calendar) { viewType = ViewType.Calendar | ViewType.Recurrence; } // Fields string[] viewFields = null; var viewFieldsElement = viewElement.Descendants("ViewFields").FirstOrDefault(); if (viewFieldsElement != null) { viewFields = (from field in viewElement.Descendants("ViewFields").Descendants("FieldRef") select field.Attribute("Name").Value).ToArray(); } // Default view var viewDefault = viewElement.Attribute("DefaultView") != null && bool.Parse(viewElement.Attribute("DefaultView").Value); // Hidden view var hidden = viewElement.Attribute("Hidden") != null && bool.Parse(viewElement.Attribute("Hidden").Value); // Row limit var viewPaged = true; uint viewRowLimit = 30; var rowLimitElement = viewElement.Descendants("RowLimit").FirstOrDefault(); if (rowLimitElement != null) { if (rowLimitElement.Attribute("Paged") != null) { viewPaged = bool.Parse(rowLimitElement.Attribute("Paged").Value); } viewRowLimit = uint.Parse(rowLimitElement.Value); } #if !SP2013 && !SP2016 //BaseViewID int BaseViewID = 1; var baseviewIDElement = viewElementRaw.Attribute("BaseViewID"); if (baseviewIDElement != null) { BaseViewID = int.Parse(baseviewIDElement.Value); } #endif // Query var viewQuery = new StringBuilder(); foreach (var queryElement in viewElement.Descendants("Query").Elements()) { viewQuery.Append(queryElement.ToString()); } var viewCI = new ViewCreationInformation { #if !SP2013 && !SP2016 baseViewId = BaseViewID, #endif ViewFields = viewFields, RowLimit = viewRowLimit, Paged = viewPaged, Title = viewTitle, Query = viewQuery.ToString(), ViewTypeKind = viewType, PersonalView = false, SetAsDefaultView = viewDefault }; // Allow to specify a custom view url. View url is taken from title, so we first set title to the view url value we need, // create the view and then set title back to the original value var urlAttribute = viewElement.Attribute("Url"); var urlHasValue = urlAttribute != null && !string.IsNullOrEmpty(urlAttribute.Value); if (urlHasValue) { //set Title to be equal to url (in order to generate desired url) viewCI.Title = urlAttribute.Value; } var reader = viewElement.CreateReader(); reader.MoveToContent(); var viewInnerXml = reader.ReadInnerXml(); var createdView = createdList.Views.Add(viewCI); createdView.ListViewXml = viewInnerXml; if (hidden) { createdView.Hidden = hidden; } createdView.Update(); #if SP2013 || SP2016 createdView.EnsureProperties(v => v.Scope, v => v.JSLink, v => v.Title, v => v.Aggregations, v => v.MobileView, v => v.MobileDefaultView, v => v.ViewData); #else createdView.EnsureProperties(v => v.Scope, v => v.JSLink, v => v.Title, v => v.Aggregations, v => v.MobileView, v => v.MobileDefaultView, v => v.ViewData, v => v.CustomFormatter); #endif web.Context.ExecuteQueryRetry(); if (urlHasValue) { //restore original title createdView.Title = viewTitle; createdView.Update(); } // ContentTypeID var contentTypeID = (string)viewElement.Attribute("ContentTypeID"); if (!string.IsNullOrEmpty(contentTypeID) && (contentTypeID != BuiltInContentTypeId.System)) { ContentTypeId childContentTypeId = null; if (contentTypeID == BuiltInContentTypeId.RootOfList) { var childContentType = web.GetContentTypeById(contentTypeID); childContentTypeId = childContentType != null ? childContentType.Id : null; } else { childContentTypeId = createdList.ContentTypes.BestMatch(contentTypeID); } if (childContentTypeId != null) { createdView.ContentTypeId = childContentTypeId; createdView.Update(); } } // Default for content type bool parsedDefaultViewForContentType; var defaultViewForContentType = (string)viewElement.Attribute("DefaultViewForContentType"); if (!string.IsNullOrEmpty(defaultViewForContentType) && bool.TryParse(defaultViewForContentType, out parsedDefaultViewForContentType)) { createdView.DefaultViewForContentType = parsedDefaultViewForContentType; createdView.Update(); } // Scope var scope = (string)viewElement.Attribute("Scope"); var parsedScope = ViewScope.DefaultValue; if (!string.IsNullOrEmpty(scope) && Enum.TryParse <ViewScope>(scope, out parsedScope)) { createdView.Scope = parsedScope; createdView.Update(); } // MobileView var mobileView = viewElement.Attribute("MobileView") != null && bool.Parse(viewElement.Attribute("MobileView").Value); if (mobileView) { createdView.MobileView = mobileView; createdView.Update(); } // MobileDefaultView var mobileDefaultView = viewElement.Attribute("MobileDefaultView") != null && bool.Parse(viewElement.Attribute("MobileDefaultView").Value); if (mobileDefaultView) { createdView.MobileDefaultView = mobileDefaultView; createdView.Update(); } // Aggregations var aggregationsElement = viewElement.Descendants("Aggregations").FirstOrDefault(); if (aggregationsElement != null && aggregationsElement.HasElements) { var fieldRefString = ""; foreach (var fieldRef in aggregationsElement.Descendants("FieldRef")) { fieldRefString += fieldRef.ToString(); } if (createdView.Aggregations != fieldRefString) { createdView.Aggregations = fieldRefString; createdView.Update(); } } // JSLink var jslinkElement = viewElement.Descendants("JSLink").FirstOrDefault(); if (jslinkElement != null) { var jslink = jslinkElement.Value; if (createdView.JSLink != jslink) { createdView.JSLink = jslink; createdView.Update(); // Only push the JSLink value to the web part as it contains a / indicating it's a custom one. So we're not pushing the OOB ones like clienttemplates.js or hierarchytaskslist.js // but do push custom ones down to th web part (e.g. ~sitecollection/Style Library/JSLink-Samples/ConfidentialDocuments.js) if (jslink.Contains("/")) { createdView.EnsureProperty(v => v.ServerRelativeUrl); createdList.SetJSLinkCustomizations(createdView.ServerRelativeUrl, jslink); } } } #if !ONPREMISES || SP2019 // CustomFormatter var customFormatterElement = viewElement.Descendants("CustomFormatter").FirstOrDefault(); if (customFormatterElement != null) { var customFormatter = customFormatterElement.Value; customFormatter = customFormatter.Replace("&", "&"); if (createdView.CustomFormatter != customFormatter) { createdView.CustomFormatter = customFormatter; createdView.Update(); } } #endif // View Data var viewDataElement = viewElement.Descendants("ViewData").FirstOrDefault(); if (viewDataElement != null && viewDataElement.HasElements) { var fieldRefString = ""; foreach (var fieldRef in viewDataElement.Descendants("FieldRef")) { fieldRefString += fieldRef.ToString(); } if (createdView.ViewData != fieldRefString) { createdView.ViewData = fieldRefString; createdView.Update(); } } createdList.Update(); web.Context.ExecuteQueryRetry(); // Add ListViewId token parser createdView.EnsureProperty(v => v.Id); //parser.AddToken(new ListViewIdToken(web, createdList.Title, createdView.Title, createdView.Id)); #if !SP2013 // Localize view title //if (displayNameElement.Value.ContainsResourceToken()) { //createdView.LocalizeView(web, displayNameElement.Value, parser, monitoredScope); } #endif } catch (Exception ex) { //monitoredScope.LogError(CoreResources.Provisioning_ObjectHandlers_ListInstances_Creating_view_failed___0_____1_, ex.Message, ex.StackTrace); throw; } }
/// <summary> /// /// </summary> /// <param name="url"></param> /// <param name="titleList"></param> /// <param name="titleView"></param> /// <param name="viewFields"></param> /// <param name="viewQuery"></param> /// <param name="jslink"></param> private static void UpdateView(string url, string titleList, string titleView, string[] viewFields, string viewQuery, string jslink = "" ) { try { using (ClientContext clientContext = new ClientContext(url)) { Web web = clientContext.Web; clientContext.Load(web); clientContext.ExecuteQuery(); List list = web.Lists.GetByTitle(titleList); ViewCollection viewColl = list.Views; clientContext.Load(viewColl); clientContext.ExecuteQuery(); View taskView = GetViewByTitle(list, titleView); if (taskView != null) { taskView.ViewFields.RemoveAll(); foreach (string i in viewFields) { taskView.ViewFields.Add(i); } taskView.ViewQuery = viewQuery; if (jslink != "") taskView.JSLink = jslink; taskView.Update(); list.Update(); clientContext.ExecuteQuery(); } else { ViewCreationInformation creationInfo = new ViewCreationInformation(); creationInfo.Title = titleView; creationInfo.RowLimit = 100; creationInfo.ViewFields = viewFields; creationInfo.Query = viewQuery; creationInfo.ViewTypeKind = ViewType.None; creationInfo.SetAsDefaultView = false; viewColl.Add(creationInfo); list.Update(); clientContext.ExecuteQuery(); taskView = GetViewByTitle(list, titleView); if (jslink != "") taskView.JSLink = jslink; taskView.Update(); list.Update(); clientContext.ExecuteQuery(); } //tasks //string viewURL = web.ServerRelativeUrl + "/Lists/Tasks/" + titleView + ".aspx"; //string displayURL = web.ServerRelativeUrl + "/Lists/Tasks/DispForm.aspx"; //Issues if (jslink != "") { string viewURL = web.ServerRelativeUrl + "/Lists/Issues/" + titleView + ".aspx"; string displayURL = web.ServerRelativeUrl + "/Lists/Issues/DispForm.aspx"; RegisterJStoWebPart(web, viewURL, ConfigurationManager.AppSettings["JSFile"].ToString()); RegisterJStoWebPart(web, displayURL, ConfigurationManager.AppSettings["JSFile"].ToString()); } //RegisterJStoWebPart(web, "/DashBoard/PSALPO/PSALFastTrackPO/FinSystemsBackLog1/Lists/Tasks/AllItems.aspx", ConfigurationManager.AppSettings["JSFile"].ToString()); } } catch(Exception ex) { Console.WriteLine(ex.Message + url); } }
public override void ProvisionObjects(Web web, ProvisioningTemplate template) { 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.Select(existingList => existingList.RootFolder.ServerRelativeUrl).ToList(); var serverRelativeUrl = web.ServerRelativeUrl; 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; listCreate.QuickLaunchOption = list.OnQuickLaunch ? QuickLaunchOptions.On : QuickLaunchOptions.Off; listCreate.Url = parser.Parse(list.Url); var createdList = web.Lists.Add(listCreate); createdList.EnableVersioning = list.EnableVersioning; if (!String.IsNullOrEmpty(list.DocumentTemplate)) { createdList.DocumentTemplateUrl = parser.Parse(list.DocumentTemplate); } createdList.Hidden = list.Hidden; createdList.ContentTypesEnabled = list.ContentTypesEnabled; createdList.Update(); web.Context.ExecuteQueryRetry(); // TODO: handle 'removedefaultcontenttype' foreach (var ctBinding in list.ContentTypeBindings) { createdList.AddContentTypeToListById(ctBinding.ContentTypeID); if (ctBinding.Default) { createdList.SetDefaultContentTypeToList(ctBinding.ContentTypeID); } } if (list.Fields.Any()) { foreach (var field in list.Fields) { // Double check that the content type did not include the field before adding it in if (!createdList.FieldExistsById(field.SchemaXml.Substring(field.SchemaXml.IndexOf("ID=\"{") + 5, 36))) { var fieldXml = parser.Parse(field.SchemaXml); createdList.Fields.AddFieldAsXml(fieldXml, false, AddFieldOptions.DefaultValue); } } createdList.Update(); web.Context.ExecuteQueryRetry(); } if (list.FieldRefs.Any()) { foreach (var fieldRef in list.FieldRefs) { var field = web.GetFieldById <Field>(fieldRef.ID); if (!createdList.FieldExistsById(fieldRef.ID)) { createdList.Fields.Add(field); } } createdList.Update(); 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(); } } } }
void ProvisionSample7(Web web) { //Delete list if it already exists ListCollection lists = web.Lists; web.Context.Load(web.CurrentUser, i => i.Id); IEnumerable<List> results = web.Context.LoadQuery<List>(lists.Where(list => list.Title == "CSR-Read-only-SP-Controls")); web.Context.ExecuteQuery(); List existingList = results.FirstOrDefault(); if (existingList != null) { existingList.DeleteObject(); web.Context.ExecuteQuery(); } //Create list ListCreationInformation creationInfo = new ListCreationInformation(); creationInfo.Title = "CSR-Read-only-SP-Controls"; 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["AssignedTo"] = new FieldLookupValue { LookupId = web.CurrentUser.Id }; item1.Update(); //Create sample view ViewCreationInformation sampleViewCreateInfo = new ViewCreationInformation(); sampleViewCreateInfo.Title = "CSR Sample View"; sampleViewCreateInfo.ViewFields = new string[] { "DocIcon", "LinkTitle", "DueDate", "AssignedTo" }; sampleViewCreateInfo.SetAsDefaultView = true; Microsoft.SharePoint.Client.View sampleView = newlist.Views.Add(sampleViewCreateInfo); sampleView.Update(); web.Context.Load(newlist, l => l.DefaultEditFormUrl); web.Context.ExecuteQuery(); //Register JS files via JSLink properties RegisterJStoWebPart(web, newlist.DefaultEditFormUrl, "~sitecollection/Style Library/JSLink-Samples/ReadOnlySPControls.js"); }
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"); }
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 override void DeployModel(object modelHost, DefinitionBase model) { var list = modelHost.WithAssertAndCast<List>("modelHost", value => value.RequireNotNull()); var listViewModel = model.WithAssertAndCast<ListViewDefinition>("model", value => value.RequireNotNull()); var currentView = FindView(list, listViewModel); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = currentView, ObjectType = typeof(View), ObjectDefinition = listViewModel, ModelHost = modelHost }); if (currentView == null) { TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new list view"); var newView = new ViewCreationInformation { Title = string.IsNullOrEmpty(listViewModel.Url) ? listViewModel.Title : GetSafeViewUrl(listViewModel.Url), RowLimit = (uint)listViewModel.RowLimit, SetAsDefaultView = listViewModel.IsDefault, Paged = listViewModel.IsPaged }; if (!string.IsNullOrEmpty(listViewModel.Query)) newView.Query = listViewModel.Query; if (listViewModel.Fields != null && listViewModel.Fields.Count() > 0) newView.ViewFields = listViewModel.Fields.ToArray(); currentView = list.Views.Add(newView); if (!string.IsNullOrEmpty(listViewModel.ContentTypeName)) currentView.ContentTypeId = LookupListContentTypeByName(list, listViewModel.ContentTypeName); if (!string.IsNullOrEmpty(listViewModel.ContentTypeId)) currentView.ContentTypeId = LookupListContentTypeById(list, listViewModel.ContentTypeId); currentView.JSLink = listViewModel.JSLink; if (listViewModel.DefaultViewForContentType.HasValue) currentView.DefaultViewForContentType = listViewModel.DefaultViewForContentType.Value; currentView.Hidden = listViewModel.Hidden; currentView.Title = listViewModel.Title; currentView.Update(); list.Context.ExecuteQueryWithTrace(); currentView = FindView(list, listViewModel); list.Context.Load(currentView); list.Context.ExecuteQueryWithTrace(); } else { list.Context.Load(currentView); list.Context.ExecuteQueryWithTrace(); TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing list view"); currentView.Hidden = listViewModel.Hidden; currentView.RowLimit = (uint)listViewModel.RowLimit; currentView.DefaultView = listViewModel.IsDefault; currentView.Paged = listViewModel.IsPaged; if (!string.IsNullOrEmpty(listViewModel.Query)) currentView.ViewQuery = listViewModel.Query; if (listViewModel.Fields != null && listViewModel.Fields.Count() > 0) { currentView.ViewFields.RemoveAll(); foreach (var f in listViewModel.Fields) currentView.ViewFields.Add(f); } if (!string.IsNullOrEmpty(listViewModel.ContentTypeName)) currentView.ContentTypeId = LookupListContentTypeByName(list, listViewModel.ContentTypeName); if (!string.IsNullOrEmpty(listViewModel.ContentTypeId)) currentView.ContentTypeId = LookupListContentTypeById(list, listViewModel.ContentTypeId); if (!string.IsNullOrEmpty(listViewModel.JSLink)) currentView.JSLink = listViewModel.JSLink; if (listViewModel.DefaultViewForContentType.HasValue) currentView.DefaultViewForContentType = listViewModel.DefaultViewForContentType.Value; currentView.Title = listViewModel.Title; } InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentView, ObjectType = typeof(View), ObjectDefinition = listViewModel, ModelHost = modelHost }); TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling currentView.Update()"); currentView.Update(); list.Context.ExecuteQueryWithTrace(); }
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 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"); }
public override void ProvisionObjects(Web web, ProvisioningTemplate template) { var parser = new TokenParser(web); if (!web.IsPropertyAvailable("ServerRelativeUrl")) { web.Context.Load(web, w => w.ServerRelativeUrl); web.Context.ExecuteQuery(); } web.Context.Load(web.Lists, lc => lc.IncludeWithDefaultProperties(l => l.RootFolder.ServerRelativeUrl)); web.Context.ExecuteQuery(); //TODO: Upgrade to SharePoint.Client v16.0 so refactoring can be done (uncomment following line when done!) //var existingLists = web.Lists.Select(existingList => existingList.RootFolder.ServerRelativeUrl).ToList(); var existingLists = web.Lists.AsEnumerable().Select(existingList => existingList.RootFolder.ServerRelativeUrl).ToList(); var serverRelativeUrl = web.ServerRelativeUrl; 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; listCreate.QuickLaunchOption = list.OnQuickLaunch ? QuickLaunchOptions.On : QuickLaunchOptions.Off; listCreate.Url = parser.Parse(list.Url); var createdList = web.Lists.Add(listCreate); createdList.EnableVersioning = list.EnableVersioning; if (!String.IsNullOrEmpty(list.DocumentTemplate)) { createdList.DocumentTemplateUrl = parser.Parse(list.DocumentTemplate); } createdList.Hidden = list.Hidden; createdList.ContentTypesEnabled = list.ContentTypesEnabled; createdList.Update(); web.Context.ExecuteQuery(); // TODO: handle 'removedefaultcontenttype' foreach (var ctBinding in list.ContentTypeBindings) { createdList.AddContentTypeToListById(ctBinding.ContentTypeID); if (ctBinding.Default) { createdList.SetDefaultContentTypeToList(ctBinding.ContentTypeID); } } if (list.Fields.Any()) { foreach (var field in list.Fields) { // Double check that the content type did not include the field before adding it in if (!createdList.FieldExistsById(field.SchemaXml.Substring(field.SchemaXml.IndexOf("ID=\"{") + 5, 36))) { var fieldXml = parser.Parse(field.SchemaXml); createdList.Fields.AddFieldAsXml(fieldXml, false, AddFieldOptions.DefaultValue); } } createdList.Update(); web.Context.ExecuteQuery(); } if (list.FieldRefs.Any()) { foreach (var fieldRef in list.FieldRefs) { var field = web.GetFieldById<Field>(fieldRef.ID); if (!createdList.FieldExistsById(fieldRef.ID)) { createdList.Fields.Add(field); } } createdList.Update(); web.Context.ExecuteQuery(); } 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.ExecuteQuery(); } } } }
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"); }
private static void AddViews(ClientContext clientContext, List listToBeReplaced, List newList) { //Delete All Views from New List RemoveDefaultViews_From_NewlyCreatedList(clientContext, listToBeReplaced, newList); //Delete All Views from New List ViewCollection views = listToBeReplaced.Views; clientContext.Load(views, v => v.Include(view => view.Paged, view => view.PersonalView, view => view.ViewQuery, view => view.Title, view => view.RowLimit, view => view.DefaultView, view => view.ViewFields, view => view.Hidden, view => view.ViewType, view => view.DefaultView, view => view.MobileDefaultView)); clientContext.ExecuteQuery(); //Build a list of views which only exist on the source list var viewsToCreate = new List<ViewCreationInformation>(); foreach (View view in listToBeReplaced.Views) { var createInfo = new ViewCreationInformation { Paged = view.Paged, PersonalView = view.PersonalView, Query = view.ViewQuery, Title = view.Title, RowLimit = view.RowLimit, SetAsDefaultView = view.DefaultView, ViewFields = view.ViewFields.ToArray(), ViewTypeKind = GetViewType(view.ViewType) }; //ViewCreationInformation createInfo = new ViewCreationInformation(); //createInfo.Title = view.Title; //createInfo.Paged = view.Paged; //createInfo.PersonalView = view.PersonalView; //createInfo.RowLimit = view.RowLimit; //createInfo.ViewFields = view.ViewFields.ToArray(); //createInfo.ViewTypeKind = GetViewType(view.ViewType); //createInfo.SetAsDefaultView = view.DefaultView; //createInfo.Query = view.ViewQuery; if (!view.Hidden) viewsToCreate.Add(createInfo); } //Create the list that we need to foreach (ViewCreationInformation newView in viewsToCreate) { newList.Views.Add(newView); } newList.Update(); UpdateViewProperties(clientContext, listToBeReplaced, newList); }
private void CreateView(Web web, View view, Microsoft.SharePoint.Client.ViewCollection existingViews, List createdList, PnPMonitoredScope monitoredScope) { try { var viewElement = XElement.Parse(view.SchemaXml); var displayNameElement = viewElement.Attribute("DisplayName"); if (displayNameElement == null) { throw new ApplicationException("Invalid View element, missing a valid value for the attribute DisplayName."); } monitoredScope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstances_Creating_view__0_, displayNameElement.Value); var existingView = existingViews.FirstOrDefault(v => v.Title == displayNameElement.Value); if (existingView != null) { existingView.DeleteObject(); web.Context.ExecuteQueryRetry(); } var viewTitle = displayNameElement.Value; // Type var viewTypeString = viewElement.Attribute("Type") != null ? viewElement.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 = viewElement.Descendants("ViewFields").FirstOrDefault(); if (viewFieldsElement != null) { viewFields = (from field in viewElement.Descendants("ViewFields").Descendants("FieldRef") select field.Attribute("Name").Value).ToArray(); } // Default view var viewDefault = viewElement.Attribute("DefaultView") != null && Boolean.Parse(viewElement.Attribute("DefaultView").Value); // Row limit var viewPaged = true; uint viewRowLimit = 30; var rowLimitElement = viewElement.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 viewElement.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, }; // Allow to specify a custom view url. View url is taken from title, so we first set title to the view url value we need, // create the view and then set title back to the original value var urlAttribute = viewElement.Attribute("Url"); var urlHasValue = urlAttribute != null && !string.IsNullOrEmpty(urlAttribute.Value); if (urlHasValue) { //set Title to be equal to url (in order to generate desired url) viewCI.Title = Path.GetFileNameWithoutExtension(urlAttribute.Value); } var createdView = createdList.Views.Add(viewCI); web.Context.Load(createdView, v => v.Scope, v => v.JSLink, v => v.Title); web.Context.ExecuteQueryRetry(); if (urlHasValue) { //restore original title createdView.Title = viewTitle; createdView.Update(); } // ContentTypeID var contentTypeID = viewElement.Attribute("ContentTypeID") != null ? viewElement.Attribute("ContentTypeID").Value : null; if (!string.IsNullOrEmpty(contentTypeID) && (contentTypeID != BuiltInContentTypeId.System)) { ContentTypeId childContentTypeId = null; if (contentTypeID == BuiltInContentTypeId.RootOfList) { var childContentType = web.GetContentTypeById(contentTypeID); childContentTypeId = childContentType != null ? childContentType.Id : null; } else { childContentTypeId = createdList.ContentTypes.BestMatch(contentTypeID); } if (childContentTypeId != null) { createdView.ContentTypeId = childContentTypeId; createdView.Update(); } } // Default for content type bool parsedDefaultViewForContentType; var defaultViewForContentType = viewElement.Attribute("DefaultViewForContentType") != null ? viewElement.Attribute("DefaultViewForContentType").Value : null; if (!string.IsNullOrEmpty(defaultViewForContentType) && bool.TryParse(defaultViewForContentType, out parsedDefaultViewForContentType)) { createdView.DefaultViewForContentType = parsedDefaultViewForContentType; createdView.Update(); } // Scope var scope = viewElement.Attribute("Scope") != null ? viewElement.Attribute("Scope").Value : null; ViewScope parsedScope = ViewScope.DefaultValue; if (!string.IsNullOrEmpty(scope) && Enum.TryParse<ViewScope>(scope, out parsedScope)) { createdView.Scope = parsedScope; createdView.Update(); } // JSLink var jslinkElement = viewElement.Descendants("JSLink").FirstOrDefault(); if (jslinkElement != null) { var jslink = jslinkElement.Value; if (createdView.JSLink != jslink) { createdView.JSLink = jslink; createdView.Update(); } } createdList.Update(); web.Context.ExecuteQueryRetry(); } catch (Exception ex) { monitoredScope.LogError(CoreResources.Provisioning_ObjectHandlers_ListInstances_Creating_view_failed___0_____1_, ex.Message, ex.StackTrace); throw; } }
void ProvisionSample6(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-Email-Regex-Validator")); web.Context.ExecuteQuery(); List existingList = results.FirstOrDefault(); if (existingList != null) { existingList.DeleteObject(); web.Context.ExecuteQuery(); } //Create list ListCreationInformation creationInfo = new ListCreationInformation(); creationInfo.Title = "CSR-Email-Regex-Validator"; 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.Text + "\" Name=\"Email\" DisplayName=\"Email\" 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"] = "Email address"; item1["Email"] = "*****@*****.**"; item1.Update(); //Create sample view ViewCreationInformation sampleViewCreateInfo = new ViewCreationInformation(); sampleViewCreateInfo.Title = "CSR Sample View"; sampleViewCreateInfo.ViewFields = new string[] { "LinkTitle", "Email" }; sampleViewCreateInfo.SetAsDefaultView = true; Microsoft.SharePoint.Client.View sampleView = newlist.Views.Add(sampleViewCreateInfo); sampleView.Update(); web.Context.Load(newlist, l => l.DefaultNewFormUrl, l => l.DefaultEditFormUrl); web.Context.ExecuteQuery(); //Register JS files via JSLink properties RegisterJStoWebPart(web, newlist.DefaultNewFormUrl, "~sitecollection/Style Library/JSLink-Samples/RegexValidator.js"); RegisterJStoWebPart(web, newlist.DefaultEditFormUrl, "~sitecollection/Style Library/JSLink-Samples/RegexValidator.js"); }