public ProjectDocument(IManager manager, string fileName, Project project) : base(manager, fileName) { mBaseDirectory = Path.GetDirectoryName(fileName); //System.Windows.Forms.Application.StartupPath; mRootItem = new ProjectDocumentItem(this); mProject = project; mImports = new ListCollection<ProjectDocument>(); }
public static void getDataFromSPList(string siteURL, string listName, string userName) { ClientContext clientContext = new ClientContext(siteURL); Web web = clientContext.Web; ListCollection collList = web.Lists; //CamlQuery CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = "<View></View>"; List planlist = collList.GetByTitle(listName); Microsoft.SharePoint.Client.ListItemCollection collListItem = planlist.GetItems(camlQuery); clientContext.Load(collListItem, items => items.Include( item => item.Id, item => item.DisplayName, item => item.HasUniqueRoleAssignments) ); clientContext.ExecuteQuery(); foreach (Microsoft.SharePoint.Client.ListItem olistItem in collListItem) { Console.WriteLine("ID: {0} \nDisplay name: {1} \nUnique role assignments: {2}", olistItem.Id, olistItem.DisplayName, olistItem.HasUniqueRoleAssignments); } clientContext.Load(planlist); clientContext.ExecuteQuery(); Console.WriteLine(planlist.Title.ToString()); Console.WriteLine(planlist.ItemCount.ToString()); Console.ReadKey(); }
public ActionResult Create(Pedidos model) { var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { if (clientContext != null) { Web web = clientContext.Web; clientContext.Load(web); clientContext.ExecuteQuery(); ListCollection lists = web.Lists; clientContext.Load <ListCollection>(lists); clientContext.ExecuteQuery(); var pedidos = lists.GetByTitle("Pedidos"); clientContext.Load(pedidos); ListItemCreationInformation lci = new ListItemCreationInformation(); ListItem pedListItem = pedidos.AddItem(lci); pedListItem["Title"] = model.Cliente; pedListItem["Unidades"] = model.Unidades; pedListItem["Fecha"] = DateTime.Now; var lv = new FieldLookupValue() { LookupId = model.IdProducto }; pedListItem["Producto"] = lv; pedListItem.Update(); clientContext.ExecuteQuery(); } } return(RedirectToAction("Index", new { SPHostUrl = SharePointContext.GetSPHostUrl(HttpContext.Request).AbsoluteUri })); }
private List <T> SelectItems <T>(CamlQuery query) where T : new() { Type entityType = typeof(T); var entities = new List <T>(); try { string listName = EntityHelper.GetInternalNameFromEntityType(entityType); using (var clientContext = GetClientContext()) { Web web = clientContext.Web; ListCollection listCollection = web.Lists; clientContext.Load(listCollection); clientContext.ExecuteQuery(); List list = listCollection.FirstOrDefault(q => q.Title == listName); if (list == null) { throw new ListNotFoundException(); } ListItemCollection items = list.GetItems(query); clientContext.Load(items); clientContext.ExecuteQuery(); foreach (var item in items) { var entity = new T(); StoreFromListItem(entity, item); entities.Add(entity); } } return(entities); } catch (Exception ex) { _log.Error($"Cannot select items from table of entity with type '{entityType.Name}", ex); throw; } }
protected void cmdGetLists_Click(object sender, EventArgs e) { SharePointContext spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { clientContext.Load(clientContext.Web); ListCollection Lists = clientContext.Web.Lists; clientContext.Load(Lists, lists => lists.Where(list => !list.Hidden) .Include(list => list.Title, list => list.DefaultViewUrl)); clientContext.ExecuteQuery(); string html = "<h2>Lists in host web</h2>"; html += "<ul>"; foreach (var list in Lists) { html += "<li>" + list.Title + "</li>"; } html += "</ul>"; placeholderMainContent.Text = html; } }
private void Form1_Load(object sender, EventArgs e) { // ClientContext - Get the context for the SharePoint Site ClientContext clientContext = new ClientContext("http://zf-sp"); // Get the SharePoint web Web web = clientContext.Web; // Get the SharePoint list collection for the web ListCollection listColl = web.Lists; // Retrieve the list collection properties clientContext.Load(listColl); // Execute the query to the server. clientContext.ExecuteQuery(); // Loop through all the list foreach (List list in listColl) { // Display the list title and ID listBox1.Items.Add("List Name: " + list.Title + "; ID: " + list.Id); } }
void WritePermissionsForLists(ClientContext clientContext, User user, Web web) { if (web.HasUniqueRoleAssignments) { WritePermissionsForObject(clientContext, user, web); } // Process lists ListCollection collList = web.Lists; clientContext.Load( collList, lists => lists.Where( list => list.Hidden == false && list.HasExternalDataSource == false).Include( list => list.Title, list => list.ParentWebUrl, list => list.HasUniqueRoleAssignments)); clientContext.ExecuteQuery(); foreach (List list in web.Lists) { if (s_verbose) { if (s_listHasOutput) { WriteLine("<br/>"); } WriteLine(string.Format("\tList {0} \t{1}", list.Title, list.HasUniqueRoleAssignments ? "*Has unique role assignments" : c_InheritsRoleAssignmentsText)); s_newList = true; s_listHasOutput = false; } WritePermissionsForObject(clientContext, user, list); WritePermissionsForListItems(clientContext, user, list); } }
public static async Task <IEnumerable <SharePointList> > GetLists() { ClientContext ctx = await GetClientContext(); ListCollection Lists = ctx.Web.Lists; ctx.Load(Lists, siteLists => siteLists.Where(list => !list.Hidden) .Include(list => list.Id, list => list.Title, list => list.DefaultViewUrl)); ctx.ExecuteQuery(); List <SharePointList> lists = new List <SharePointList>(); foreach (var list in ctx.Web.Lists) { lists.Add(new SharePointList { Id = list.Id.ToString(), Title = list.Title, DefaultViewUrl = siteUrl + "/" + list.DefaultViewUrl }); } ctx.Dispose(); return(lists); }
/// <summary> /// /// </summary> /// <param name="propertyDescriptor"></param> /// <param name="source"></param> /// <returns></returns> protected virtual SqlParameter[] CreateParameters(DbQueryPropertyDescriptor propertyDescriptor) { var _parameters = new ListCollection <SqlParameter>(); if (propertyDescriptor.HasInputDirection && propertyDescriptor.HasOutputDirection) { var _inputName = propertyDescriptor.GetName(DbQueryPropertyDirections.Input); var _outputName = propertyDescriptor.GetName(DbQueryPropertyDirections.Output); if (_inputName.Equals(_outputName)) { _parameters.Add(CreateParameter(propertyDescriptor, _inputName, DbQueryPropertyDirections.InputOutput)); } else { _parameters.Add(CreateParameter(propertyDescriptor, _inputName, DbQueryPropertyDirections.Input)); _parameters.Add(CreateParameter(propertyDescriptor, _outputName, DbQueryPropertyDirections.Output)); } } else if (propertyDescriptor.HasOutputDirection) { var _direction = DbQueryPropertyDirections.Output; var _parameterName = propertyDescriptor.GetName(_direction); _parameters.Add(CreateParameter(propertyDescriptor, _parameterName, _direction)); } else if (propertyDescriptor.HasInputDirection) { var _direction = DbQueryPropertyDirections.Input; var _parameterName = propertyDescriptor.GetName(_direction); _parameters.Add(CreateParameter(propertyDescriptor, _parameterName, _direction)); } return(_parameters.ToArray()); }
public void Counting() { var col = new ListCollection <int, int>(); for (var i = 0; i < 11; ++i) { col.Add(1, 1000 + i); } for (var i = 0; i < 22; ++i) { col.Add(2, 2000 + i); } for (var i = 0; i < 33; ++i) { col.Add(3, 3000 + i); } Assert.Equal(11, col.CountValues(1)); Assert.Equal(22, col.CountValues(2)); Assert.Equal(33, col.CountValues(3)); Assert.Equal(0, col.CountValues(4)); }
public ChatCommand(String commandText) { Command = null; Arguments = new ListCollection <String>(); String[] commandData = commandText.Split(' '); if (commandData.Length <= 0 || commandData[0].Length < 2 || !commandData[0].StartsWith(CommandChar)) { return; } Command = commandData[0].Remove(0, 1).ToLower(); if (commandData.Length <= 1) { return; } for (Int32 i = 1; i <= commandData.Length - 1; i++) { Arguments.Add(commandData[i]); } }
public Dictionary <string, string> LoadList(string list) { var site = ConfigurationManager.AppSettings["SharePointSite"]; ClientContext clientContext = new ClientContext(site); Web oWebsite = clientContext.Web; ListCollection collList = oWebsite.Lists; var spList = collList.GetByTitle(list); var q = new CamlQuery(); ListItemCollection collListItem = spList.GetItems(q); clientContext.Load( collListItem, items => items.Include( item => item["Key"], item => item["Value"])); clientContext.ExecuteQuery(); var dictionary = new Dictionary <string, string>(); object keyName; object valueName; foreach (var item in collListItem) { item.FieldValues.TryGetValue("Key", out keyName); item.FieldValues.TryGetValue("Value", out valueName); dictionary.Add(keyName.ToString(), valueName as string); } return(dictionary); }
/// <summary> /// Function to check whether list is present or not. /// </summary> /// <param name="clientContext">Client context object for SharePoint</param> /// <param name="listsNames">List name</param> /// <returns>Success flag</returns> public static List <string> MatterAssociatedLists(ClientContext clientContext, ReadOnlyCollection <string> listsNames) { List <string> existingLists = new List <string>(); try { if (null != clientContext && null != listsNames) { //ToDo: Chec ListCollection lists = clientContext.Web.Lists; clientContext.Load(lists); clientContext.ExecuteQuery(); existingLists = (from listName in listsNames join item in lists on listName.ToUpper(CultureInfo.InvariantCulture) equals item.Title.ToUpper(CultureInfo.InvariantCulture) select listName).ToList(); } } catch (Exception ex) { throw; } return(existingLists); }
/// <summary> /// Navigate to the "Documents" list. /// </summary> /// <remarks> /// When all folders under "Documents" have been traversed, fire the NewOnekyDriveItems event. /// </remarks> public void Run() { ClientContext clientContext = null; String hostWeb = ""; // Get the top-level Lists collection. ListCollection lists = GetLists(ref clientContext, ref hostWeb); // Get all items under the Documents list. GetItemsInDocumentsList(clientContext, lists.GetByTitle(documentsList), hostWeb); if (NewOneDriveItems != null) { if (_ItemsList.Count == 0) { ItemAttributes itemAttrs = new ItemAttributes(); itemAttrs.FileName = logInfo; _ItemsList.Add(itemAttrs); } OneDriveEventData data = new OneDriveEventData(_ItemsList); NewOneDriveItems(this, data); } }
private static void ScanLists(Web web, List <ContentTypeSpec> contentTypes, List <SiteColumnSpec> siteColumns) { try { ListCollection lists = web.Lists; web.Context.Load(lists); web.Context.ExecuteQuery(); foreach (List list in lists) { // We dont want to abort the entire collection if we get an exception on a given list (e.g., a list definition is missing) try { // scan the list for our custom site columns foreach (SiteColumnSpec sc in siteColumns) { ReportSiteColumnUsage(web, list, sc.Id, sc.Name); } // scan the web for our custom content types; either as is or as parents foreach (ContentTypeSpec ct in contentTypes) { ReportContentTypeUsage(web, list, ct.Id, ct.Name); } } catch (Exception ex) { Logger.LogErrorMessage(String.Format("ScanLists() failed on a list of {0}: Error={1}", web.Url, ex.Message), false); } } } catch (Exception ex) { Logger.LogErrorMessage(String.Format("ScanLists() failed for {0}: Error={1}", web.Url, ex.Message), false); } }
public async Task <ActionResult> Create(string selectedSharePointList) { var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); using (var cc = spContext.CreateUserClientContextForSPHost()) { if (cc != null) { // Hookup event to capture access token cc.ExecutingWebRequest += Cc_ExecutingWebRequest; ListCollection lists = cc.Web.Lists; Guid listId = new Guid(selectedSharePointList); IEnumerable <List> sharePointLists = cc.LoadQuery <List>(lists.Where(lst => lst.Id == listId)); cc.Load(cc.Web, w => w.Url); cc.ExecuteQueryRetry(); WebHookManager webHookManager = new WebHookManager(); var res = await webHookManager.AddListWebHookAsync(cc.Web.Url, listId.ToString(), CloudConfigurationManager.GetSetting("WebHookEndPoint"), this.accessToken); // persist the latest changetoken of the list when we create a new webhook. This allows use to only grab the changes as of web hook creation when the first notification comes in using (SharePointWebHooks dbContext = new SharePointWebHooks()) { dbContext.ListWebHooks.Add(new ListWebHooks() { Id = new Guid(res.Id), ListId = listId, LastChangeToken = sharePointLists.FirstOrDefault().CurrentChangeToken.StringValue, }); var saveResult = await dbContext.SaveChangesAsync(); } } } return(RedirectToAction("Index", "Home", new { SPHostUrl = Request.QueryString["SPHostUrl"] })); }
public override void UpdateListitemLookup(List targetList, ListCollection webListCollection, ContentType contentType) { var relatedList = webListCollection.GetByTitle(DependListTitle); if (relatedList == null) { return; } var fields = targetList.Fields; context.Load(relatedList); context.ExecuteQuery(); string schema = $"<Field ID='{Guid.NewGuid()}' Type='Lookup' Name='{DependListTitle}' StaticName='Project' DisplayName='Project' List='{relatedList.Id}' ShowField='ProjectName' />"; Field newField = fields.AddFieldAsXml(schema, true, AddFieldOptions.AddFieldInternalNameHint); newField.SetShowInEditForm(true); newField.SetShowInNewForm(true); context.Load(newField); UpdateFieldToContentType(contentType, newField, "Project"); context.Load(fields); context.ExecuteQuery(); }
private void VisioScanJob_TimerJobRun(object sender, OfficeDevPnP.Core.Framework.TimerJobs.TimerJobRunEventArgs e) { // Validate ClientContext objects if (e.WebClientContext == null || e.SiteClientContext == null) { ScanError error = new ScanError() { Error = "No valid ClientContext objects", SiteURL = e.Url, SiteColUrl = e.Url }; this.ScanErrors.Push(error); Console.WriteLine("Error for site {1}: {0}", "No valid ClientContext objects", e.Url); // bail out return; } // thread safe increase of the sites counter IncreaseScannedSites(); try { // Set the first site collection done flag + perform telemetry SetFirstSiteCollectionDone(e.WebClientContext, this.Name); // Manually iterate over the content IEnumerable <string> expandedSites = e.SiteClientContext.Site.GetAllSubSites(); bool isFirstSiteInList = true; string siteCollectionUrl = ""; List <Dictionary <string, string> > pageSearchResults = null; foreach (string site in expandedSites) { try { // thread safe increase of the webs counter IncreaseScannedWebs(); // Clone the existing ClientContext for the sub web using (ClientContext ccWeb = e.SiteClientContext.Clone(site)) { Console.WriteLine("Processing site {0}...", site); // Allow max server time out, might be needed for sites having a lot of users ccWeb.RequestTimeout = Timeout.Infinite; if (isFirstSiteInList) { // Perf optimization: do one call per site to load all the needed properties var spSite = (ccWeb as ClientContext).Site; ccWeb.Load(spSite, p => p.Url); ccWeb.ExecuteQueryRetry(); isFirstSiteInList = false; } ListCollection listCollection = ccWeb.Web.Lists; ccWeb.Load(listCollection, coll => coll.Include(li => li.Title, li => li.Hidden, li => li.DefaultViewUrl, li => li.BaseTemplate, li => li.RootFolder)); ccWeb.ExecuteQueryRetry(); // Do things only once per site collection if (string.IsNullOrEmpty(siteCollectionUrl)) { // Cross check Url property availability ccWeb.Site.EnsureProperty(s => s.Url); siteCollectionUrl = ccWeb.Site.Url; // Site scan SiteAnalyzer siteAnalyzer = new SiteAnalyzer(site, siteCollectionUrl, this); var siteScanDuration = siteAnalyzer.Analyze(ccWeb); pageSearchResults = siteAnalyzer.PageSearchResults; } VisioWebPartAnalyzer visioWebPartAnalyzer = new VisioWebPartAnalyzer(site, siteCollectionUrl, this, pageSearchResults); visioWebPartAnalyzer.Analyze(ccWeb); } } catch (Exception ex) { ScanError error = new ScanError() { Error = ex.Message, SiteColUrl = e.Url, SiteURL = site, Field1 = "MainWebLoop", Field2 = ex.StackTrace, }; this.ScanErrors.Push(error); Console.WriteLine("Error for site {1}: {0}", ex.Message, site); } } } catch (Exception ex) { ScanError error = new ScanError() { Error = ex.Message, SiteColUrl = e.Url, SiteURL = e.Url, Field1 = "MainSiteLoop", Field2 = ex.StackTrace, }; this.ScanErrors.Push(error); Console.WriteLine("Error for site {1}: {0}", ex.Message, e.Url); } // Output the scanning progress try { TimeSpan ts = DateTime.Now.Subtract(this.StartTime); Console.WriteLine($"Thread: {Thread.CurrentThread.ManagedThreadId}. Processed {this.ScannedSites} of {this.SitesToScan} site collections ({Math.Round(((float)this.ScannedSites / (float)this.SitesToScan) * 100)}%). Process running for {ts.Days} days, {ts.Hours} hours, {ts.Minutes} minutes and {ts.Seconds} seconds."); } catch (Exception ex) { Console.WriteLine($"Error showing progress: {ex.ToString()}"); } }
public static Dictionary<String, String> TokenizeWorkflowDefinitionProperties(this IDictionary<String, String> properties, ListCollection lists) { Dictionary<String, String> result = new Dictionary<String, String>(); foreach (var p in properties) { switch (p.Key) { case "RestrictToScope": case "HistoryListId": case "TaskListId": if (!String.IsNullOrEmpty(p.Value)) { result.Add(p.Key, String.Format("{{listid:{0}}}", lists.First(l => l.Id == Guid.Parse(p.Value)).Title)); } break; //case "SubscriptionId": //case "ServerUrl": //case "EncodedAbsUrl": //case "MetaInfo": default: result.Add(p.Key, p.Value); break; } } return (result); }
public virtual void UpdateListitemLookup(List list, ListCollection webListCollection, ContentType contentType) { }
/// <summary> /// Process the request /// </summary> public override void ExecuteCmdlet() { base.ExecuteCmdlet(); if (this.ClientContext == null) { LogWarning("Invalid client context, configure the service to run again"); return; } // obtain CSOM object for host web Web hostWeb = this.ClientContext.Web; // check to see if Picture library named Photos already exists ListCollection allLists = hostWeb.Lists; IEnumerable <List> foundLists = this.ClientContext.LoadQuery(allLists.Where(list => list.Title == "Site Assets")); this.ClientContext.ExecuteQuery(); List siteAssetsLibrary = foundLists.FirstOrDefault(); if (siteAssetsLibrary == null) { LogWarning("Failed to find site assets"); return; } var appFileFolder = string.Format("{0}\\SiteAssets", this.SiteContent); if (!System.IO.Directory.Exists(appFileFolder)) { LogWarning("Site Assets Folder {0} does not exist.", appFileFolder); return; } var searchPattern = "*"; if (!string.IsNullOrEmpty(this.SiteActionFile)) { searchPattern = this.SiteActionFile; if (this.SiteActionFile.IndexOf(@"\") > -1) { searchPattern = this.SiteActionFile.Substring(0, this.SiteActionFile.IndexOf(@"\")); } } var appDirectories = System.IO.Directory.GetDirectories(appFileFolder, searchPattern, System.IO.SearchOption.TopDirectoryOnly); foreach (var appDirectory in appDirectories) { var appDirectoryInfo = new System.IO.DirectoryInfo(appDirectory); string folder = appDirectoryInfo.Name, folderPath = appDirectoryInfo.FullName; var searchPatternFiles = "*"; if (!string.IsNullOrEmpty(this.SiteActionFile)) { if (this.SiteActionFile.IndexOf(@"\") > -1) { searchPatternFiles = string.Format("*{0}*", this.SiteActionFile.Substring(this.SiteActionFile.IndexOf(@"\") + 1)); } } var appRootFolder = siteAssetsLibrary.RootFolder.EnsureFolder(folder); var siteAssetsFiles = System.IO.Directory.GetFiles(folderPath, searchPatternFiles); LogVerbose("Now searching folder {0} and uploading files {1}", folderPath, siteAssetsFiles.Count()); // enmuerate through each file in folder foreach (string filePath in siteAssetsFiles) { if (this.ShouldProcess(string.Format("---------------- Now uploading file {0}", filePath))) { // upload each file to library in host web byte[] fileContent = System.IO.File.ReadAllBytes(filePath); FileCreationInformation fileInfo = new FileCreationInformation(); fileInfo.Content = fileContent; fileInfo.Overwrite = true; fileInfo.Url = System.IO.Path.GetFileName(filePath); File newFile = appRootFolder.Files.Add(fileInfo); // commit changes to library this.ClientContext.Load(newFile, nf => nf.ServerRelativeUrl, nf => nf.Length); this.ClientContext.ExecuteQuery(); } } } }
public ListDictionary(Func <IList <TValue> > listConstructor) { _dict = new Dictionary <TKey, IList <TValue> >(); _listConstructor = (listConstructor != null) ? listConstructor : DefaultListConstructor; _listRedirectColl = new ListCollection(this); }
/// <summary> /// To update List Collection /// </summary> /// <param name="practiceGroupFieldName">Practice Group field name</param> /// <param name="areaOfLawFieldName">Area of Law field name</param> /// <param name="subareaOfLawColumnName">Sub Area of Law column</param> /// <param name="practiceGroups">Practice groups</param> /// <param name="clientContext">Client Context</param> /// <param name="client">Client object</param> /// <param name="collection">List collection</param> private static void UpdateListCollection(string practiceGroupFieldName, string areaOfLawFieldName, string subareaOfLawColumnName, List<PracticeGroup> practiceGroups, ClientContext clientContext, Client client, ListCollection collection) { string matterCenterDefaultContentType = string.Empty; // Display the group name bool isUpdate = false; foreach (List list in collection) { try { if (list.RootFolder.Properties.FieldValues.ContainsKey(Constants.MatterKey)) { if (list.RootFolder.Properties.FieldValues.ContainsKey(Constants.MatterContentTypeKey)) { matterCenterDefaultContentType = WebUtility.HtmlDecode(Convert.ToString(list.RootFolder.Properties.FieldValues[Constants.MatterContentTypeKey], CultureInfo.InvariantCulture)); isUpdate = Utility.UpdateMatterBasedOnContentType(clientContext, list, practiceGroups, matterCenterDefaultContentType, client.Name, 1); if (isUpdate) { Console.WriteLine(string.Format(CultureInfo.InvariantCulture, Constants.SuccessMessageMatter, list.Title)); } } else { string areaOfLawStringTrimed, practiceGroupStringTrimed; string[] subAreaOfLawString = Convert.ToString(list.RootFolder.Properties.FieldValues[subareaOfLawColumnName], CultureInfo.InvariantCulture).Split(';'); string[] areaOfLawString = Convert.ToString(list.RootFolder.Properties.FieldValues[areaOfLawFieldName], CultureInfo.InvariantCulture).Split(';'); string[] practiceGroupString = Convert.ToString(list.RootFolder.Properties.FieldValues[practiceGroupFieldName], CultureInfo.InvariantCulture).Split(';'); ContentTypeCollection currentContentTypeOrder = list.ContentTypes; clientContext.Load(currentContentTypeOrder); clientContext.ExecuteQuery(); string subAreaOfLawStringTrimed = WebUtility.HtmlDecode(currentContentTypeOrder[0].Name.ToString()); int iPosition = Array.IndexOf(subAreaOfLawString, subAreaOfLawStringTrimed); if (-1 == iPosition) { areaOfLawStringTrimed = WebUtility.HtmlDecode(areaOfLawString[0]); practiceGroupStringTrimed = WebUtility.HtmlDecode(practiceGroupString[0]); } else { areaOfLawStringTrimed = WebUtility.HtmlDecode(areaOfLawString[iPosition]); practiceGroupStringTrimed = WebUtility.HtmlDecode(practiceGroupString[iPosition]); } if (!(string.IsNullOrWhiteSpace(subAreaOfLawStringTrimed) || (string.IsNullOrWhiteSpace(areaOfLawStringTrimed)) || (string.IsNullOrWhiteSpace(practiceGroupStringTrimed)))) { isUpdate = Utility.UpdateMatterBasedOnContentType(clientContext, list, practiceGroups, subAreaOfLawStringTrimed, client.Name, 2); if (isUpdate) { Console.WriteLine(string.Format(CultureInfo.InvariantCulture, Constants.SuccessMessageMatter, list.Title)); } } } } else { Console.WriteLine(string.Format(CultureInfo.InvariantCulture, Constants.SkippedMatterMessageMatter, list.Title)); } } catch (Exception exception) { Console.WriteLine(string.Format(CultureInfo.InvariantCulture, Constants.ClientFailureMessage, client.Name, exception.Message)); } } }
void Options_ItemAdded(ListCollection <IOptions> sender, IOptions item) { Load(item); Store(item); }
private void GetListByNameOrGuid(string listGuid, string listName) { txt_Guid.Text = ""; txt_Name.Text = ""; // Store loop counter for rows added to the data grid view int i = 0; // If we find a GUID, there will only be one bool foundGuid = false; // Store variables for field values string defaultViewUrl = null; string defaultViewTitle = null; string viewCount = null; string fieldCount = null; string itemCount = null; string listType = null; string siteName = null; string siteAddress = null; string listTitle = null; // Open the List form frm_Data_List listForm = OpenForm("", "", this.Name, 1000, 500); // Show the Site Name column listForm.dgv_Data.Columns["siteName"].Visible = true; // Hide the Site Address column listForm.dgv_Data.Columns["siteAddress"].Visible = false; // Loop through each row of the data grid view foreach (DataGridViewRow row in dgv_Data.Rows) { // If we find a GUID, there will only be one foundGuid = false; // Store the Site URL to get the Client Context string siteUrl = row.Cells[5].Value.ToString(); // Select the row in the data grid view for visual effect row.Selected = true; // Do this or it won't show the selected record dgv_Data.Refresh(); // Get the Client Context ClientContext clientContext = SharePoint.GetClient(siteUrl, frm_Main_Menu.username, frm_Main_Menu.password); // Store the lists ListCollection collList = clientContext.Web.Lists; // Load lists clientContext.Load(collList); // Execute the query to the server clientContext.ExecuteQuery(); // Loop through each list to check against Name (i.e. Title) or GUID foreach (SP.List oList in collList) { // Variable to check if we need to add a row bool addRow = false; // If we have a GUID, check the GUID if (listGuid != "") { // Check the GUID if (oList.Id.ToString() == listGuid) { // Select the cell to indicate a find row.Cells[1].Selected = true; // Set the variables foundGuid = true; addRow = true; } } // We are checking name else { // Do a contains for basic "fuzzy" matching if (oList.Title.ToLower().Contains(listName.ToLower())) { // Select the cell to indicate a find row.Cells[1].Selected = true; // Set the variable to add a row addRow = true; } } // Check if we are needing to add a row to the data grid view if (addRow) { // Increment counter i++; // Load lists clientContext.Load(oList, l => l.SchemaXml); // Execute the query to the server clientContext.ExecuteQuery(); // Set the field-related vairables SetFieldVars(clientContext, oList, listForm.dgv_Data, ref fieldCount); // Set the view-related variables SetViewVars(clientContext, oList, listForm.dgv_Data, ref defaultViewUrl, ref defaultViewTitle, ref viewCount); // Set other variables itemCount = oList.ItemCount.ToString(); listType = GetBaseTypeDescription(oList.BaseType); siteAddress = row.Cells[5].Value.ToString(); listTitle = oList.Title; // Find the full Site Name that the List belongs to if (row.Cells[2].Value != null) { siteName = row.Cells[2].Value.ToString() + " --> " + row.Cells[1].Value.ToString(); } else { siteName = row.Cells[1].Value.ToString(); } // Add a row to the data grid view listForm.AddRow ( i.ToString(), siteName, siteAddress, listTitle, oList.Description, listType, oList.EnableVersioning, oList.MajorVersionLimit, defaultViewTitle, fieldCount, viewCount, itemCount, !oList.DisableGridEditing, oList.Id.ToString(), oList.Created.ToString(), defaultViewUrl, oList.SchemaXml.ToString() ); lbl_Row_Count.Text = i.ToString() + " record(s) found"; lbl_Row_Count.Refresh(); // Show the form if it is still invisible if (listForm.Visible == false) { listForm.Show(); } // Refresh it for visual effects listForm.Refresh(); // Leave if the addition was the result of a GUID match if (foundGuid == true) { break; } } } // Leave if the addition was the result of a GUID match if (foundGuid == true) { break; } } if (i > 0) { if (foundGuid == true) { MessageBox.Show("Found list '" + listTitle + "' with GUID " + listGuid); } else { MessageBox.Show("Found " + i + " list(s) matching the name '" + listName + "'"); } } else { MessageBox.Show("Could not find a match"); } }
public static Dictionary <String, String> TokenizeWorkflowDefinitionProperties(this IDictionary <String, String> properties, ListCollection lists) { Dictionary <String, String> result = new Dictionary <String, String>(); foreach (var p in properties) { switch (p.Key) { case "RestrictToScope": case "HistoryListId": case "TaskListId": if (!String.IsNullOrEmpty(p.Value)) { var list = lists.FirstOrDefault(l => l.Id == Guid.Parse(p.Value)); if (list != null) { result.Add(p.Key, String.Format("{{listid:{0}}}", list.Title)); } } break; //case "SubscriptionId": //case "ServerUrl": //case "EncodedAbsUrl": //case "MetaInfo": default: result.Add(p.Key, p.Value); break; } } return(result); }
public static Dictionary <String, String> TokenizeWorkflowSubscriptionProperties(this IDictionary <String, String> properties, ListCollection lists) { Dictionary <String, String> result = new Dictionary <String, String>(); foreach (var p in properties) { switch (p.Key) { case "TaskListId": case "HistoryListId": if (!String.IsNullOrEmpty(p.Value)) { var list = lists.FirstOrDefault(l => l.Id == Guid.Parse(p.Value)); if (list != null) { result.Add(p.Key, String.Format("{{listid:{0}}}", list.Title)); } } break; //case "Microsoft.SharePoint.ActivationProperties.ListId": //case "SharePointWorkflowContext.Subscription.Id": //case "CurrentWebUri": //case "SharePointWorkflowContext.Subscription.EventSourceId": //case "SharePointWorkflowContext.Subscription.EventType": //case "SharePointWorkflowContext.ActivationProperties.SiteId": //case "SharePointWorkflowContext.ActivationProperties.WebId": //case "ScopeId": default: result.Add(p.Key, p.Value); break; } } return(result); }
private bool IsLibraryExist(string pageLibraryName, ListCollection collList) { foreach (List oList in collList) { if (oList.Title.Equals(pageLibraryName)) { return true; } } return false; }
private void ProcessAction(List <Web> webs) { bool processAction; int webCount = webs.Count; for (int webIndex = 0; webIndex < webCount; webIndex++) { Web currentWeb = webs[webIndex]; //Update current connection context to the web that is beeing process //So commands like Get-PnPList returns the correct list for the current web beeing proccess PnPConnection.Current.Context = (ClientContext)currentWeb.Context; currentWeb.LoadProperties(_webActions.Properties); UpdateWebProgressBar(webs, webIndex, webCount, 0, _totalExecutionTimeStopWatch); if (!_webActions.ShouldProcessAnyAction(currentWeb)) { continue; } processAction = ProcessAction(currentWeb, GetTitle, _webActions.Properties, _webActions.ShouldProcessAction, _webActions.Action, ref _currentWebsProcessed, ref _averageWebTime, ref _averageShouldProcessWebTime); if (!processAction) { continue; } if (_listActions.HasAnyAction || _listItemActions.HasAnyAction) { ListCollection lists = currentWeb.Lists; int listCount = lists.Count; for (int listIndex = 0; listIndex < listCount; listIndex++) { List currentList = lists[listIndex]; currentList.LoadProperties(_listActions.Properties); if (_isListNameSpecified && !currentList.Title.Equals(_listName, StringComparison.CurrentCultureIgnoreCase)) { continue; } UpdateWebProgressBar(webs, webIndex, webCount, listIndex, _totalExecutionTimeStopWatch); UpdateListProgressBar(lists, listIndex, listCount); processAction = ProcessAction(currentList, GetTitle, _listActions.Properties, _listActions.ShouldProcessAction, _listActions.Action, ref _currentListsProcessed, ref _averageListTime, ref _averageShouldProcessListTime); if (!processAction) { continue; } if (_listItemActions.HasAnyAction) { ListItemCollection listItems = currentList.GetItems(CamlQuery.CreateAllItemsQuery()); currentList.Context.Load(listItems); currentList.Context.ExecuteQueryRetry(); int listItemCount = listItems.Count; for (int listItemIndex = 0; listItemIndex < listItemCount; listItemIndex++) { ListItem currentListItem = listItems[listItemIndex]; currentListItem.LoadProperties(_listItemActions.Properties); WriteIterationProgress(ListItemProgressBarId, ListProgressBarId, "Iterating list items", GetTitle(currentListItem), listItemIndex, listItemCount, CalculateRemainingTimeForListItems(listItemCount, listItemIndex)); ProcessAction(currentListItem, GetTitle, _listItemActions.Properties, _listItemActions.ShouldProcessAction, _listItemActions.Action, ref _currentListItemsProcessed, ref _averageListItemTime, ref _averageShouldProcessListItemTime); } CompleteProgressBar(ListItemProgressBarId); } processAction = ProcessAction(currentList, GetTitle, _listActions.Properties, _listActions.ShouldProcessPostAction, _listActions.PostAction, ref _currentPostListsProcessed, ref _averagePostListTime, ref _averageShouldProcessPostListTime); } CompleteProgressBar(ListProgressBarId); } processAction = ProcessAction(currentWeb, GetTitle, _webActions.Properties, _webActions.ShouldProcessPost, _webActions.PostAction, ref _currentPostWebsProcessed, ref _averagePostWebTime, ref _averageShouldProcessPostWebTime); } CompleteProgressBar(WebProgressBarId); }
protected List FindListByTitle(ListCollection listCollection, string listTitle) { foreach (var list in listCollection) { if (System.String.Compare(list.Title, listTitle, System.StringComparison.OrdinalIgnoreCase) == 0) return list; } return null; }
public static Dictionary<String, String> TokenizeWorkflowSubscriptionProperties(this IDictionary<String, String> properties, ListCollection lists) { Dictionary<String, String> result = new Dictionary<String, String>(); foreach (var p in properties) { switch (p.Key) { case "TaskListId": case "HistoryListId": if (!String.IsNullOrEmpty(p.Value)) { result.Add(p.Key, String.Format("{{listid:{0}}}", lists.First(l => l.Id == Guid.Parse(p.Value)).Title)); } break; //case "Microsoft.SharePoint.ActivationProperties.ListId": //case "SharePointWorkflowContext.Subscription.Id": //case "CurrentWebUri": //case "SharePointWorkflowContext.Subscription.EventSourceId": //case "SharePointWorkflowContext.Subscription.EventType": //case "SharePointWorkflowContext.ActivationProperties.SiteId": //case "SharePointWorkflowContext.ActivationProperties.WebId": //case "ScopeId": default: result.Add(p.Key, p.Value); break; } } return (result); }
private string ParseFieldSchema(string schemaXml, ListCollection lists) { foreach (var list in lists) { schemaXml = Regex.Replace(schemaXml, list.Id.ToString(), string.Format("{{listid:{0}}}", list.Title), RegexOptions.IgnoreCase); } return schemaXml; }
private void AddLists(string siteName, string siteUrl, frm_Data_List listForm) { ClientContext clientContext = SharePoint.GetClient(siteUrl, frm_Main_Menu.username, frm_Main_Menu.password); ListCollection collList = SharePoint.GetLists(clientContext); // Initialise row counter int i = 0; foreach (SP.List oList in collList) { // Load lists clientContext.Load(oList, l => l.SchemaXml); // Execute the query to the server clientContext.ExecuteQuery(); string defaultViewUrl = null; string defaultViewTitle = null; string viewCount = null; string fieldCount = null; string itemCount = oList.ItemCount.ToString(); string listType = GetBaseTypeDescription(oList.BaseType); SetFieldVars(clientContext, oList, listForm.dgv_Data, ref fieldCount); SetViewVars(clientContext, oList, listForm.dgv_Data, ref defaultViewUrl, ref defaultViewTitle, ref viewCount); // Increment counter i++; //oList.DisableGridEditing = (listType == "List"); //oList.Update(); listForm.AddRow ( i.ToString(), siteName, siteUrl, oList.Title, oList.Description, listType, oList.EnableVersioning, oList.MajorVersionLimit, defaultViewTitle, fieldCount, viewCount, itemCount, !oList.DisableGridEditing, oList.Id.ToString(), oList.Created.ToString(), defaultViewUrl, oList.SchemaXml.ToString() ); lbl_Row_Count.Text = i.ToString() + " record(s) found"; lbl_Row_Count.Refresh(); if (i >= nud_Row_Limit.Value && nud_Row_Limit.Value != 0) { break; } } //clientContext.ExecuteQuery(); }
private ListInstance ExtractFields(Web web, List siteList, List<FieldRef> contentTypeFields, ListInstance list, ListCollection lists) { var siteColumns = web.Fields; web.Context.Load(siteColumns, scs => scs.Include(sc => sc.Id)); web.Context.ExecuteQueryRetry(); var allowedFields = siteList.Fields.Where(field => !(BuiltInFieldId.Contains(field.Id) && field.Hidden)); foreach (var field in allowedFields) { if (siteColumns.FirstOrDefault(sc => sc.Id == field.Id) != null) { var addField = true; if (siteList.ContentTypesEnabled && contentTypeFields.FirstOrDefault(c => c.Id == field.Id) == null) { if (contentTypeFields.FirstOrDefault(c => c.Id == field.Id) == null) { addField = false; } } var fieldElement = XElement.Parse(field.SchemaXml); var sourceId = fieldElement.Attribute("SourceID") != null ? fieldElement.Attribute("SourceID").Value : null; if (sourceId != null && sourceId == "http://schemas.microsoft.com/sharepoint/v3") { if (field.InternalName == "Editor" || field.InternalName == "Author" || field.InternalName == "Title" || field.InternalName == "ID" || field.InternalName == "Created" || field.InternalName == "Modified" || field.InternalName == "Attachments" || field.InternalName == "_UIVersionString" || field.InternalName == "DocIcon" || field.InternalName == "LinkTitleNoMenu" || field.InternalName == "LinkTitle" || field.InternalName == "Edit" || field.InternalName == "AppAuthor" || field.InternalName == "AppEditor" || field.InternalName == "ContentType" || field.InternalName == "ItemChildCount" || field.InternalName == "FolderChildCount" || field.InternalName == "LinkFilenameNoMenu" || field.InternalName == "LinkFilename" || field.InternalName == "_CopySource" || field.InternalName == "ParentVersionString" || field.InternalName == "ParentLeafName" || field.InternalName == "_CheckinComment" || field.InternalName == "FileLeafRef" || field.InternalName == "FileSizeDisplay" || field.InternalName == "Preview" || field.InternalName == "ThumbnailOnForm") { addField = false; } } if (addField) { list.FieldRefs.Add(new FieldRef(field.InternalName) { Id = field.Id, DisplayName = field.Title, Required = field.Required, Hidden = field.Hidden, }); if (field.TypeAsString.StartsWith("TaxonomyField")) { // find the corresponding taxonomy field and include it anyway var taxField = (TaxonomyField)field; taxField.EnsureProperties(f => f.TextField, f => f.Id); var noteField = siteList.Fields.GetById(taxField.TextField); web.Context.Load(noteField, nf => nf.Id, nf => nf.Title, nf => nf.Required, nf => nf.Hidden, nf => nf.InternalName); web.Context.ExecuteQueryRetry(); list.FieldRefs.Insert(0, new FieldRef(noteField.InternalName) { Id = noteField.Id, DisplayName = noteField.Title, Required = noteField.Required, Hidden = noteField.Hidden }); } } } else { var schemaXml = ParseFieldSchema(field.SchemaXml, lists); var fieldElement = XElement.Parse(field.SchemaXml); var listId = fieldElement.Attribute("List") != null ? fieldElement.Attribute("List").Value : null; if (listId == null) list.Fields.Add((new Model.Field { SchemaXml = field.SchemaXml })); else { var listIdValue = Guid.Empty; if (Guid.TryParse(listId, out listIdValue)) { var sourceList = lists.AsEnumerable().Where(l => l.Id == listIdValue).FirstOrDefault(); if (sourceList != null) fieldElement.Attribute("List").SetValue(String.Format("{{listid:{0}}}", sourceList.Title)); } list.Fields.Add(new Model.Field { SchemaXml = fieldElement.ToString() }); } if (field.TypeAsString.StartsWith("TaxonomyField")) { // find the corresponding taxonomy field and include it anyway var taxField = (TaxonomyField)field; taxField.EnsureProperties(f => f.TextField, f => f.Id); var noteField = siteList.Fields.GetById(taxField.TextField); web.Context.Load(noteField, nf => nf.SchemaXml); web.Context.ExecuteQueryRetry(); var noteSchemaXml = XElement.Parse(noteField.SchemaXml); noteSchemaXml.Attribute("SourceID").Remove(); list.Fields.Insert(0, new Model.Field { SchemaXml = ParseFieldSchema(noteSchemaXml.ToString(), lists) }); } } } return list; }
public ListDictionary() { _dict = new Dictionary <TKey, IList <TValue> >(); _listConstructor = DefaultListConstructor; _listRedirectColl = new ListCollection(this); }
public static string TokenizeListIdProperty(string listId, ListCollection lists) { var returnValue = listId; var list = lists.FirstOrDefault(l => l.Id == Guid.Parse(listId)); if (list != null) { returnValue = String.Format("{{listid:{0}}}", list.Title); } return returnValue; }
private void SetIncludeValues(Book book) { ListCollection.SetAllValue(book.Genres, book.Languages, book.Translators); }
public static String SaveXamlToFile(this String xaml, Guid id, OfficeDevPnP.Core.Framework.Provisioning.Connectors.FileConnectorBase connector, ListCollection lists) { // Tokenize XAML to replace any ListId attribute with the corresponding token XElement xamlDocument = XElement.Parse(xaml); var elements = (IEnumerable)xamlDocument.XPathEvaluate("//child::*[@ListId]"); if (elements != null) { foreach (var element in elements.Cast<XElement>()) { var listId = element.Attribute("ListId").Value; element.SetAttributeValue("ListId", TokenizeListIdProperty(listId, lists)); } xaml = xamlDocument.ToString(); } using (Stream mem = new MemoryStream()) { using (StreamWriter sw = new StreamWriter(mem, Encoding.Unicode, 2048, true)) { sw.Write(xaml); } mem.Position = 0; String xamlFileName = String.Format("{0}.xaml", id.ToString()); connector.SaveFileStream(xamlFileName, mem); return (xamlFileName); } }
public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo) { using (var scope = new PnPMonitoredScope(this.Name)) { var clientSidePageContentsHelper = new ClientSidePageContentsHelper(); // Extract the Home Page web.EnsureProperties(w => w.RootFolder.WelcomePage, w => w.ServerRelativeUrl, w => w.Url); var homePageUrl = web.RootFolder.WelcomePage; // Get pages library List sitePagesLibrary = null; try { ListCollection listCollection = web.Lists; listCollection.EnsureProperties(coll => coll.Include(li => li.BaseTemplate, li => li.RootFolder)); sitePagesLibrary = listCollection.Where(p => p.BaseTemplate == (int)ListTemplateType.WebPageLibrary).FirstOrDefault(); } catch { // fall back in case of exception when the site has been incorrectly provisioned which can cause access issues on lists/libraries. sitePagesLibrary = web.Lists.GetByTitle("Site Pages"); sitePagesLibrary.EnsureProperties(l => l.BaseTemplate, l => l.RootFolder); } if (sitePagesLibrary != null) { var baseUrl = $"{sitePagesLibrary.RootFolder.ServerRelativeUrl}/"; var templateFolderName = PnP.Framework.Pages.ClientSidePage.DefaultTemplatesFolder;// string.Empty; var templateFolderString = sitePagesLibrary.GetPropertyBagValueString(TemplatesFolderGuid, null); Guid.TryParse(templateFolderString, out Guid templateFolderGuid); if (templateFolderGuid != Guid.Empty) { try { var templateFolder = ((ClientContext)sitePagesLibrary.Context).Web.GetFolderById(templateFolderGuid); templateFolderName = templateFolder.EnsureProperty(f => f.Name); } catch { //eat it and continue with default name } } CamlQuery query = new CamlQuery { ViewXml = CAMLQueryByExtension }; var pages = sitePagesLibrary.GetItems(query); web.Context.Load(pages); web.Context.ExecuteQueryRetry(); if (pages.FirstOrDefault() != null) { // Prep a list of pages to export allowing us hanlde translations List <PageToExport> pagesToExport = new List <PageToExport>(); foreach (var page in pages) { PageToExport pageToExport = new PageToExport() { ListItem = page, IsTranslation = false, TranslatedLanguages = null, }; // If multi-lingual is enabled these fields will be available on the SitePages library if (page.FieldValues.ContainsKey(SPIsTranslation) && page[SPIsTranslation] != null && !string.IsNullOrEmpty(page[SPIsTranslation].ToString())) { if (bool.TryParse(page[SPIsTranslation].ToString(), out bool isTranslation)) { pageToExport.IsTranslation = isTranslation; } } if (page.FieldValues.ContainsKey(PageIDField) && page[PageIDField] != null && !string.IsNullOrEmpty(page[PageIDField].ToString())) { pageToExport.PageId = Guid.Parse(page[PageIDField].ToString()); } if (page.FieldValues.ContainsKey(SPTranslationSourceItemId) && page[SPTranslationSourceItemId] != null && !string.IsNullOrEmpty(page[SPTranslationSourceItemId].ToString())) { pageToExport.SourcePageId = Guid.Parse(page[SPTranslationSourceItemId].ToString()); } if (page.FieldValues.ContainsKey(SPTranslationLanguage) && page[SPTranslationLanguage] != null && !string.IsNullOrEmpty(page[SPTranslationLanguage].ToString())) { pageToExport.Language = page[SPTranslationLanguage].ToString(); } if (page.FieldValues.ContainsKey(SPTranslatedLanguages) && page[SPTranslatedLanguages] != null && !string.IsNullOrEmpty(page[SPTranslatedLanguages].ToString())) { pageToExport.TranslatedLanguages = new List <string>(page[SPTranslatedLanguages] as string[]); } string pageUrl = null; string pageName = ""; if (page.FieldValues.ContainsKey(FileRefField) && !String.IsNullOrEmpty(page[FileRefField].ToString())) { pageUrl = page[FileRefField].ToString(); pageName = page[FileLeafRefField].ToString(); } else { //skip page continue; } var isTemplate = false; // Is this page a template? if (pageUrl.IndexOf($"/{templateFolderName}/", StringComparison.InvariantCultureIgnoreCase) > -1) { isTemplate = true; } // Is this page the web's home page? bool isHomePage = false; if (pageUrl.EndsWith(homePageUrl, StringComparison.InvariantCultureIgnoreCase)) { isHomePage = true; } // Get the name of the page, including the folder name pageName = Regex.Replace(pageUrl, baseUrl, "", RegexOptions.IgnoreCase); pageToExport.IsHomePage = isHomePage; pageToExport.IsTemplate = isTemplate; pageToExport.PageName = pageName; pageToExport.PageUrl = pageUrl; pagesToExport.Add(pageToExport); } // Populate SourcePageName to make it easier to hookup translations at export time foreach (var page in pagesToExport.Where(p => p.IsTranslation)) { var sourcePage = pagesToExport.Where(p => p.PageId == page.SourcePageId).FirstOrDefault(); if (sourcePage != null) { page.SourcePageName = sourcePage.PageName; } } var currentPageIndex = 1; foreach (var page in pagesToExport.OrderBy(p => p.IsTranslation)) { if (creationInfo.IncludeAllClientSidePages || page.IsHomePage) { // Is this a client side page? if (FieldExistsAndUsed(page.ListItem, ClientSideApplicationId) && page.ListItem[ClientSideApplicationId].ToString().Equals(FeatureId_Web_ModernPage.ToString(), StringComparison.InvariantCultureIgnoreCase)) { WriteSubProgress("ClientSidePage", !string.IsNullOrWhiteSpace(page.PageName) ? page.PageName : page.PageUrl, currentPageIndex, pages.Count); // extract the page using the OOB logic clientSidePageContentsHelper.ExtractClientSidePage(web, template, creationInfo, scope, page); } } currentPageIndex++; } } } // If a base template is specified then use that one to "cleanup" the generated template model if (creationInfo.BaseTemplate != null) { template = CleanupEntities(template, creationInfo.BaseTemplate); } } return(template); }
void CheckEquals1(ListCollection<string> list1, Collection<string> list2) { if (list1.Count != list2.Count) throw new Exception(); for (int x = 0; x < list1.Count; x++) { if (list1[x] != list2[x]) throw new Exception(); } var enum1 = list1.GetEnumerator(); var enum2 = list2.GetEnumerator(); while (enum1.MoveNext()) { if (!enum2.MoveNext()) throw new Exception(); if (enum1.Current != enum2.Current) throw new Exception(); } if (enum2.MoveNext()) throw new Exception(); if (!list1.SequenceEqual(list2)) throw new Exception(); CheckEquals2(list1, list2); }
private void UpdateListProgressBar(ListCollection lists, int index, int count) { WriteIterationProgress(ListProgressBarId, WebProgressBarId, "Iterating lists", GetTitle(lists[index]), index, count, CalculateRemainingTimeForList(lists, index)); }
public void TestAdd() { var rand = new Random(3); ListCollection<string> list1 = new ListCollection<string>(); Collection<string> list2 = new Collection<string>(); //Check Add for (int x = 0; x < 100; x++) { var str = x.ToString(); list1.Add(str); list2.Add(str); CheckEquals1(list1, list2); } //Check Remove for (int x = 100; x < 200; x++) { var str = x.ToString(); var removeItem = list1[rand.Next(list1.Count)]; list1.Remove(removeItem); list2.Remove(removeItem); CheckEquals1(list1, list2); list1.Add(str); list2.Add(str); CheckEquals1(list1, list2); } //Check RemoveAt for (int x = 0; x < 100; x++) { int index = rand.Next(list1.Count); list1.RemoveAt(index); list2.RemoveAt(index); CheckEquals1(list1, list2); } //Check Insert for (int x = 0; x < 100; x++) { int index = rand.Next(list1.Count); list1.Insert(index, x.ToString()); list2.Insert(index, x.ToString()); CheckEquals1(list1, list2); } //Check set for (int x = 0; x < 100; x++) { int index = rand.Next(list1.Count); list1[index] = x.ToString(); list2[index] = x.ToString(); CheckEquals1(list1, list2); } list1.Clear(); list2.Clear(); CheckEquals1(list1, list2); //Check Add for (int x = 0; x < 100; x++) { var str = x.ToString(); list1.Add(str); list2.Add(str); CheckEquals1(list1, list2); } //Check indexOf for (int x = 0; x < 100; x++) { int index = rand.Next(list1.Count * 2); if (list1.IndexOf(index.ToString()) != list2.IndexOf(index.ToString())) throw new Exception(); CheckEquals1(list1, list2); } string[] lst1 = new string[list1.Count]; string[] lst2 = new string[list2.Count]; list1.CopyTo(lst1, 0); list2.CopyTo(lst2, 0); CheckEquals3(list1, list2); for (int x = 0; x < 100; x++) { int index = rand.Next(list1.Count * 2); if (list1.Contains(index.ToString()) != list2.Contains(index.ToString())) throw new Exception(); CheckEquals1(list1, list2); } }