/// <summary> /// Evaulate the path string in relation to the current item /// </summary> /// <param name="context">The Revolver context to evaluate the path against</param> /// <param name="path">The path to evaulate. Can either be absolute or relative</param> /// <returns>The full sitecore path to the target item</returns> public static string EvaluatePath(Context context, string path) { if (ID.IsID(path)) return path; string workingPath = string.Empty; if (!path.StartsWith("/")) workingPath = context.CurrentItem.Paths.FullPath + "/" + path; else workingPath = path; // Strip any language and version tags if (workingPath.IndexOf(':') >= 0) workingPath = workingPath.Substring(0, workingPath.IndexOf(':')); // Make relative paths absolute string[] parts = workingPath.Split('/'); StringCollection targetParts = new StringCollection(); targetParts.AddRange(parts); while (targetParts.Contains("..")) { int ind = targetParts.IndexOf(".."); targetParts.RemoveAt(ind); if (ind > 0) { targetParts.RemoveAt(ind - 1); } } if (targetParts[targetParts.Count - 1] == ".") targetParts.RemoveAt(targetParts.Count - 1); // Remove empty elements while (targetParts.Contains("")) { targetParts.RemoveAt(targetParts.IndexOf("")); } string[] toRet = new string[targetParts.Count]; targetParts.CopyTo(toRet, 0); return "/" + string.Join("/", toRet); }
public void AddToFavoriteFolders(string str) { _favoriteFolders.Insert(0, str); while (_favoriteFolders.Count > 10) { _favoriteFolders.RemoveAt(10); } RaisePropertyChanged("FavoriteFolders"); }
/// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ public static StringCollection Initialize(StringCollection paths, int maxMruListSize) { MaxMRUListSize = maxMruListSize; s_paths = (paths ?? new StringCollection()); RemoveStalePaths(); while (s_paths.Count > MaxMRUListSize) s_paths.RemoveAt(s_paths.Count - 1); return s_paths; }
private void _aimTCGAServiceComboBox_KeyDown(object sender, KeyEventArgs e) { if (_aimTCGAServiceComboBox.DroppedDown && _aimTCGAServiceComboBox.SelectedIndex != -1 && e.KeyCode == Keys.Delete) { e.Handled = true; var sl = new StringCollection(); sl.AddRange(CollectionUtils.ToArray<string>(_component.AIMTCGAServiceList)); sl.RemoveAt(_aimTCGAServiceComboBox.SelectedIndex); _component.AIMTCGAServiceList = sl; } }
/// <summary> /// Adds a string to the list and positions it in the recent list /// </summary> /// <param name="text">The string that should be added</param> public void AddString(string text) { if (m_List.Contains(text)) { m_List.Remove(text); m_List.Insert(0, text); } else { if (m_List.Count == m_Capacity) { m_List.RemoveAt(m_List.Count - 1); } m_List.Insert(0, text); } }
private Collection<string> ExpandMshGlobPath(string path, bool allowNonexistingPaths, PSDriveInfo drive, ContainerCmdletProvider provider, CmdletProviderContext context) { if (path == null) { throw PSTraceSource.NewArgumentNullException("path"); } if (provider == null) { throw PSTraceSource.NewArgumentNullException("provider"); } if (drive == null) { throw PSTraceSource.NewArgumentNullException("drive"); } tracer.WriteLine("path = {0}", new object[] { path }); NavigationCmdletProvider provider2 = provider as NavigationCmdletProvider; Collection<string> collection = new Collection<string>(); using (pathResolutionTracer.TraceScope("EXPANDING WILDCARDS", new object[0])) { if (ShouldPerformGlobbing(path, context)) { StringCollection currentDirs = new StringCollection(); Stack<string> stack = new Stack<string>(); using (pathResolutionTracer.TraceScope("Tokenizing path", new object[0])) { while (StringContainsGlobCharacters(path)) { if (context.Stopping) { throw new PipelineStoppedException(); } string childName = path; if (provider2 != null) { childName = provider2.GetChildName(path, context); } if (string.IsNullOrEmpty(childName)) { break; } tracer.WriteLine("Pushing leaf element: {0}", new object[] { childName }); pathResolutionTracer.WriteLine("Leaf element: {0}", new object[] { childName }); stack.Push(childName); if (provider2 != null) { string a = provider2.GetParentPath(path, drive.Root, context); if (string.Equals(a, path, StringComparison.OrdinalIgnoreCase)) { throw PSTraceSource.NewInvalidOperationException("SessionStateStrings", "ProviderImplementationInconsistent", new object[] { provider.ProviderInfo.Name, path }); } path = a; } else { path = string.Empty; } tracer.WriteLine("New path: {0}", new object[] { path }); pathResolutionTracer.WriteLine("Parent path: {0}", new object[] { path }); } tracer.WriteLine("Base container path: {0}", new object[] { path }); if (stack.Count == 0) { string str3 = path; if (provider2 != null) { str3 = provider2.GetChildName(path, context); if (!string.IsNullOrEmpty(str3)) { path = provider2.GetParentPath(path, null, context); } } else { path = string.Empty; } stack.Push(str3); pathResolutionTracer.WriteLine("Leaf element: {0}", new object[] { str3 }); } pathResolutionTracer.WriteLine("Root path of resolution: {0}", new object[] { path }); } currentDirs.Add(path); while (stack.Count > 0) { if (context.Stopping) { throw new PipelineStoppedException(); } string leafElement = stack.Pop(); currentDirs = this.GenerateNewPSPathsWithGlobLeaf(currentDirs, drive, leafElement, stack.Count == 0, provider, context); if (stack.Count > 0) { using (pathResolutionTracer.TraceScope("Checking matches to ensure they are containers", new object[0])) { int index = 0; while (index < currentDirs.Count) { if (context.Stopping) { throw new PipelineStoppedException(); } string mshQualifiedPath = GetMshQualifiedPath(currentDirs[index], drive); if ((provider2 != null) && !this.sessionState.Internal.IsItemContainer(mshQualifiedPath, context)) { tracer.WriteLine("Removing {0} because it is not a container", new object[] { currentDirs[index] }); pathResolutionTracer.WriteLine("{0} is not a container", new object[] { currentDirs[index] }); currentDirs.RemoveAt(index); } else if (provider2 != null) { pathResolutionTracer.WriteLine("{0} is a container", new object[] { currentDirs[index] }); index++; } } continue; } } } foreach (string str6 in currentDirs) { pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", new object[] { str6 }); collection.Add(str6); } return collection; } string str7 = context.SuppressWildcardExpansion ? path : RemoveGlobEscaping(path); string format = OSHelper.IsUnix && provider.GetType () == typeof(Microsoft.PowerShell.Commands.FileSystemProvider) ? (str7.StartsWith ("/") ? "{1}" : "{0}/{1}") : "{0}:" + '\\' + "{1}"; if (drive.Hidden) { if (IsProviderDirectPath(str7)) { format = "{1}"; } else { format = "{0}::{1}"; } } else { char ch = OSHelper.IsUnix && provider.GetType () == typeof(Microsoft.PowerShell.Commands.FileSystemProvider) ? '/' : '\\'; if (path.StartsWith(ch.ToString(), StringComparison.Ordinal)) { format = OSHelper.IsUnix && provider.GetType () == typeof(Microsoft.PowerShell.Commands.FileSystemProvider) ? "{1}" : "{0}:{1}"; } } string str9 = string.Format(CultureInfo.InvariantCulture, format, new object[] { drive.Name, str7 }); if (allowNonexistingPaths || provider.ItemExists(this.GetProviderPath(str9, context), context)) { pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", new object[] { str9 }); collection.Add(str9); return collection; } ItemNotFoundException exception2 = new ItemNotFoundException(str9, "PathNotFound", SessionStateStrings.PathNotFound); pathResolutionTracer.TraceError("Item does not exist: {0}", new object[] { path }); throw exception2; } }
internal Collection<string> ExpandGlobPath(string path, bool allowNonexistingPaths, ContainerCmdletProvider provider, CmdletProviderContext context) { if (path == null) { throw PSTraceSource.NewArgumentNullException("path"); } if (provider == null) { throw PSTraceSource.NewArgumentNullException("provider"); } string updatedPath = null; string updatedFilter = null; string filter = context.Filter; bool flag = provider.ConvertPath(path, context.Filter, ref updatedPath, ref updatedFilter, context); if (flag) { tracer.WriteLine("Provider converted path and filter.", new object[0]); tracer.WriteLine("Original path: " + path, new object[0]); tracer.WriteLine("Converted path: " + updatedPath, new object[0]); tracer.WriteLine("Original filter: " + context.Filter, new object[0]); tracer.WriteLine("Converted filter: " + updatedFilter, new object[0]); path = updatedPath; filter = context.Filter; } NavigationCmdletProvider provider2 = provider as NavigationCmdletProvider; tracer.WriteLine("path = {0}", new object[] { path }); Collection<string> collection = new Collection<string>(); using (pathResolutionTracer.TraceScope("EXPANDING WILDCARDS", new object[0])) { if (ShouldPerformGlobbing(path, context)) { StringCollection currentDirs = new StringCollection(); Stack<string> stack = new Stack<string>(); using (pathResolutionTracer.TraceScope("Tokenizing path", new object[0])) { while (StringContainsGlobCharacters(path)) { if (context.Stopping) { throw new PipelineStoppedException(); } string childName = path; if (provider2 != null) { childName = provider2.GetChildName(path, context); } if (string.IsNullOrEmpty(childName)) { break; } tracer.WriteLine("Pushing leaf element: {0}", new object[] { childName }); pathResolutionTracer.WriteLine("Leaf element: {0}", new object[] { childName }); stack.Push(childName); if (provider2 != null) { string root = string.Empty; if (context != null) { PSDriveInfo drive = context.Drive; if (drive != null) { root = drive.Root; } } string a = provider2.GetParentPath(path, root, context); if (string.Equals(a, path, StringComparison.OrdinalIgnoreCase)) { throw PSTraceSource.NewInvalidOperationException("SessionStateStrings", "ProviderImplementationInconsistent", new object[] { provider.ProviderInfo.Name, path }); } path = a; } else { path = string.Empty; } tracer.WriteLine("New path: {0}", new object[] { path }); pathResolutionTracer.WriteLine("Parent path: {0}", new object[] { path }); } tracer.WriteLine("Base container path: {0}", new object[] { path }); if (stack.Count == 0) { string str7 = path; if (provider2 != null) { str7 = provider2.GetChildName(path, context); if (!string.IsNullOrEmpty(str7)) { path = provider2.GetParentPath(path, null, context); } } else { path = string.Empty; } stack.Push(str7); pathResolutionTracer.WriteLine("Leaf element: {0}", new object[] { str7 }); } pathResolutionTracer.WriteLine("Root path of resolution: {0}", new object[] { path }); } currentDirs.Add(path); while (stack.Count > 0) { if (context.Stopping) { throw new PipelineStoppedException(); } string leafElement = stack.Pop(); currentDirs = this.GenerateNewPathsWithGlobLeaf(currentDirs, leafElement, stack.Count == 0, provider, context); if (stack.Count > 0) { using (pathResolutionTracer.TraceScope("Checking matches to ensure they are containers", new object[0])) { int index = 0; while (index < currentDirs.Count) { if (context.Stopping) { throw new PipelineStoppedException(); } if ((provider2 != null) && !provider2.IsItemContainer(currentDirs[index], context)) { tracer.WriteLine("Removing {0} because it is not a container", new object[] { currentDirs[index] }); pathResolutionTracer.WriteLine("{0} is not a container", new object[] { currentDirs[index] }); currentDirs.RemoveAt(index); } else if (provider2 != null) { pathResolutionTracer.WriteLine("{0} is a container", new object[] { currentDirs[index] }); index++; } } continue; } } } foreach (string str9 in currentDirs) { pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", new object[] { str9 }); collection.Add(str9); } } else { string str10 = context.SuppressWildcardExpansion ? path : RemoveGlobEscaping(path); if (allowNonexistingPaths || provider.ItemExists(str10, context)) { pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", new object[] { str10 }); collection.Add(str10); } else { ItemNotFoundException exception2 = new ItemNotFoundException(path, "PathNotFound", SessionStateStrings.PathNotFound); pathResolutionTracer.TraceError("Item does not exist: {0}", new object[] { path }); throw exception2; } } } if (flag) { context.Filter = filter; } return collection; }
public void Test01() { IntlStrings intl; StringCollection sc; // simple string values string[] values = { "", " ", "a", "aa", "text", " spaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // [] initialize IntStrings intl = new IntlStrings(); // [] StringCollection is constructed as expected //----------------------------------------------------------------- sc = new StringCollection(); // [] RemoveAt() for empty collection // if (sc.Count > 0) sc.Clear(); Assert.Throws<ArgumentOutOfRangeException>(() => { sc.RemoveAt(0); }); // [] RemoveAt() on filled collection // sc.Clear(); sc.AddRange(values); if (sc.Count != values.Length) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, values.Length)); } sc.RemoveAt(0); if (sc.Count != values.Length - 1) { Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", sc.Count, values.Length - 1)); } if (sc.Contains(values[0])) { Assert.False(true, string.Format("Error, removed wrong item")); } // check that all init items were moved for (int i = 0; i < values.Length; i++) { if (sc.IndexOf(values[i]) != i - 1) { Assert.False(true, string.Format("Error, IndexOf returned {1} instead of {2}", i, sc.IndexOf(values[i]), i - 1)); } } sc.Clear(); sc.AddRange(values); if (sc.Count != values.Length) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, values.Length)); } sc.RemoveAt(values.Length - 1); if (sc.Count != values.Length - 1) { Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", sc.Count, values.Length - 1)); } if (sc.Contains(values[values.Length - 1])) { Assert.False(true, string.Format("Error, removed wrong item")); } // check that all init items were moved for (int i = 0; i < values.Length - 1; i++) { if (sc.IndexOf(values[i]) != i) { Assert.False(true, string.Format("Error, IndexOf returned {1} instead of {2}", i, sc.IndexOf(values[i]), i)); } } sc.Clear(); sc.AddRange(values); if (sc.Count != values.Length) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, values.Length)); } sc.RemoveAt(values.Length / 2); if (sc.Count != values.Length - 1) { Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", sc.Count, values.Length - 1)); } if (sc.Contains(values[values.Length / 2])) { Assert.False(true, string.Format("Error, removed wrong item")); } // check that all init items were moved for (int i = 0; i < values.Length; i++) { int expected = i; if (i == values.Length / 2) expected = -1; else if (i > values.Length / 2) expected = i - 1; if (sc.IndexOf(values[i]) != expected) { Assert.False(true, string.Format("Error, IndexOf returned {1} instead of {2}", i, sc.IndexOf(values[i]), expected)); } } // // [] RemoveAt() on collection with identical items // sc.Clear(); string intlStr = intl.GetRandomString(MAX_LEN); sc.Add(intlStr); // index 0 sc.AddRange(values); sc.Add(intlStr); // second index values.Length + 1 if (sc.Count != values.Length + 2) { Assert.False(true, string.Format("Error, count is {1} instead of {2}", sc.Count, values.Length + 2)); } // remove // sc.RemoveAt(values.Length + 1); if (!sc.Contains(intlStr)) { Assert.False(true, string.Format("Error, removed both duplicates")); } // second string should still be present if (sc.IndexOf(intlStr) != 0) { Assert.False(true, string.Format("Error, removed 1st instance")); } // // [] Invalid parameter // sc.Clear(); sc.AddRange(values); Assert.Throws<ArgumentOutOfRangeException>(() => { sc.RemoveAt(-1); }); sc.Clear(); sc.AddRange(values); Assert.Throws<ArgumentOutOfRangeException>(() => { sc.RemoveAt(sc.Count); }); sc.Clear(); sc.AddRange(values); Assert.Throws<ArgumentOutOfRangeException>(() => { sc.RemoveAt(sc.Count + 1); }); }
/// <summary> /// This method updates the cache and hak list properties in the module /// info, adding the passed array of strings to the appropriate property. /// Both of these lists consist of an array of structures with 1 string /// item in each struture. /// </summary> /// <param name="listTag">The property name for the list</param> /// <param name="entryTag">The property name for each string in the list's /// structures</param> /// <param name="structID">The structure ID of the structures in the list</param> /// <param name="stringType">The data type of the string in the list, either /// ExoString or ResRef</param> /// <param name="values">The array of strings to add, duplicates are pruned</param> private void UpdateList(string listTag, string entryTag, uint structID, GffFieldType stringType, string[] values) { // Get the array of elements in the list. GffListField listField = (GffListField) GetField(properties[listTag]); GffFieldCollection list = listField.Value; // Create a string collection containing lower case copies of all of // the strings. StringCollection strings = new StringCollection(); strings.AddRange(values); for (int i = 0; i < strings.Count; i ++) strings[i] = strings[i].ToLower(); // Make a first pass and eliminate any strings that are already // in the module. foreach (GffStructField field in list) { // Get the string entry for the value. GffFieldDictionary dict = field.Value; GffField structValue = dict[entryTag]; // Check to see if the hak is in the list of haks to add if it is // then remove it. int index = strings.IndexOf((string) structValue.Value); if (-1 != index) strings.RemoveAt(index); } // Now loop through all of the remaining strings and add them to the // beginning of the list. We walk the list backwards adding the items // to the beginning of the list's collection, so when we are done // all of the added items are in order at the FRONT of the list. for (int i = strings.Count - 1; i >= 0; i--) { // Create a ExoString field for the hak file name. GffField structValue = GffFieldFactory.CreateField(stringType); structValue.Value = strings[i]; // Create a GffStructField for the new list element and // save the exoString hak name in it. GffStructField listStruct = (GffStructField) GffFieldFactory.CreateField(GffFieldType.Struct); listStruct.StructureType = structID; listStruct.Value = new GffFieldDictionary(); listStruct.Value.Add(entryTag, structValue); // Add the structure to the list. list.Insert(0, listStruct); } }
/// <summary>Returns the array of strings, containing templates, used on page /// (applied to page). Everything inside braces is returned with all parameters /// untouched. Links to templates (like [[:Template:...]]) are not returned. Templates, /// mentioned inside <nowiki></nowiki> tags are also not returned. The "magic words" /// (see http://meta.wikimedia.org/wiki/Help:Magic_words) are recognized and /// not returned by this function as templates. When using this function on text of the /// template, parameters names and numbers (like {{{link}}} and {{{1}}}) are not returned /// by this function as templates too.</summary> /// <returns>Returns the string[] array.</returns> public string[] GetTemplatesWithParams() { Dictionary<int, int> templPos = new Dictionary<int, int>(); StringCollection templates = new StringCollection(); int startPos, endPos, len = 0; string str = text; while ((startPos = str.LastIndexOf("{{")) != -1) { endPos = str.IndexOf("}}", startPos); len = (endPos != -1) ? endPos - startPos + 2 : 2; if (len != 2) templPos.Add(startPos, len); str = str.Remove(startPos, len); str = str.Insert(startPos, new String('_', len)); } string[] templTitles = GetTemplates(false); Array.Reverse(templTitles); foreach (KeyValuePair<int, int> pos in templPos) templates.Add(text.Substring(pos.Key + 2, pos.Value - 4)); for (int i = 0; i < templTitles.Length; i++) while (i < templates.Count && !templates[i].StartsWith(templTitles[i]) && !templates[i].StartsWith(site.namespaces["10"].ToString() + ":" + templTitles[i], true, site.langCulture) && !templates[i].StartsWith(Site.wikiNSpaces["10"].ToString() + ":" + templTitles[i], true, site.langCulture) && !templates[i].StartsWith("msgnw:" + templTitles[i])) templates.RemoveAt(i); string[] arr = new string[templates.Count]; templates.CopyTo(arr, 0); Array.Reverse(arr); return arr; }
/// <summary> /// main method of the thread, generates a master report /// </summary> /// <param name="report_params"></param> private void generate_dataemail_processingfileMaster(report_values report_params) { datamgmt.process_responses processing_files = new datamgmt.process_responses(true); processing_files.permss_user = report_params.permss_user; processing_files.permss_admin = report_params.permss_admin; processing_files.questionnaire_id = report_params.questionnaire_id; processing_files.from = report_params.from; processing_files.until = report_params.until; processing_files.questionnaire_title = report_params.questionnaire_title; processing_files.pathtotempdir = report_params.pathtotempdir; processing_files.Master = report_params.Master; processing_files.IsmasterReport = report_params.IsMasterReport; if(report_params.scheduled) processing_files.IsMasterFail = processing_files.Master.ValidateMaster(); StringCollection file_names = new StringCollection(); int record_counter = 0; string zip_name = ""; if (!processing_files.IsMasterFail) { file_names = processing_files.generate(); //read number of records and delete entry in file_names record_counter = Int32.Parse(file_names[0]); file_names.RemoveAt(0); #region create zip file string timeformat = "yyyyMMddHHmmss"; zip_name = String.Format("zip_{0}_{1}.zip", report_params.Master.Dto.MasterRptId, DateTime.Now.ToString(timeformat)); utility.createZIP(zip_name, report_params.pathtotempdir, file_names); #endregion } #region create and send email MailMessage msg = new MailMessage(); //.NET 1.1: msg.BodyFormat = MailFormat.Html; msg.IsBodyHtml = true; //.NET 1.1: msg.From = email_from; msg.From = new MailAddress(email_from); //.NET 1.1: msg.To = report_params.permss_user; //MailAddressCollection to = msg.To; utility.set_Mail_address(ref msg, "to", report_params.permss_user); //to.Add(report_params.permss_user); if (processing_files.IsMasterFail) { msg.Subject = String.Format("RFG - FAILURE - combined response file report for master report {0}", report_params.Master.Dto.MasterName); } else { msg.Subject = String.Format("RFG - combined response file report for master report {0}", report_params.Master.Dto.MasterName); } if (record_counter > 0) { //.NET 1.1: MailAttachment response_files = new MailAttachment(report_params.pathtotempdir + zip_name); Attachment response_files = new Attachment(report_params.pathtotempdir + zip_name); msg.Attachments.Add(response_files); } #region building emails content (information about the responsefiles) //††† 20120302 Biju Pattathil | RFG2.7 PR629425:dts email having wrong RFG support link (RFG Support link will change):Start††† string support_url = utility.getParameter("support_link"); //+ "live/index.aspx?qid=1493&flexfield1=stop_scheduled_report&flexfield14=qid-" + report_params.questionnaire_id + "-sid-" + report_params.schedule_id + "&flexfield15=" + report_params.permss_user; string mail_text = @" <style> body {font-family:""Arial"";font-weight:normal;font-size:10pt;color:black;} table {font-family:""Arial"";font-weight:normal;font-size:10pt;color:black;} p {font-family:""Arial"";font-weight:normal;color:black;margin-top: -5px} b {font-family:""Arial"";font-weight:bold;color:black;margin-top: -5px} H1 { font-family:""Arial"";font-weight:normal;font-size:14pt;color:black } H2 { font-family:""Arial"";font-weight:normal;font-size:10pt;color:maroon } H3 { font-family:""Arial"";font-weight:normal;font-size:10pt;color:darkgreen } pre {font-family:""Arial Console"";font-size: .9em} .head{ font-family:""Arial"";font-weight:bold;font-size:10pt;color:red } .marker {font-weight: bold; color: black;text-decoration: none;} .version {color: gray;} .error {margin-bottom: 10px;} .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; } </style>"; if (report_params.scheduled) { //Commented by Phani for RFG 1.9.4 release //mail_text = String.Format("{0}<span><b>This is a scheduled report!</b></span><br><br>", mail_text); mail_text = String.Format("{0}<span class=head>This is an automatically generated scheduled report - please do not reply to this email as answers won't be read!</span><br>", mail_text); mail_text = String.Format("{0}<span><i>If you don't need to receive this report any longer please submit your request for the report to stop on the <a href=" + support_url + "> RFG support form</a></i></span><br><br><br>", mail_text); } mail_text = String.Format("{0}<span><p>Hello {1},<br><br>", mail_text, report_params.permss_user); if (record_counter > 0) { mail_text = String.Format("{0}please find attached a zip-archive containing the requested responses for<br><br><table border=1>", mail_text); } else { if (!processing_files.IsMasterFail) { mail_text = String.Format("{0}there were no records of responses you have requested for<br><br><table border=1>", mail_text); } else { string txt = "there is a configuration error for the below master report you should receive. Due to this error a report can not be generated.<br><span class=head>Please get in touch with {1} in order to fix the configuration error.</span><br><br><table border=1>"; mail_text = String.Format("{0}" + txt, mail_text, report_params.Master.Dto.Creator.ToString()); } } //if (!report_params.IsMasterReport) //{ // mail_text = String.Format("{0}<tr><td width=100>Campaign - Title:</td><td><b>{1} - {2}</b> (qid = {3}) </td></tr>", mail_text, report_params.campaign_name, report_params.questionnaire_title, report_params.questionnaire_id); //} //else //{ if(report_params.Master.Dto.MasterRptId>1) mail_text = String.Format("{0}<tr><td width=100>Master Report Name:</td><td><b>{1}(mid = {2})</b> </td></tr>", mail_text, report_params.Master.Dto.MasterName, report_params.Master.Dto.MasterRptId.ToString()); else mail_text = String.Format("{0}<tr><td width=100>Master Report Name:</td><td><b>{1}{2}</b> </td></tr>", mail_text, report_params.Master.Dto.MasterName, ""); //} mail_text = String.Format("{0}<tr><td>from: </td><td><b>{1}</b></td></tr>", mail_text, report_params.from.ToShortDateString()); mail_text = String.Format("{0}<tr><td>until: </td><td><b>{1}</b></td></tr>", mail_text, report_params.until.AddDays(-1d).ToShortDateString()); mail_text = String.Format("{0}<tr><td>number of records<br>in response file: </td><td><b>{1}</b></td></tr><br>", mail_text, record_counter.ToString()); //for master report if (report_params.IsMasterReport) { string str = ""; report_params.Master.Dto.MasterQ.ForEach(delegate(MasterQuestionnaireDto mq) { str = string.Format("{4}{0}-{1}({2}={3})<br>", mq.CName, mq.QName, "qid", mq.QId.ToString(), str); }); mail_text = String.Format("{0}<tr><td>list of questionnaires/<br>processors contained<br>in this master report: </td><td><b>{1}</b></td></tr></table><br>", mail_text, str); } mail_text = String.Format("{0}<br>Regards,<br>Your RFG-team</p></span>", mail_text); #endregion msg.Body = mail_text; //.NET 1.1: SmtpMail.Send(msg); SmtpClient smtp = new SmtpClient(utility.getParameter("smtp")); smtp.Send(msg); msg.Dispose(); try { File.Delete(report_params.pathtotempdir + zip_name); //foreach (String file in file_names) //{ // File.Delete(report_params.pathtotempdir + file); //} } catch { } #endregion //log finish in DB int reportId = 0; if (int.TryParse(report_params.queue_entry_id, out reportId)) { QueueFacade.SetMasterReportStatus(reportId, QueueStatus.Completed); } }
public void CleanRecentlyUsedFiles() { StringCollection recent = new StringCollection(); recent.AddRange(data.RecentOpenedFiles); int i = 0; while (recent.Count > i) { if (File.Exists(recent[i])) { i++; } else { recent.RemoveAt(i); } } string[] result = new string[recent.Count]; recent.CopyTo(result, 0); data.RecentOpenedFiles = result; }
public static int Main(string[] argv) { #if TEST AutoTest.TestSuite(); #endif int result = 1; StringCollection parameters = new StringCollection(); parameters.AddRange(argv); AppDomain.CurrentDomain.AppendPrivatePath(Environment.CurrentDirectory); AppDomain.CurrentDomain.AppendPrivatePath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); try { EntryPoint entryPoint = new EntryPoint(); if (parameters.Contains(DebugOption)) { // Handle debug mode AspectDngConfig.Instance.debug = true; parameters.Remove(DebugOption); } if (parameters.Contains(QueryOption) && parameters.Count >= 3) { // Handle query mode parameters.Remove(QueryOption); Cil.Init(parameters[0], parameters[0]); parameters.RemoveAt(0); string[] array = new string[parameters.Count]; parameters.CopyTo(array, 0); string xpath = string.Join(" ", array); Console.WriteLine("\nReal XPath query:\n{0}", xpath); ICollection results = Cil.TargetNavigator.SelectList(xpath); Console.WriteLine("{0} results", results.Count); foreach (Navigator nav in results) { Console.WriteLine("[" + nav.Name + "] " + nav); } } else if (parameters.Contains(IlmlDumpOption) && parameters.Count == 3) { // Handle ilml mode parameters.Remove(IlmlDumpOption); Cil.Init(parameters[0], parameters[0]); parameters.RemoveAt(0); // Apply XSLT to Assembly XslTransform ilmlDump = new XslTransform(); ilmlDump.Load(new XmlTextReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("IlmlDump.xsl")), null, null); XmlTextWriter writer = new XmlTextWriter(parameters[0], Encoding.Unicode); writer.Formatting = Formatting.Indented; ilmlDump.Transform(new Navigator(Cil.TargetAssembly), null, writer, null); writer.Close(); } else { // Handle weave mode long Start = DateTime.Now.Ticks; // Interpret parameters if (parameters.Count > 0) { string firstArg = parameters[0]; if (firstArg.EndsWith(".xml")) { Log.Debug("Weaving as specified in " + firstArg); entryPoint.Weave(firstArg); result = 0; } else if (firstArg.EndsWith(".dll") || firstArg.EndsWith(".exe")) { if (parameters.Count == 1) entryPoint.DirectWeave(firstArg); else if (parameters.Count == 2) { string secondArg = parameters[1]; entryPoint.DirectWeave(firstArg, secondArg); } result = 0; } else entryPoint.PrintUsage(); } else entryPoint.PrintUsage(); if (result == 0) { Log.Debug("aspectdng took in {0} millis to weave {1} aspects", (DateTime.Now.Ticks - Start) / 10000, AspectDngConfig.Instance.Advice.Count); Log.Save(); } } } catch (ConfigurationException e) { Log.Error(e.Message); } catch (AdviceException e) { Log.Error(e.Message); } catch (Exception e) { Log.Error(e.Message); Log.Error(e.StackTrace); } return result; }
private static StringCollection GetFilteredFileList(DirectoryInfo sourceDirectory, ArrayList includes, ArrayList excludes) { StringCollection fileList = new StringCollection(); foreach (FileFilter fileFilter in includes) { FileInfo[] files = sourceDirectory.GetFiles(fileFilter.Mask); if (files.Length <= 0) { if (fileFilter.FailOnEmpty) GenError("File by mask '{0}' not found in directory '{1}' !", fileFilter.Mask, sourceDirectory.FullName); } else for (int i = 0; i < files.Length; ++i) { string fileFullName = files[i].FullName; int fileIndex = fileList.IndexOf(fileFullName); // Защита от дублирования if (fileIndex < 0) fileList.Add(fileFullName); else { Console.Error.WriteLine( "WixGen.exe : warning WGEN1002: File '{0}' already included.\r\nDetail info: Directory '{1}', Filter '{2}'\r\n", fileFullName, sourceDirectory.FullName, fileFilter.Mask); } } } foreach (FileFilter fileFilter in excludes) { FileInfo[] files = sourceDirectory.GetFiles(fileFilter.Mask); for (int i = 0; i < files.Length; ++i) { int fileIndex = fileList.IndexOf(files[i].FullName); if (fileIndex >= 0) fileList.RemoveAt(fileIndex); } } return fileList; }
public void Test01() { StringCollection sc; StringEnumerator en; string curr; // Enumerator.Current value bool res; // boolean result of MoveNext() // simple string values string[] values = { "a", "aa", "", " ", "text", " spaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // [] StringEnumerator.Reset() //----------------------------------------------------------------- sc = new StringCollection(); // // [] on Empty Collection // // // no exception // en = sc.GetEnumerator(); en.Reset(); // // Attempt to get Current should result in exception // Assert.Throws<InvalidOperationException>(() => { curr = en.Current; }); // // [] Add item to collection and Reset() // int cnt = sc.Count; sc.Add(values[0]); if (sc.Count != 1) { Assert.False(true, string.Format("Error, failed to add item")); } Assert.Throws<InvalidOperationException>(() => { en.Reset(); }); // // [] on Filled collection // sc.AddRange(values); en = sc.GetEnumerator(); // // Reset() should not result in any exceptions // en.Reset(); en.Reset(); // // [] Move to 0th item and Reset() // if (!en.MoveNext()) { Assert.False(true, string.Format("Error, MoveNext() returned false")); } curr = en.Current; if (String.Compare(curr, values[0]) != 0) { Assert.False(true, string.Format("Error, Current returned wrong value")); } // Reset() and repeat two checks en.Reset(); if (!en.MoveNext()) { Assert.False(true, string.Format("Error, MoveNext() returned false")); } if (String.Compare(en.Current, curr) != 0) { Assert.False(true, string.Format("Error, Current returned wrong value")); } // // [] Move to Count/2 item and Reset() // int ind = sc.Count / 2; en.Reset(); for (int i = 0; i < ind + 1; i++) { res = en.MoveNext(); if (!res) { Assert.False(true, string.Format("Error, MoveNext returned false", i)); } curr = en.Current; if (String.Compare(curr, sc[i]) != 0) { Assert.False(true, string.Format("Error, Current returned \"{1}\" instead of \"{2}\"", i, curr, sc[i])); } // while we didn't MoveNext, Current should return the same value string curr1 = en.Current; if (String.Compare(curr, curr1) != 0) { Assert.False(true, string.Format("Error, second call of Current returned different result", i)); } } // Reset() and check 0th item en.Reset(); if (!en.MoveNext()) { Assert.False(true, string.Format("Error, MoveNext() returned false")); } if (String.Compare(en.Current, sc[0]) != 0) { Assert.False(true, string.Format("Error, Current returned wrong value")); } // // [] Move to the last item and Reset() // ind = sc.Count; en.Reset(); for (int i = 0; i < ind; i++) { res = en.MoveNext(); if (!res) { Assert.False(true, string.Format("Error, MoveNext returned false", i)); } curr = en.Current; if (String.Compare(curr, sc[i]) != 0) { Assert.False(true, string.Format("Error, Current returned \"{1}\" instead of \"{2}\"", i, curr, sc[i])); } // while we didn't MoveNext, Current should return the same value string curr1 = en.Current; if (String.Compare(curr, curr1) != 0) { Assert.False(true, string.Format("Error, second call of Current returned different result", i)); } } // Reset() and check 0th item en.Reset(); if (!en.MoveNext()) { Assert.False(true, string.Format("Error, MoveNext() returned false")); } if (String.Compare(en.Current, sc[0]) != 0) { Assert.False(true, string.Format("Error, Current returned wrong value")); } // // [] Move beyond the last item and Reset() // en.Reset(); for (int i = 0; i < ind; i++) { res = en.MoveNext(); } // next MoveNext should bring us outside of the collection // res = en.MoveNext(); res = en.MoveNext(); if (res) { Assert.False(true, string.Format("Error, MoveNext returned true")); } // Reset() and check 0th item en.Reset(); if (!en.MoveNext()) { Assert.False(true, string.Format("Error, MoveNext() returned false")); } if (String.Compare(en.Current, sc[0]) != 0) { Assert.False(true, string.Format("Error, Current returned wrong value")); } // // Attempt to get Current should result in exception // en.Reset(); Assert.Throws<InvalidOperationException>(() => { curr = en.Current; }); // // [] Modify collection when enumerating // if (sc.Count < 1) sc.AddRange(values); // // modify the collection and call Reset() before first MoveNext() // en = sc.GetEnumerator(); sc.RemoveAt(0); Assert.Throws<InvalidOperationException>(() => { en.Reset(); }); // // Enumerate to the middle item of the collection, modify the collection, // and call Reset() // // create valid enumerator // en = sc.GetEnumerator(); for (int i = 0; i < sc.Count / 2; i++) { res = en.MoveNext(); } curr = en.Current; sc.RemoveAt(0); // will return previous current if (String.Compare(curr, en.Current) != 0) { Assert.False(true, string.Format("Error, current returned {0} instead of {1}", en.Current, curr)); } // exception expected Assert.Throws<InvalidOperationException>(() => { en.Reset(); }); // // Enumerate to the last item of the collection, modify the collection, // and call Reset() // // create valid enumerator // en = sc.GetEnumerator(); for (int i = 0; i < sc.Count; i++) { res = en.MoveNext(); } sc.RemoveAt(0); // exception expected Assert.Throws<InvalidOperationException>(() => { en.Reset(); }); // // [] Modify collection after enumerating beyond the end // if (sc.Count < 1) sc.AddRange(values); en = sc.GetEnumerator(); for (int i = 0; i < sc.Count; i++) { res = en.MoveNext(); } res = en.MoveNext(); // should be beyond the end if (res) { Assert.False(true, string.Format("Error, MoveNext returned true after moving beyond the end")); } cnt = sc.Count; sc.RemoveAt(0); if (sc.Count != cnt - 1) { Assert.False(true, string.Format("Error, didn't remove 0-item")); } // exception expected Assert.Throws<InvalidOperationException>(() => { en.Reset(); }); }
/// <summary> /// This method splits values on a comma but also honours double quotes /// ensuring something in double quotes is never split. /// eg: if text = value1, "value 2, 2a", value3 /// then: words[0] = value1 /// words[1] = value2, 2a /// words[2] = value3 /// All values returned have been trimmed of spaces and double quotes. /// </summary> public static StringCollection SplitStringHonouringQuotes(string text, string delimiters) { StringCollection ReturnStrings = new StringCollection(); if (text.Trim() == "") return ReturnStrings; bool InsideQuotes = false; int Start = IndexNotOfAny(text, " ".ToCharArray()); for (int i = Start; i < text.Length; i++) { if (text[i] == '"') InsideQuotes = !InsideQuotes; // toggle else if (!InsideQuotes) { if (delimiters.IndexOf(text[i]) != -1) { // Found a word - store it. if (Start != i) ReturnStrings.Add(text.Substring(Start, i - Start).Trim(" ".ToCharArray())); Start = i+1; } } } if (Start != text.Length) ReturnStrings.Add(text.Substring(Start, text.Length - Start).Trim(" ".ToCharArray())); // remove leading and trailing quote if necessary. for (int i = 0; i < ReturnStrings.Count; i++) { if (ReturnStrings[i][0] == '"' && ReturnStrings[i][ReturnStrings[i].Length - 1] == '"') { ReturnStrings[i] = ReturnStrings[i].Substring(1, ReturnStrings[i].Length - 2).Trim(); if (ReturnStrings[i] == "") { ReturnStrings.RemoveAt(i); i--; } } } return ReturnStrings; }
/// <summary> /// Remove an element from an array by value and optionally a number of elements after it. /// </summary> /// <param name="array">The array to remove the value from</param> /// <param name="value">The value to remove</param> /// <param name="count">The number of elements after the value to remove aswell</param> /// <returns>An array without the value</returns> public static string[] RemoveParameter(string[] array, string value, int count) { if (Array.IndexOf(array, value) < 0) return array; else { StringCollection coll = new StringCollection(); coll.AddRange(array); int ind = coll.IndexOf(value); for (int i = ind + count; i >= ind; i--) coll.RemoveAt(ind); string[] output = new string[coll.Count]; coll.CopyTo(output, 0); return output; } }
// Token: 0x06001234 RID: 4660 // RVA: 0x0006137C File Offset: 0x0005F57C public static void smethod_7(StringCollection stringCollection_0, Class158 class158_0, Class157 class157_0) { if (class157_0 != null) { class158_0.Remove(class157_0); int i = int.Parse(class157_0.Value); stringCollection_0.RemoveAt(i); while (i < stringCollection_0.Count) { if (Class174.smethod_2(stringCollection_0[i])) { break; } if (stringCollection_0[i][0] != '\t' && stringCollection_0[i][0] != ' ') { return; } stringCollection_0.RemoveAt(i); } } }
private int ExtractExpectedListCountFrom(StringCollection elementsList) { if (elementsList.Count < 2) return 0; string expectedListCountText = elementsList[0]; if (!REGEX_INT.IsMatch(expectedListCountText)) return 0; elementsList.RemoveAt(0); return int.Parse(expectedListCountText); }
// generic method to add a string to a history item private void AddSearchHistoryItem(StringCollection history, string toAdd) { // add the item to the find history if (history.Contains(toAdd)) { // remove it so it gets added at the top history.Remove(toAdd); } // make sure there is only 20 if (history.Count == HISTORY_LIMIT) { history.RemoveAt(HISTORY_LIMIT - 1); } history.Insert(0, toAdd); // update the drop down for the combobox string[] stringArray = new string[history.Count]; history.CopyTo(stringArray, 0); if (history == findHistory) { searchPatternComboBox.SetPopdownStrings(stringArray); } else if( history == replaceHistory) { replacePatternComboBox.SetPopdownStrings(stringArray); } }
private string ExtractObjectTypeNameFrom(StringCollection elementsList) { if (elementsList.Count <= 1) return null; string typeName = elementsList[0]; elementsList.RemoveAt(0); return GetCheckedTypeNameBy(typeName); }
// ヘッダを分析し、Dictionary<string, string> に格納 public static Dictionary<string, string> Parse(string header) { StringCollection line = new StringCollection(); Dictionary<string, string> sd = new Dictionary<string, string>(); line.AddRange(Regex.Split(header, "\r\n")); Match m = Regex.Match(line[0], @"^(.+)\s+(.+)/(\d\.\d)$"); Match n = Regex.Match(line[0], @"^(.+)/(\d\.\d)\s+(\d{3})\s+(.+)$"); if (m.Success) { // REQUEST - e.g.: "^(GET String) (SHIORI)/(2.5)$" sd["_COMMANDLINE_"] = line[0]; sd["_METHOD_"] = m.Groups[1].Value; sd["_PROTOCOL_"] = m.Groups[2].Value; sd["_VERSION_"] = m.Groups[3].Value; } else if (n.Success) { // RESPONSE - e.g.: "^(SHIORI)/(3.0) (204) (No Content)$" sd["_STATUSLINE_"] = line[0]; sd["_PROTOCOL_"] = n.Groups[1].Value; sd["_VERSION_"] = n.Groups[2].Value; sd["_STATUS_"] = n.Groups[3].Value; sd["_STRING_"] = n.Groups[4].Value; } line.RemoveAt(0); // コマンドライン削除 // SSTP の Entry, IfGhost - Script は例外にならざるを得ないので、このような処理になった // その他の方法論としては、レスポンス格納用の変数をさらにネストするか、 // 行単位で保持するか、独自の管理クラスを作るか、 // そもそも帰ってきた値を変数としてキープしておくのをやめるか、等々 // int e = 0; // Entryキー用カウンタ // int i = 0; // IfGhost 用カウンタ // int s = 0; // Script 用カウンタ // Regex re = new Regex(@"^Entry\s*:\s*(.+)\s*$", RegexOptions.Compiled); // Regex ri = new Regex(@"^IfGhost\s*:\s*(.+)\s*$", RegexOptions.Compiled); // Regex rs = new Regex(@"^Script\s*:\s*(.+)\s*$", RegexOptions.Compiled); // Regex rg = new Regex(@"^GhostEx\s*:\s*(.+)\s*$", RegexOptions.Compiled); // Regex rb = new Regex(@"^X-Bottle-IfGhost\s*:\s*(.+)\s*$", RegexOptions.Compiled); // ボトル拡張 for (int j = 0; j < line.Count; ++j) { m = Protocol.rGeneralEntry.Match(line[j]); if (m.Success) { // e.g.: "^Value: \0\s[10]Hello, World!\e" sd[m.Groups[1].Value] = m.Groups[2].Value.Trim(); // } else if (re.Match(c).Success) { // "Entry: SAKURA script" // sd["Entry" + e++] = re.Match(c).Groups[1].Value; // } else if (ri.Match(c).Success) { // "IfGhost: Ghost name(s)" // sd["IfGhost" + i++] = ri.Match(c).Groups[1].Value; // } else if (rs.Match(c).Success) { // "Script: SAKURA script" // sd["GhostEx" + s++] = rs.Match(c).Groups[1].Value; // } else if (rg.Match(c).Success) { // "GhostEx: Ghost name" // sd["Script" + s++] = rg.Match(c).Groups[1].Value; // } else if (rb.Match(c).Success) { // "X-Bottle-IfGhost: Ghost name" // sd["X-Bottle-IfGhost"] = rb.Match(c).Groups[1].Value; } } return sd; }
public void Test01() { StringCollection sc; StringEnumerator en; string curr; // Eumerator.Current value // simple string values string[] values = { "a", "aa", "", " ", "text", " spaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // [] StringCollection GetEnumerator() //----------------------------------------------------------------- sc = new StringCollection(); // [] Enumerator for empty collection // en = sc.GetEnumerator(); string type = en.GetType().ToString(); if (type.IndexOf("StringEnumerator", 0) == 0) { Assert.False(true, string.Format("Error, type is not StringEnumerator")); } // // MoveNext should return false // bool res = en.MoveNext(); if (res) { Assert.False(true, string.Format("Error, MoveNext returned true")); } // // Attempt to get Current should result in exception // Assert.Throws<InvalidOperationException>(() => { curr = en.Current; }); // // Filled collection // [] Enumerator for filled collection // sc.AddRange(values); en = sc.GetEnumerator(); type = en.GetType().ToString(); if (type.IndexOf("StringEnumerator", 0) == 0) { Assert.False(true, string.Format("Error, type is not StringEnumerator")); } // // MoveNext should return true // for (int i = 0; i < sc.Count; i++) { res = en.MoveNext(); if (!res) { Assert.False(true, string.Format("Error, MoveNext returned false", i)); } curr = en.Current; if (String.Compare(curr, sc[i]) != 0) { Assert.False(true, string.Format("Error, Current returned \"{1}\" instead of \"{2}\"", i, curr, sc[i])); } // while we didn't MoveNext, Current should return the same value string curr1 = en.Current; if (String.Compare(curr, curr1) != 0) { Assert.False(true, string.Format("Error, second call of Current returned different result", i)); } } // next MoveNext should bring us outside of the collection // res = en.MoveNext(); res = en.MoveNext(); if (res) { Assert.False(true, string.Format("Error, MoveNext returned true")); } // // Attempt to get Current should result in exception // Assert.Throws<InvalidOperationException>(() => { curr = en.Current; }); en.Reset(); // // Attempt to get Current should result in exception // Assert.Throws<InvalidOperationException>(() => { curr = en.Current; }); // // [] Modify collection when enumerating // if (sc.Count < 1) sc.AddRange(values); en = sc.GetEnumerator(); res = en.MoveNext(); if (!res) { Assert.False(true, string.Format("Error, MoveNext returned false")); } int cnt = sc.Count; sc.RemoveAt(0); if (sc.Count != cnt - 1) { Assert.False(true, string.Format("Error, didn't remove 0-item")); } // will return just removed item curr = en.Current; if (String.Compare(curr, values[0]) != 0) { Assert.False(true, string.Format("Error, current returned {0} instead of {1}", curr, values[0])); } // exception expected Assert.Throws<InvalidOperationException>(() => { res = en.MoveNext(); }); }
private void LoadDataSourceFields() { using (new MobileComponentEditorPage.LoadingModeResource(this)) { ObjectList baseControl = base.GetBaseControl(); this._cmbLabelField.SelectedIndex = -1; this._cmbLabelField.Items.Clear(); this._cmbLabelField.EnsureNotSetItem(); this._xLists.Clear(); if (this._currentDataSource != null) { StringCollection strings = new StringCollection(); foreach (ObjectListField field in baseControl.get_Fields()) { this._cmbLabelField.AddItem(field.get_Name()); strings.Add(field.get_Name()); } if (baseControl.get_AutoGenerateFields()) { PropertyDescriptorCollection fields = this._currentDataSource.Fields; if (fields != null) { IEnumerator enumerator = fields.GetEnumerator(); while (enumerator.MoveNext()) { PropertyDescriptor current = (PropertyDescriptor) enumerator.Current; if (this.IsBindableType(current.PropertyType)) { this._cmbLabelField.AddItem(current.Name); strings.Add(current.Name); } } } } if ((baseControl.get_TableFields() != string.Empty) && !this._dataSourceDirty) { char[] separator = new char[] { ';' }; foreach (string str in baseControl.get_TableFields().Split(separator)) { for (int i = 0; i < strings.Count; i++) { string strB = strings[i]; if (string.Compare(str, strB, true) == 0) { this._xLists.AddToSelectedList(strB); strings.RemoveAt(i); break; } } } } StringEnumerator enumerator3 = strings.GetEnumerator(); while (enumerator3.MoveNext()) { string str3 = enumerator3.Current; this._xLists.AddToAvailableList(str3); } this._xLists.Initialize(); } } }
public void AddRecentlyUsedFile(FileInfo newFile) { StringCollection recent = new StringCollection(); recent.AddRange(data.RecentOpenedFiles); while(recent.IndexOf(newFile.FullName) >= 0) { recent.Remove(newFile.FullName); } recent.Insert(0, newFile.FullName); while (recent.Count > 16) { recent.RemoveAt(16); } string[] result = new string[recent.Count]; recent.CopyTo(result, 0); data.RecentOpenedFiles = result; }
/// <summary> /// Extracts a member name. /// </summary> /// <param name="words">The words to extract the member name and type from.</param> /// <param name="name">The member name.</param> /// <param name="returnType">The meber return type.</param> private static void GetMemberNameAndType( StringCollection words, out string name, out string returnType) { name = null; returnType = null; for (int wordIndex = 0; wordIndex < words.Count; wordIndex++) { string wordGroup = words[wordIndex]; int separatorIndex = wordGroup.IndexOf(CSharpSymbol.AliasSeparator); if (separatorIndex >= 0 && wordGroup[wordGroup.Length - 1] != CSharpSymbol.EndAttribute) { if (separatorIndex < wordGroup.Length - 1) { // // Format words with commas to have a space after comma // string[] aliases = wordGroup.Split(CSharpSymbol.AliasSeparator); wordGroup = string.Empty; for (int aliasIndex = 0; aliasIndex < aliases.Length; aliasIndex++) { string alias = aliases[aliasIndex]; wordGroup += alias.Trim(); if (aliasIndex < aliases.Length - 1) { wordGroup += ", "; } } wordGroup = wordGroup.TrimEnd(); words[wordIndex] = wordGroup; } // // Concatenate comma separated values into logical groups // if (wordGroup[0] == CSharpSymbol.AliasSeparator && wordIndex > 0) { if (wordGroup.Length == 1 && wordIndex < words.Count - 1) { words[wordIndex - 1] = words[wordIndex - 1] + CSharpSymbol.AliasSeparator + " " + words[wordIndex + 1]; words.RemoveAt(wordIndex); words.RemoveAt(wordIndex); wordIndex--; wordIndex--; } else { words[wordIndex - 1] = words[wordIndex - 1] + wordGroup; words.RemoveAt(wordIndex); wordIndex--; } } else if (wordIndex < words.Count && wordGroup[wordGroup.Length - 1] == CSharpSymbol.AliasSeparator) { wordGroup = wordGroup + " " + words[wordIndex + 1]; words[wordIndex] = wordGroup; words.RemoveAt(wordIndex + 1); wordIndex--; } } } if (words.Count > 1) { int nameIndex = words.Count - 1; name = words[nameIndex]; words.RemoveAt(nameIndex); int typeIndex = nameIndex; string typeCandidate; do { typeIndex--; typeCandidate = words[typeIndex]; words.RemoveAt(typeIndex); } while (words.Count > 0 && (typeCandidate == CSharpKeyword.Operator || typeCandidate == CSharpKeyword.Implicit || typeCandidate == CSharpKeyword.Explicit)); if (name[name.Length - 1] == CSharpSymbol.EndAttribute && words.Count > 0) { // // Property indexer // while (typeIndex > 0 && name.IndexOf(CSharpSymbol.BeginAttribute) < 0) { name = typeCandidate + " " + name; typeIndex--; typeCandidate = words[typeIndex]; words.RemoveAt(typeIndex); } if (name[0] == CSharpSymbol.BeginAttribute) { name = typeCandidate + name; typeIndex--; typeCandidate = words[typeIndex]; words.RemoveAt(typeIndex); } } // // Array return type with spaces? // while (typeCandidate[typeCandidate.Length - 1] == CSharpSymbol.EndAttribute && typeCandidate[0] == CSharpSymbol.BeginAttribute) { typeIndex--; typeCandidate = words[typeIndex] + typeCandidate; words.RemoveAt(typeIndex); } if (typeCandidate != CSharpKeyword.Abstract && typeCandidate != CSharpKeyword.Constant && typeCandidate != CSharpKeyword.Internal && typeCandidate != CSharpKeyword.New && typeCandidate != CSharpKeyword.Override && typeCandidate != CSharpKeyword.Private && typeCandidate != CSharpKeyword.Protected && typeCandidate != CSharpKeyword.Public && typeCandidate != CSharpKeyword.ReadOnly && typeCandidate != CSharpKeyword.Sealed && typeCandidate != CSharpKeyword.Static && typeCandidate != CSharpKeyword.Virtual && typeCandidate != CSharpKeyword.Operator && typeCandidate != CSharpKeyword.Implicit && typeCandidate != CSharpKeyword.Explicit) { returnType = typeCandidate; } } else { name = words[0]; words.RemoveAt(0); } }
/// <summary> /// Tries to find and remove a word from the word list. /// </summary> /// <param name="wordList">The word list.</param> /// <param name="word">The word to find and remove.</param> /// <returns>Whether or not the word was found and removed.</returns> private static bool TryFindAndRemoveWord(StringCollection wordList, string word) { bool removed = false; int wordIndex = wordList.IndexOf(word); if (wordIndex >= 0) { wordList.RemoveAt(wordIndex); removed = true; } return removed; }
// generic method to add a string to a history item private void AddSearchHistoryItem(StringCollection history, string toAdd) { // add the item to the find history if (history.Contains(toAdd)) { // remove it so it gets added at the top history.Remove(toAdd); } // make sure there is only 20 if (history.Count == historyLimit) { history.RemoveAt(historyLimit - 1); } history.Insert(0, toAdd); // update the drop down for the combobox ListStore store = new ListStore (typeof (string)); for (int i = 0; i < history.Count; i ++) store.AppendValues (history[i]); if (history == findHistory) searchPatternEntry.Completion.Model = store; else if( history == replaceHistory) replacePatternEntry.Completion.Model = store; }
private void AddPathToHistory(StringCollection list, string entry) { if (list == null) return; foreach (string item in list) { if (item == entry) { list.Remove(item); break; } } while (list.Count >= 5) list.RemoveAt(list.Count - 1); list.Insert(0, entry); }
/// <summary> /// Adds the passed hif name / version number to the list of hifs installed on /// the module. Both arrays must be the same length. /// </summary> /// <param name="hifs">The hifs to add</param> /// <param name="versions">The version numbers of the hifs</param> public void AddInstalledHakInfos(string[] hifs, float[] versions) { // Get the current values if any. string[] currentHifs; float[] currentVersions; GetInstalledHakInfos(out currentHifs, out currentVersions); // Create StringCollections for them so we can use IndexOf() for searching. StringCollection colHifs = new StringCollection(); colHifs.AddRange(currentHifs); ArrayList colVersions = new ArrayList(); colVersions.AddRange(currentVersions); // Check for duplicates, pruning duplicates out of the current list. foreach (string hif in hifs) { // Find the hif in the current values, if we don't find it then // skip it. int index = colHifs.IndexOf(hif); if (-1 == index) continue; // Remove it from the current list. colHifs.RemoveAt(index); colVersions.RemoveAt(index); } // Now build a string with all of the current hifs/version numbers then // all of the added hif/version numbers. System.Text.StringBuilder b = new StringBuilder(); for (int i = 0; i < colHifs.Count; i++) { if (b.Length > 0) b.Append(";"); b.AppendFormat("{0};{1}", colHifs[i], colVersions[i].ToString()); } for (int i = 0; i < hifs.Length; i++) { if (b.Length > 0) b.Append(";"); b.AppendFormat("{0};{1}", hifs[i], versions[i].ToString()); } // Get the schema for the field and get it, creating it if it is not there. // Then save the StringBuilder text as the field's value. GffFieldSchema schema = properties["installedhifs"]; GffExoStringField field = (GffExoStringField) GetField(schema); field.Value = b.ToString(); }
/// <summary> /// Load the list of recent files from disk. /// </summary> public static void LoadRecentFiles() { if (File.Exists(RecentFilesFilePath)) { // Load the Recent Files from disk XmlSerializer ser = new XmlSerializer(typeof(StringCollection)); using (TextReader reader = new StreamReader(RecentFilesFilePath)) { recentFiles = (StringCollection)ser.Deserialize(reader); } // Remove files from the Recent Files list that no longer exists. for (int i = 0; i < recentFiles.Count; i++) { if (!File.Exists(recentFiles[i])) recentFiles.RemoveAt(i); } // Only keep the 5 most recent files, trim the rest. while (recentFiles.Count > NumberOfRecentFiles) recentFiles.RemoveAt(NumberOfRecentFiles); } }
public void ProcessWikiCommands(string[] wikiCommands, List<BreakPoint> breakPoints, System.Threading.Thread activeThread, CommandEditorPage currentPage, bool commandLineMode, List<CommandResult> listOfResults, string fileName) { bool inComment = false; string cleanedCommand = ""; foreach (string wikiCommand in wikiCommands) { lineNumber++; Command mngrCommand = new Command(wikiCommand.TrimStart('|')); cleanedCommand = cleanCommand(wikiCommand); if (breakPoints.Count > 0) CheckForBreakPointOnLine(breakPoints, lineNumber, activeThread, currentPage); CommandResult returnResult = new CommandResult(); returnResult.FileName = fileName; returnResult.LineNumber = lineNumber; returnResult.FullCommand = mngrCommand.FullCommand; listOfResults.Add(returnResult); if (cleanedCommand.Equals(String.Empty)) { if (_finishBlockOnFailure) { TestManager.FinishBlockOnFailure = true; _finishBlockOnFailure = false; } TestManager.ResetForNewTable(); } if (!cleanedCommand.StartsWith("#") && !inComment && !cleanedCommand.StartsWith("{{{") && !cleanedCommand.StartsWith("}}}") && !isIgnoredCommand(cleanedCommand) && !TestManager.InCompareData) { if (cleanedCommand.StartsWith("!")) { if (cleanedCommand.StartsWith("!define")) { try { cleanedCommand = replaceVar(cleanedCommand); } catch (SWATVariableDoesNotExistException e) { returnResult.Success = false; mngrCommand.Passed = false; returnResult.Message = e.Message; returnResult.Command = "Could not be defined"; TestManager.LogCommand(mngrCommand); goto Exit; } WikiVariable var = new WikiVariable(cleanedCommand); if (!_variables.ContainsKey(var.Name)) _variables.Add(var.Name, var.Value); else _variables[var.Name] = var.Value; returnResult.Success = true; returnResult.Command = string.Format("Defined {0} as {1}", var.Name, var.Value); } if (cleanedCommand.StartsWith("!include")) { WikiInclude include = new WikiInclude(cleanedCommand); try { string newFileName = SWAT.FitnesseSettings.FitnesseRootDirectory.TrimEnd('\\') + "\\" + include.FilePath + "content.txt"; string[] lines = File.ReadAllLines(newFileName); //Need an intermediate slot in the results. returnResult.Command = "INCLUDE"; returnResult.FullCommand = cleanedCommand; returnResult.Success = true; returnResult.Ignored = false; ProcessWikiCommands(lines, breakPoints, activeThread, currentPage, commandLineMode, returnResult.Children, newFileName); } catch (DirectoryNotFoundException) { returnResult.Success = false; returnResult.Ignored = false; returnResult.Message = string.Format("Could not load macro at {0}", SWAT.FitnesseSettings.FitnesseRootDirectory.TrimEnd('\\') + "\\" + include.FilePath); returnResult.Command = "INCLUDE"; } } } else { //string[] sections = cleanedCommand.TrimStart('|').TrimEnd('|').Split('|'); // Remove leading pipes cleanedCommand = cleanedCommand.TrimStart('|'); // Remove last pipe. Can't use TrimEnd('|') in case we are passing empty parameters string[] sections = parseSections(cleanedCommand.Substring(0, cleanedCommand.LastIndexOf('|'))); StringCollection parameters = new StringCollection(); if (sections.Length < 1) { returnResult.Success = false; returnResult.Message = "Command is not formated correctly."; returnResult.Command = cleanedCommand; goto Exit; } string command = sections[0]; returnResult.Command = command; for (int i = 1; i < sections.Length; i++) { string replace = ""; try { replace = replaceVar(sections[i]); } catch (SWATVariableDoesNotExistException e) { parameters.Add(sections[i]); var paramEntryex = new CommandResult.ParameterEntry { OriginalParam = sections[i], ReplacedParam = sections[i] }; returnResult.Parameters.Add(paramEntryex); returnResult.Success = false; mngrCommand.Passed = false; returnResult.Message = e.Message; TestManager.LogCommand(mngrCommand); goto Exit; } parameters.Add(replace); var paramEntry = new CommandResult.ParameterEntry { OriginalParam = sections[i], ReplacedParam = replace }; returnResult.Parameters.Add(paramEntry); } if (TestManager.ShouldExecute(mngrCommand)) { try { string varKey = ""; if (command == "GetElementAttribute") { varKey = parameters[3]; parameters.RemoveAt(3); } if (command == "GetConfigurationItem") { varKey = parameters[1]; parameters.RemoveAt(1); } if (command.Contains("GetDbRecord") || command.Contains("GetDbDate") || command.Contains("GetLocation") || command.Contains("GetWindowTitle") || command.Contains("RunScriptSaveResult") || command.Contains("SetVariable") || command.StartsWith("GetSavedDbDate") || command == "GetTimerValue") { varKey = parameters[0]; parameters.RemoveAt(0); } if(command == "BeginCompareData") { TestManager.InCompareData = true; _inCompareDataIndex = 0; TestManager.InCompareDataIsCritical = false; } InvokeResult result = _invokeManager.Invoke(command, parameters); if (mngrCommand.IsInverse) { returnResult.Success = !result.Success; mngrCommand.Passed = !result.Success; } else { returnResult.Success = result.Success; mngrCommand.Passed = result.Success; } if (!mngrCommand.Passed && mngrCommand.FinishBlockOnFailure) { _finishBlockOnFailure = true; } returnResult.Cond = wikiCommand.StartsWith("|?"); //Notify the user on success. if (result.Success) { //If original command failed, now passes with inverse modifier if (mngrCommand.IsInverse) returnResult.Message = "Inverse modifier failed passing command"; else returnResult.Message = "Success"; //C# Operator == is overloaded, so Equals() method is called when used. That is why it can be used to compare Strings. if ((command == "GetElementAttribute" || command.Contains("GetDbRecord") || command == "GetDbDate" || command == "GetLocation" || command == "GetConfigurationItem") || command == "GetWindowTitle" || command == "RunScriptSaveResult" || command == "SetVariable" || command.StartsWith("GetSavedDbDate") || command == "GetTimerValue") { if (_variables.ContainsKey(varKey.ToString())) { _variables.Remove(varKey); } _variables.Add(varKey, result.ReturnValue); } if (command == "DisplayVariable" || command == "DisplayTimerValue") { returnResult.Parameters[0].ReplacedParam = result.ReturnValue; } } if (!result.Success) { if (mngrCommand.IsInverse) returnResult.Message = "Success - Inverse modifier passed failing command. Original error message: " + result.FailureMessage; else returnResult.Message = result.FailureMessage; } } catch (Exception e) { returnResult.Success = false; returnResult.Message = e.Message; if (mngrCommand.Passed && mngrCommand.FinishBlockOnFailure) { _finishBlockOnFailure = true; } } } else { returnResult.Ignored = true; returnResult.ModIgn = true; } TestManager.LogCommand(mngrCommand); } } else if (TestManager.InCompareData) { cleanedCommand = cleanCommand(wikiCommand); cleanedCommand = cleanedCommand.TrimStart('|'); string[] sections = parseSections(cleanedCommand.Substring(0, cleanedCommand.LastIndexOf('|'))); // 1. if endCompareData if (wikiCommand.Contains("EndCompareData")) { returnResult.Command = "EndCompareData"; returnResult.Success = true; mngrCommand.Passed = true; returnResult.Message = "Success"; TestManager.LogCommand(mngrCommand); TestManager.InCompareData = false; } else { //StringCollection rowParameters = new StringCollection(); for (int i = 0; i < sections.Length; i++) { string replace = ""; replace = replaceVar(sections[i]); //rowParameters.Add(replace); var paramEntry = new CommandResult.ParameterEntry { OriginalParam = sections[i], ReplacedParam = replace }; returnResult.Parameters.Add(paramEntry); } // 2. if _inCompareDataIndex = 0 we are reading the columns if (_inCompareDataIndex == 0) { _compareDatafieldNames = new List<string>(); for (int colIndex = 0; colIndex < returnResult.Parameters.Count; colIndex++) { _compareDatafieldNames.Add(returnResult.Parameters[colIndex].ReplacedParam); } } // 3. otherwise we are now looking at actual row of data else { for (int colIndex = 0; colIndex < _compareDatafieldNames.Count; colIndex++) { StringCollection parameters = new StringCollection(); int dataRowIndex = _inCompareDataIndex - 1; parameters.Add(dataRowIndex.ToString()); parameters.Add(_compareDatafieldNames[colIndex]); parameters.Add(returnResult.Parameters[colIndex].ReplacedParam); InvokeResult result = _invokeManager.Invoke("AssertRecordValuesByColumnName", parameters); if (!result.Success) returnResult.Message = result.FailureMessage; returnResult.CompareDataResults.Add(result.Success.ToString()); } } _inCompareDataIndex++; } } else { returnResult.Ignored = true; returnResult.ModIgn = false; if (wikiCommand.StartsWith("{{{")) inComment = true; if (wikiCommand.EndsWith("}}}")) inComment = false; } Exit: if (!commandLineMode) CommandProcessed(returnResult); } }