private static void GetAllAssembly(Assembly assembly, StringCollection stringCollection) { string location = assembly.Location; if (!stringCollection.Contains(location)) { stringCollection.Add(location); } }
//public static bool IsComment(SiteInfo siteInfo, int channelId, string administratorName) //{ // return siteInfo.Additional.IsCommentable && AdminUtility.HasChannelPermissions(administratorName, siteInfo.Id, channelId, ConfigManager.Permissions.Channel.CommentCheck, ConfigManager.Permissions.Channel.CommentDelete); //} public static string GetColumnsHeadHtml(List <TableStyleInfo> tableStyleInfoList, StringCollection attributesOfDisplay, SiteInfo siteInfo) { var builder = new StringBuilder(); var styleInfoList = ContentUtility.GetAllTableStyleInfoList(tableStyleInfoList); foreach (var styleInfo in styleInfoList) { if (!attributesOfDisplay.Contains(styleInfo.AttributeName) || styleInfo.AttributeName == ContentAttribute.Title) { continue; } builder.Append($@"<th class=""text-nowrap"">{styleInfo.DisplayName}</th>"); } return(builder.ToString()); }
public void AddInMemoryImageClipsToTrack() { var tempFiles = new StringCollection(); Action <IClip> addClip = delegate(IClip clip) { if (tempFiles.Contains(clip.File.FileName)) { Assert.Fail("TempFile: {0} duplicated", clip.File.FileName); } }; string outputFile = "AddInMemoryImageClipsToTrack.wmv"; Image image = Image.FromFile("..\\..\\image1.jpg"); using (ITimeline timeline = new DefaultTimeline()) { timeline.AddAudioGroup().AddTrack().AddAudio("..\\..\\testinput.wav", 0, 7.5); ITrack videoTrack = timeline.AddVideoGroup(24, 320, 200).AddTrack(); addClip(videoTrack.AddImage(image)); // 0->1 addClip(videoTrack.AddImage(image, 1)); // 2->3 addClip(videoTrack.AddImage(image, 1, 0.5)); // 4->4.5 addClip(videoTrack.AddImage(image, InsertPosition.Absolute, 5, 0, 1)); // 5->6 IClip clip = videoTrack.AddImage("named", image, InsertPosition.Absolute, 7, 0.5, 1); // 7->7.5 addClip(clip); Assert.AreEqual("named", clip.Name); Assert.AreEqual(7.5, videoTrack.Duration); using ( var renderer = new WindowsMediaRenderer(timeline, outputFile, WindowsMediaProfiles.HighQualityVideo) ) { renderer.Render(); } } foreach (string file in tempFiles) { Assert.IsFalse(File.Exists(file)); } }
public void LoadData(StringCollection currentLanguages) { System.Globalization.CultureInfo[] cs = System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures); SortedList <string, CultureInfo> list = new SortedList <string, CultureInfo>(); for (int i = 0; i < cs.Length; i++) { if (!string.IsNullOrEmpty(cs[i].Name)) { if (_specificCulture) { if (cs[i].Name.IndexOf('-') < 0) { continue; } } if (string.CompareOrdinal("zh-CHS", cs[i].Name) == 0) { if (!list.ContainsKey("zh")) { list.Add("zh", cs[i]); } } list.Add(cs[i].Name, cs[i]); } } IEnumerator <KeyValuePair <string, CultureInfo> > ie = list.GetEnumerator(); while (ie.MoveNext()) { int n; if (string.CompareOrdinal("zh", ie.Current.Key) == 0) { n = checkedListBox1.Items.Add(new CultureZh()); } else { n = checkedListBox1.Items.Add(new Cultrue(ie.Current.Value)); } if (currentLanguages != null && currentLanguages.Contains(ie.Current.Key)) { checkedListBox1.SetItemChecked(n, true); } } }
private void validatingEditors() { if (_editorList == null) { _editorList = new WebDataEditorList(this); } else { int n = FieldCount; StringCollection fieldNames = new StringCollection(); for (int j = 0; j < n; j++) { fieldNames.Add(GetFieldNameByIndex(j).ToLowerInvariant()); } //remove invalid editors StringCollection sc = new StringCollection(); for (int i = 0; i < _editorList.Count; i++) { bool isValid = false; if (!string.IsNullOrEmpty(_editorList[i].ValueField)) { string s = _editorList[i].ValueField.ToLowerInvariant(); isValid = fieldNames.Contains(s); } if (!isValid) { sc.Add(_editorList[i].ValueField); } } for (int i = 0; i < sc.Count; i++) { _editorList.RemoveEditorByName(sc[i]); } //add missing editors for (int j = 0; j < n; j++) { if (_editorList.GetEditorByName(fieldNames[j]) == null) { WebDataEditorNone wn = new WebDataEditorNone(); wn.ValueField = GetFieldNameByIndex(j); _editorList.AddEditor(wn); } } } }
/// <summary> /// Resolves the profiles. /// </summary> /// <param name="dateRuleProfiles">The date rule profile names.</param> /// <param name="calendarNames">The calendar names.</param> public DateRuleParser(string[] calendarNames, List <DateRuleProfile> dateRuleProfiles) { DateRuleProfiles = dateRuleProfiles; CalendarNames = calendarNames; var resolvedNames = new StringCollection(); var resolvedFpmlNames = new StringCollection(); var resolvedCultures = new List <CultureInfo>(); var resolvedCalendars = new List <Calendar>(); Boolean bExists = true; InValidCentres = new List <string>(); foreach (string calendarName in calendarNames) { string calendarName1 = calendarName; DateRuleProfile dateRuleProfile = dateRuleProfiles.Find( profile => (String.Compare(profile.name, calendarName1, StringComparison.OrdinalIgnoreCase) == 0) || (String.Compare(profile.fPmlIdentifier, calendarName1, StringComparison.OrdinalIgnoreCase) == 0) ); if (dateRuleProfile == null) { InValidCentres.Add(calendarName); bExists = false; } else { CultureInfo resolvedCulture = dateRuleProfile.culture.Length > 0 ? CultureInfo.CreateSpecificCulture(dateRuleProfile.culture) : CultureInfo.InvariantCulture; if (!resolvedNames.Contains(dateRuleProfile.name)) { resolvedNames.Add(dateRuleProfile.name); resolvedFpmlNames.Add(dateRuleProfile.fPmlIdentifier); resolvedCultures.Add(resolvedCulture); resolvedCalendars.Add(resolvedCulture.Calendar); } } } IsValidCalendar = bExists; Name = new string[resolvedNames.Count]; FpmlName = new string[resolvedFpmlNames.Count]; Culture = new CultureInfo[resolvedCultures.Count]; Calendar = new Calendar[resolvedCalendars.Count]; resolvedNames.CopyTo(Name, 0); resolvedFpmlNames.CopyTo(FpmlName, 0); resolvedCultures.CopyTo(Culture, 0); resolvedCalendars.CopyTo(Calendar, 0); }
private SiteMapNode GetNodeFromProvider(string providerName) { SiteMapProvider provider = GetProviderFromName(providerName); SiteMapNode node = null; // Check infinite recursive sitemap files if (provider is XmlSiteMapProvider) { XmlSiteMapProvider xmlProvider = (XmlSiteMapProvider)provider; StringCollection parentSiteMapFileCollection = new StringCollection(); if (_parentSiteMapFileCollection != null) { foreach (string filename in _parentSiteMapFileCollection) { parentSiteMapFileCollection.Add(filename); } } // Make sure the provider is initialized before adding to the collection. xmlProvider.BuildSiteMap(); parentSiteMapFileCollection.Add(_normalizedVirtualPath.VirtualPathString); if (parentSiteMapFileCollection.Contains(VirtualPath.GetVirtualPathString(xmlProvider._normalizedVirtualPath))) { throw new InvalidOperationException(SR.GetString(SR.XmlSiteMapProvider_FileName_already_in_use, xmlProvider._virtualPath)); } xmlProvider._parentSiteMapFileCollection = parentSiteMapFileCollection; } node = provider.GetRootNodeCore(); if (node == null) { throw new InvalidOperationException( SR.GetString(SR.XmlSiteMapProvider_invalid_GetRootNodeCore, ((ProviderBase)provider).Name)); } ChildProviderTable.Add(provider, node); _childProviderList = null; provider.ParentProvider = this; return(node); }
private bool IsPrimaryKey(String tableName, String columnName) { IDataReader r = null; try { // Don't do anything if no table or column is given if ((tableName == "") || (columnName == "")) { return(false); } if (currTable != tableName) { currTable = tableName; pkList.Clear(); r = db.ExecuteReader( "select u2.column_name " + "from user_constraints u1, " + " user_cons_columns u2 " + "where u1.table_name = '" + tableName + "' " + "and constraint_type = 'P' " + "and u1.owner = u2.owner " + "and u1.constraint_name = u2.constraint_name " + "and u1.table_name = u2.table_name " + "order by position"); while (r.Read()) { String ss = r.GetString(0); pkList.Add(ss); } } } finally { if (r != null) { r.Close(); } } return(pkList.Contains(columnName)); }
public StringCollection GetInsertedItems(string propertyName) { var col = new StringCollection(); if (!props.ContainsKey("@" + propertyName)) { return(col); //никаких изменений не внесено } StringCollection nw = Str2Collection(props["@" + propertyName]); StringCollection ld = Str2Collection(props.ContainsKey(propertyName) ? props[propertyName] : ""); foreach (string id in nw.Cast <string>().Where(id => !ld.Contains(id))) { col.Add(id); } return(col); }
public void LoadCategoryStates() { StringCollection expandedPresets = this.userSettingService.GetUserSetting <StringCollection>(UserSettingConstants.PresetExpandedStateList); if (expandedPresets == null || expandedPresets.Count == 0) { return; } foreach (IPresetObject presetObject in this.presets) { PresetDisplayCategory category = presetObject as PresetDisplayCategory; if (category != null && expandedPresets.Contains(category.Category)) { category.IsExpanded = true; } } }
/// <summary> /// Update the MRU list with the specified project filename by /// adding it to the list or making it the most recently used. /// </summary> private static void UpdateMruList(string projectFile) { StringCollection mruList = Settings.Default.MruList; projectFile = Path.GetFullPath(projectFile); if (mruList.Contains(projectFile)) { mruList.Remove(projectFile); } mruList.Insert(0, projectFile); while (mruList.Count > 10) { mruList.RemoveAt(9); } }
public string GetRawCacheKey(StringCollection includeVaryByKeys, StringCollection excludeVaryByKeys, SortedDictionary <string, string> varyBy) { var cacheKey = new StringBuilder(); if (varyBy != null) { SortedDictionary <string, string> .Enumerator varyByParms = varyBy.GetEnumerator(); while ((varyByParms.MoveNext())) { string key = varyByParms.Current.Key.ToLower(); if (includeVaryByKeys.Contains(key) && !excludeVaryByKeys.Contains(key)) { cacheKey.Append(string.Concat(key, "=", varyByParms.Current.Value, "|")); } } } return(cacheKey.ToString()); }
// Load fueltype defaults private FuelTypesInfo _LoadFuelTypesDefaults(FuelTypesDefaults fuelTypesConfig) { FuelTypesInfo fuelTypesInfo = new FuelTypesInfo(); StringCollection uniqueNames = new StringCollection(); foreach (FuelTypeConfig fuelTypeConfig in fuelTypesConfig.FuelTypeConfig) { if (!uniqueNames.Contains(fuelTypeConfig.Name)) { // added only unique named types FuelTypeInfo fuelTypeInfo = new FuelTypeInfo(fuelTypeConfig.Name, fuelTypeConfig.Price, fuelTypeConfig.Co2Emission); fuelTypesInfo.Add(fuelTypeInfo); uniqueNames.Add(fuelTypeConfig.Name); } } return(fuelTypesInfo); }
/// <summary> /// 去除字符串数组中的重复项 /// </summary> /// <param name="strs"></param> /// <returns></returns> public static string[] RemoveRepeat(this string[] strs) { StringCollection sc = new StringCollection(); for (int i = 0; i < strs.Length; i++) { if (!sc.Contains(strs[i])) { sc.Add(strs[i]); } } string[] results = new string[sc.Count]; sc.CopyTo(results, 0); return(results); }
public void AddKey(string key) { if (key == null || key.Trim() == "") { throw new Exception("Invalid key value"); } if (_maxKeyCount >= 0 && _maxKeyCount <= _keyList.Count) { throw new Exception("Key count limit exceeded"); } if (_keyList.Contains(key) == false) { this.OnChange(); _keyList.Add(key); } }
private StringCollection GetCustomerCollection4OTD(string country) { StringCollection ret = new StringCollection(); string customer; foreach (DataRow dr in frmInput.ds.Tables["WeeklyOTDActivity"].Rows) { customer = dr["Sales Orders SoldTo - Customer Name"].ToString(); if ((dr["Sales Orders - ShipTo Country"].ToString() == country) && (ret.Contains(customer) == false) && (CustomerNameFilter(customer) == false)) { ret.Add(customer); } } return(ret); }
private void loadAuxilliaryKnowledgeIntoMemory(string i) { bestMatchesList.Clear(); if (botsMemory != null) { List <string> externalAnswers = getExternalAnswers(i); foreach (string a in externalAnswers) { //if(!botsMemory.ContainsKey(i)) // botsMemory.Add(i, a); if (!bestMatchesList.Contains(a)) { bestMatchesList.Add(a); } } } }
/// <summary> /// Update the MRU list with the specified project filename by /// adding it to the list or making it the most recently used. /// </summary> protected void UpdateMostRecentUsedList(string fsmFile) { StringCollection mruList = Settings.Default.MruList; fsmFile = Path.GetFullPath(fsmFile); if (mruList.Contains(fsmFile)) { mruList.Remove(fsmFile); } mruList.Insert(0, fsmFile); while (mruList.Count > 10) { mruList.RemoveAt(9); } }
public virtual void UpdateDataFields(string dataMember, int dataMemberIndex, StringCollection dataFields) { if (!(this.DataMember == dataMember)) { if (!string.IsNullOrEmpty(this.DataMember)) { return; } if (dataMemberIndex != 0) { return; } } if (!dataFields.Contains(this.BindingField)) { this.BindingField = ""; } }
/// <summary> /// Handles the Click event of the btnBatchAdd control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void BtnBatchAdd_Click(object sender, EventArgs eventArgs) { StringCollection col = BlogService.LoadPingServices(); foreach (string service in txtBatchPingService.Text.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)) { if (!col.Contains(service.ToLower())) { col.Add(service); } else { liBatchOutput.Text += service + " " + Resources.labels.pingServiceNotUnique + ".<br/>"; } } BlogService.SavePingServices(col); BindGrid(); }
private StringCollection GetCustomerCollection4OTDNonOnelog(string country) { StringCollection ret = new StringCollection(); string customer; foreach (DataRow dr in frmInput.ds.Tables["OTD-NonOnelog"].Rows) { customer = dr["Customer Name"].ToString(); if ((dr["Country"].ToString() == country) && (ret.Contains(customer) == false) && (CustomerNameFilter(customer) == false)) { ret.Add(customer); } } return(ret); }
/// <summary> /// Looks for a given path in the list of paths excluded from compression /// </summary> /// <param name="relUrl">the relative url to check</param> /// <returns>true if excluded, false if not</returns> public bool IsExcludedPath(string relUrl) { // 排除 .axd 和图片 string fileExt = Path.GetExtension(relUrl); if (!string.IsNullOrEmpty(fileExt) && (fileExt.ToLower() == ".axd" || fileExt.ToLower() == ".jpg" || fileExt.ToLower() == ".png" || fileExt.ToLower() == ".gif" || fileExt.ToLower() == ".bmp" )) { return(true); } return(_excludedPaths.Contains(relUrl.ToLower())); }
//for Selection without grouping id in from pxs public PXSqlGrouping(GroupingRow groupingRow, PXSqlMeta_21 meta, PXSqlVariableClassification var, GroupingIncludesType include) { Init(groupingRow, meta, var); //TODO overriding include from paxiom, have to discuss how paxion can override database default. this.mIncludeType = include; // DONE, is now passed to paxiom as part of GroupingInfo ... this.mIncludeType = this.mDefaultIncludeType; //TODO end StringCollection tempParentList = new StringCollection(); mGroups = new List <PXSqlGroup>(); PXSqlGroup tmpGroup = null; foreach (VSGroupRow myRow in meta.MetaQuery.GetVSGroupRowsSorted(mValuePoolId, mValuesetIds, mGroupingId, meta.MainLanguageCode)) { if (!tempParentList.Contains(myRow.GroupCode)) { tmpGroup = new PXSqlGroup(myRow.GroupCode); mGroups.Add(tmpGroup); tempParentList.Add(myRow.GroupCode); } else { foreach (PXSqlGroup group in mGroups) { if (group.ParentCode == myRow.GroupCode) { tmpGroup = group; break; } } } tmpGroup.AddChildCode(myRow.ValueCode); } // Add the values to valuecollection of this variable AddValues(mValuePoolId, tempParentList, valuePoolValueTextExists); //PXSqlValue tempValue; // foreach (ValueRow row in meta.MetaQuery.GetValueRowsByValuePool(mValuePoolId, tempParentList, valuePoolValueTextExists)) //{ // tempValue = new PXSqlValue(row, meta.LanguageCodes, meta.MainLanguageCode); // var.Values.Add(tempValue.ValueCode,tempValue); //} }
/// <summary> /// Neem voor de Last-recent-used list met de gegeven naam t, /// de meegegeven filename op. /// Check eerst of ie al in de lijst staat en haal hem eruit, zet hem dan /// op positie 0 er weer in en sla de lijst op. /// </summary> /// <param name="t"></param> /// <param name="filename"></param> private void RegisterFor(string t, string filename) { StringCollection strings = CollectLruListFor(t); if (strings.Contains(filename)) { strings.Remove(filename); } strings.Insert(0, filename); RegistryKey masterkey = GetOurKey(); for (int i = 0; i < MAX_RECENTLYUSED_TO_REMEMBER && i < strings.Count; i++) { string valuename = String.Format("{0}_{1}", t, i.ToString()); masterkey.SetValue(valuename, strings[i], RegistryValueKind.String); } masterkey.Flush(); }
private static StringCollection LoadThemeClasses() { StringCollection ThemeClasses = new StringCollection(); foreach (Theme thm in Theme.GetAll(UIServices.KB.CurrentModel)) { KBDoctorOutput.Message("Procesing theme .." + thm.Name); ThemeStylesPart part = thm.Parts.Get <ThemeStylesPart>(); foreach (Artech.Genexus.Common.Objects.Themes.ThemeStyle thmclass in part.GetAllStyles()) { string thmstr = thmclass.Name; if (!ThemeClasses.Contains(thmstr) && (!(thmstr.Contains("Dragging") || thmstr.Contains("AcceptDrag") || thmstr.Contains("NoAcceptDrag")))) //Excluyo clases especiales { ThemeClasses.Add(thmstr.ToLower()); } } } return(ThemeClasses); }
private static void ZipDirectoryRecursive(String ARootDirectory, String ADirectory, ref ZipOutputStream zs, StringCollection AExcludeDirectories) { ZipEntry entry; FileStream fs; Int32 sourcebytes = 0; byte[] buffer = new byte[2096]; // if ADirectory in AExcludeDirectories then exit if ((AExcludeDirectories != null) && (AExcludeDirectories.Contains(Path.GetFileName(ADirectory)))) { return; } string[] directories = System.IO.Directory.GetDirectories(ADirectory); foreach (string dir in directories) { ZipDirectoryRecursive(ARootDirectory, dir, ref zs, AExcludeDirectories); } string[] files = System.IO.Directory.GetFiles(ADirectory); foreach (string filename in files) { // Console.WriteLine('adding to zip ' + Path.GetFullPath(filename).tostring().Substring(ARootDirectory.Length+1)); entry = new ZipEntry(Path.GetFullPath(filename).Substring(ARootDirectory.Length + 1)); entry.DateTime = System.IO.File.GetLastWriteTime(filename); zs.PutNextEntry(entry); fs = System.IO.File.OpenRead(filename); do { sourcebytes = fs.Read(buffer, 0, buffer.Length); zs.Write(buffer, 0, sourcebytes); } while (sourcebytes > 0); fs.Close(); } }
/// <summary> /// 获取表所拥有的列列表 /// </summary> /// <param name="table"></param> /// <returns></returns> public override List <SOColumn> GetTableColumnList(SOTable table) { string cmdText = string.Format(@"select c.COLUMN_ID,c.COLUMN_NAME,c.DATA_TYPE,c.DATA_LENGTH,c.DATA_PRECISION,c.DATA_SCALE,c.NULLABLE,c.DATA_DEFAULT,c.CHAR_COL_DECL_LENGTH,c.CHAR_LENGTH,cc.COMMENTS from dba_tab_columns c left join dba_col_comments cc on c.table_name=cc.table_name and c.column_name=cc.column_name where c.owner='{0}' and cc.owner='{0}' and c.table_name='{1}' order by c.column_id", table.Database.Name, table.Name); List <SOColumn> columnList = new List <SOColumn>(); List <string> pkList = GetPrimaryKeys(table); DataTable dt = this.DbProvider.ExecuteDataSet(System.Data.CommandType.Text, cmdText).Tables[0]; StringCollection sc = new StringCollection(); foreach (DataRow row in dt.Rows) { SOColumn column = new SOColumn { Parent = table, Name = row["COLUMN_NAME"].ToString(), DefaultValue = row["DATA_LENGTH"].ToString(), Nullable = row["NULLABLE"].ToString().ToUpper() == "Y", NativeType = row["DATA_TYPE"].ToString().Replace(" identity", ""), //Identify = row["type_name"].ToString().IndexOf("identity") != -1, Identify = false, //ForeignKey Length = ConvertUtil.ToInt32(row["CHAR_LENGTH"], 0), Precision = ConvertUtil.ToInt32(row["DATA_PRECISION"], 0), Scale = ConvertUtil.ToInt32(row["DATA_SCALE"], 0), Comment = row["COMMENTS"].ToString() }; column.PrimaryKey = pkList.Contains(column.Name); column.DataType = this.GetDbType(column.NativeType, column.Precision, column.Scale); if (!sc.Contains(column.Name)) { columnList.Add(column); } sc.Add(column.Name); } return(columnList); }
private string[] getGARCs() { StringCollection sc = new StringCollection(); foreach (int indexChecked in CHKLB_GARCs.CheckedIndices) { sc.Add(CHKLB_GARCs.Items[indexChecked].ToString()); } string[] rtbLines = RTB_GARCs.Lines; foreach (string s in rtbLines.Where(s => s.Length == 7 && !sc.Contains(s.Replace('/', Path.DirectorySeparatorChar)))) { sc.Add(s.Replace('/', Path.DirectorySeparatorChar)); } string[] garcs = new string[sc.Count]; sc.CopyTo(garcs, 0); return(garcs.Distinct().ToArray()); }
internal static StringCollection GetBaseVlcInstanceArguments() { var result = new StringCollection(); result.Add("-I"); result.Add("dummy"); //result.Add("--no-snapshot-preview"); if (StartupOptions.IgnoreConfig) { result.Add("--ignore-config"); } result.Add("--plugin-path=" + LibVlcPluginsPath); if (!StartupOptions.ScreenSaverEnabled) { result.Add("--disable-screensaver"); } if (!string.IsNullOrEmpty(StartupOptions.UserAgent)) { result.Add("--user-agent=" + StartupOptions.UserAgent); } if (StartupOptions.LogOptions != null && StartupOptions.LogOptions.Verbosity != VlcLogVerbosities.None) { if (StartupOptions.LogOptions.ShowLoggerConsole) { result.Add("--extraintf=logger"); } result.Add("--verbose=" + (int)StartupOptions.LogOptions.Verbosity); if (StartupOptions.LogOptions.LogInFile) { result.Add("--file-logging"); result.Add(@"--logfile=" + StartupOptions.LogOptions.LogInFilePath); } } foreach (var vlcStartupOption in StartupOptions.Options) { if (!result.Contains(vlcStartupOption)) { result.Add(vlcStartupOption); } } return(result); }
/// <summary> /// Returns a percentage of 1 on how many words were matched /// </summary> /// <returns></returns> private decimal CompareText(string formHeading, string userSearch) { StringCollection formHeadingWords = new StringCollection(); StringCollection userSearchWords = new StringCollection(); formHeadingWords.AddRange(System.Text.RegularExpressions.Regex.Split(formHeading, @"\W")); userSearchWords.AddRange(System.Text.RegularExpressions.Regex.Split(userSearch, @"\W")); int wordsFound = 0; for (int i1 = 0; i1 < userSearchWords.Count; i1++) { if (formHeadingWords.Contains(userSearchWords[i1])) { wordsFound += 1; } } return(Convert.ToDecimal(wordsFound) / Convert.ToDecimal(formHeadingWords.Count)); }
public void Test01() { StringCollection sc; // [] StringCollection is constructed as expected //----------------------------------------------------------------- sc = new StringCollection(); // [] compare to null // if (sc == null) { Assert.False(true, string.Format("Error, collection is null after default ctor")); } // [] check Count // if (sc.Count != 0) { Assert.False(true, string.Format("Error, Count = {0} after default ctor", sc.Count)); } // [] check more properties // if (sc.Contains("string")) { Assert.False(true, string.Format("Error, Contains() returned true after default ctor")); } if (sc.IsReadOnly) { Assert.False(true, string.Format("Error, IsReadOnly returned {0}", sc.IsReadOnly)); } // // IsSynchronized = false by default // if (sc.IsSynchronized) { Assert.False(true, string.Format("Error, IsSynchronized returned {0}", sc.IsSynchronized)); } }
// Main entry point for the application. public static int Main(String[] args) { #if CONFIG_EXTENDED_NUMERICS && CONFIG_REFLECTION StreamReader reader = null; int len; VsaEngine engine; IVsaCodeItem item; StringCollection scripts = new StringCollection(); // Create an engine instance and add the script to it. engine = VsaEngine.CreateEngine(); engine.SetOption("print", true); // get command-line arguments int i = 0; String arg = args.Length == 0 ? null : args[0]; while(arg != null) { String next = null; if (arg.StartsWith("-") && !arg.StartsWith("--") && arg.Length > 2) { next = "-" + arg.Substring(2, arg.Length - 2); arg = arg.Substring(0,2); } switch(arg) { case "-h": case "--help": Usage(); return 0; case "-v": case "--version": Version(); return 0; default: // matches both short and long options. (-/--) if (arg.StartsWith("-")) { #if !CONFIG_SMALL_CONSOLE Console.Error.WriteLine #else Console.WriteLine #endif ("jsrun: unkown option `{0}'", arg); return 1; } // not an option - assumes script path else { // To prevent a relative and a absolute pathname to same file! FileInfo fi = new FileInfo(arg); if(!fi.Exists) { #if !CONFIG_SMALL_CONSOLE Console.Error.WriteLine #else Console.WriteLine #endif ("jsrun: {0}: No such file or directory", arg); return 1; } // Cannot load same script source twice! if(scripts.Contains(fi.FullName)) { #if !CONFIG_SMALL_CONSOLE Console.Error.WriteLine #else Console.WriteLine #endif ("jsrun: {0}: use of duplicate sources illegal.", fi.FullName); } else { scripts.Add(fi.FullName); } // Load script file try { reader = new StreamReader(arg); } catch(Exception e) { #if !CONFIG_SMALL_CONSOLE Console.Error.WriteLine #else Console.WriteLine #endif ("jsrun: ({0}): {1}", e.GetType(), e.Message); } // Load the script into memory as a string. StringBuilder scriptBuilder = new StringBuilder(); char[] scriptBuffer = new char [512]; while((len = reader.Read(scriptBuffer, 0, 512)) > 0) { scriptBuilder.Append(scriptBuffer, 0, len); } reader.Close(); item = (IVsaCodeItem)(engine.Items.CreateItem (String.Concat("script",engine.Items.Count+1), VsaItemType.Code, VsaItemFlag.None)); item.SourceText = scriptBuilder.ToString(); item.SetOption("codebase", arg); } break; } // switch(arg) if(next != null) { arg = next; } else if(i + 1 >= args.Length) { arg = null; } else { i = i + 1; arg = args[i]; } } // for each in args // We need at least one item. if(engine.Items.Count == 0) { Usage(); return 1; } // Compile and run the script. if(!engine.Compile()) { #if !CONFIG_SMALL_CONSOLE Console.Error.WriteLine #else Console.WriteLine #endif ("jsrun: Could not compile script"); return 1; } engine.Run(); // Shut down the engine and exit. engine.Close(); return 0; #else // Use error output and exit status in case any // script/program is depending on output. #if !CONFIG_SMALL_CONSOLE Console.Error.WriteLine #else Console.WriteLine #endif ("JScript is not available in this configuration " + "because the library does\n" + "not have sufficient features to support JScript."); return 1; #endif }
public static void Optimize(ArrayList list) { for (int i = 1; i < list.Count; i++) { X86Code x0 = list[i] as X86Code; if (x0 == null || x0.ignore || x0.IsBrTarget) continue; ArrayList listx = new ArrayList(); listx.Add(x0); for (int j = 1;; j++) { X86Code xx = GetPrevious(list, i, j); if (xx == null) break; listx.Add(xx); } if (listx.Count < 2) continue; X86Code[] x = listx.ToArray(typeof(X86Code)) as X86Code[]; if (IsMovEtc(x[0].Mnemonic) && !IsXS(x[0].Operand1) && IsXX(x[0].Operand2) && x[0].Operand1 != x[0].Operand2) { for (int j = 1; j < x.Length; j++) { if (x[j].Mnemonic == "mov" && x[j].Operand1 == x[0].Operand2 && !IsXS(x[j].Operand2) && !(IsAddr(x[0].Operand1) && IsAddr(x[j].Operand2))) { if (x[0].Operand1 != x[j].Operand2 && (IsXX(x[0].Operand1) || IsXX(x[j].Operand2))) { x[j].Ignore(); x[0].Ignore(); X86Code xx = new X86Code(x[0].Mnemonic, x[0].Operand1, x[j].Operand2); xx.Notes = "[optimize] add"; list.Insert(i + 1, xx); } } else if (IsMovEtc(x[j].Mnemonic) && x[j].Operand1 != x[0].Operand2) { continue; } break; } if (x[0].ignore) continue; } switch (x[0].Mnemonic) { case "pop": { Hashtable t = new Hashtable(); for (int j = 1; j < x.Length; j++) { if (x[j].Mnemonic == "push") { if (!t.Contains(x[j].Operand1)) { if (x[j].Operand1 == x[0].Operand1) { x[j].Ignore(); x[0].Ignore(); } else if (IsXX(x[j].Operand1) || IsXX(x[0].Operand1)) { x[j].Ignore(); x[0].Ignore(); X86Code xx = new X86Code("mov", x[0].Operand1, x[j].Operand1); xx.Notes = "[optimize] add"; list.Insert(i + 1, xx); } } else if (!t.Contains(x[0].Operand1)) { if (IsXX(x[j].Operand1) || IsXX(x[0].Operand1)) { x[j].Ignore(); x[0].Ignore(); X86Code xx = new X86Code("mov", x[0].Operand1, x[j].Operand1); xx.Notes = "[optimize] add"; i = list.IndexOf(x[j]); list.Insert(i + 1, xx); } } } else if (IsMovEtc(x[j].Mnemonic)) { t[x[j].Operand1] = true; continue; } break; } break; } case "cmp": if (IsXX(x[0].Operand1) && IsDigit(x[0].Operand2)) { for (int j = 1; j < x.Length; j++) { if (x[j].Mnemonic == "mov" && x[j].Operand1 == x[0].Operand1) { x[j].Ignore(); x[0].Ignore(); X86Code xx = new X86Code("cmp", x[j].Operand2, x[0].Operand2); xx.Notes = "[optimize] add"; list.Insert(i + 1, xx); } else if (IsMovEtc(x[j].Mnemonic) && x[j].Operand1 != x[0].Operand1) { continue; } break; } } break; case "je": case "jne": case "jz": case "jnz": if (x[1].Mnemonic == "cmp" && IsXX(x[1].Operand1) && !IsDigit(x[1].Operand2)) { for (int j = 2; j < x.Length; j++) { if (x[j].Mnemonic == "mov" && x[j].Operand1 == x[1].Operand1) { x[j].Ignore(); x[1].Ignore(); X86Code xx = new X86Code("cmp", x[1].Operand2, x[j].Operand2); xx.Notes = "[optimize] add"; i = list.IndexOf(x[1]); list.Insert(i + 1, xx); } else if (IsMovEtc(x[j].Mnemonic) && x[j].Operand1 != x[1].Operand1) { continue; } break; } } break; case "mov": if (x.Length > 2 && IsAddEtc(x[1].Mnemonic) && x[2].Mnemonic == "mov" && x[0].Operand2 == x[1].Operand1 && x[1].Operand1 == x[2].Operand1) { if (x[1].Mnemonic == "inc" || x[1].Mnemonic == "dec") { x[2].Ignore(); x[1].Ignore(); x[0].Ignore(); X86Code xx = new X86Code(x[1].Mnemonic, x[0].Operand1); xx.Notes = "[optimize] add"; list.Insert(i + 1, xx); } else if (x[0].Operand1 == x[1].Operand2 && !IsAddr(x[2].Operand2)) { x[2].Ignore(); x[1].Ignore(); x[0].Ignore(); X86Code xx = new X86Code(x[1].Mnemonic, x[0].Operand1, x[2].Operand2); xx.Notes = "[optimize] add"; list.Insert(i + 1, xx); } else if (x[0].Operand1 == x[2].Operand2 && !IsAddr(x[1].Operand2)) { x[2].Ignore(); x[1].Ignore(); x[0].Ignore(); X86Code xx = new X86Code(x[1].Mnemonic, x[0].Operand1, x[1].Operand2); xx.Notes = "[optimize] add"; list.Insert(i + 1, xx); } } break; case "add": if (x[0].Operand2 == "1") { x[0].Ignore(); X86Code xx = new X86Code("inc", x[0].Operand1); xx.Notes = "[Optimize] add"; list.Insert(i + 1, xx); } break; case "sub": if (x[0].Operand2 == "1") { x[0].Ignore(); X86Code xx = new X86Code("dec", x[0].Operand1); xx.Notes = "[Optimize] add"; list.Insert(i + 1, xx); } break; } } StringCollection jmp = new StringCollection(); for (int i = 0; i < list.Count; i++) { X86Code x = list[i] as X86Code; if (x == null || x.ignore) continue; if (x.Mnemonic == "mov" && X86Code.IsXX(x.Operand1) && x.Operand2 == "0") { x.Ignore(); X86Code xx = new X86Code("xor", x.Operand1, x.Operand1); xx.Notes = "[optimize] add"; list.Insert(i + 1, xx); } else if (x.Mnemonic == "mov" && x.Operand1 == x.Operand2) { x.Ignore(); } else if (x.Mnemonic.StartsWith("j")) { jmp.Add(x.Operand1); } } for (int i = 0; i < list.Count; i++) { X86Code x = list[i] as X86Code; if (x == null) continue; if (x.IsBrTarget && !jmp.Contains(x.Label)) x.IsBrTarget = false; } }
public virtual bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver: " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; IntlStrings intl; String strLoc = "Loc_000oo"; StringCollection sc; string [] values = { "", " ", "a", "aa", "text", " spaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; int cnt = 0; try { intl = new IntlStrings(); Console.WriteLine("--- create collection ---"); strLoc = "Loc_001oo"; iCountTestcases++; sc = new StringCollection(); Console.WriteLine("1. add simple strings"); iCountTestcases++; cnt = sc.Count; sc.AddRange(values); if (sc.Count != values.Length) { iCountErrors++; Console.WriteLine("Err_0001, count is {0} instead of {1}", sc.Count, values.Length); } Console.WriteLine("2. verify that collection contains all added items"); strLoc = "Loc_002oo"; for (int i = 0; i < values.Length; i++) { iCountTestcases++; if (!sc.Contains(values[i])) { iCountErrors++; Console.WriteLine("Err_0002_{0}, collection doesn't contain new item", i); } } Console.WriteLine("3. add intl strings"); string [] intlValues = new string [values.Length]; for (int i = 0; i < values.Length; i++) { string val = intl.GetString(MAX_LEN, true, true, true); while (Array.IndexOf(intlValues, val) != -1 ) val = intl.GetString(MAX_LEN, true, true, true); intlValues[i] = val; } strLoc = "Loc_003oo"; cnt = sc.Count; Console.WriteLine(" initial number of items: " + cnt); iCountTestcases++; sc.AddRange(intlValues); if (sc.Count != (cnt + intlValues.Length)) { iCountErrors++; Console.WriteLine("Err_0003, count is {0} instead of {1}", sc.Count, cnt + intlValues.Length); } Console.WriteLine("4. verify that collection contains all added items"); strLoc = "Loc_004oo"; for (int i = 0; i < intlValues.Length; i++) { iCountTestcases++; iCountTestcases++; if (!sc.Contains(intlValues[i])) { iCountErrors++; Console.WriteLine("Err_0004_{0}, collection doesn't contain new item", i); } } Console.WriteLine("5. add empty range"); strLoc = "Loc_005oo"; iCountTestcases++; cnt = sc.Count; string [] empty = {}; sc.AddRange(empty); if (sc.Count != cnt) { iCountErrors++; Console.WriteLine("Err_0005, count is {0} instead of {1}", sc.Count, cnt); } } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_general! strLoc=="+ strLoc +", exc_general==\n"+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "Pass. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.WriteLine("Fail! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }
/// <summary> /// Invokes the FindServers service. /// </summary> /// <param name="requestHeader">The request header.</param> /// <param name="endpointUrl">The endpoint URL.</param> /// <param name="localeIds">The locale ids.</param> /// <param name="serverUris">The server uris.</param> /// <param name="servers">List of Servers that meet criteria specified in the request.</param> /// <returns> /// Returns a <see cref="ResponseHeader"/> object /// </returns> public override ResponseHeader FindServers( RequestHeader requestHeader, string endpointUrl, StringCollection localeIds, StringCollection serverUris, out ApplicationDescriptionCollection servers) { servers = new ApplicationDescriptionCollection(); ValidateRequest(requestHeader); lock (m_lock) { // parse the url provided by the client. IList<BaseAddress> baseAddresses = BaseAddresses; Uri parsedEndpointUrl = Utils.ParseUri(endpointUrl); if (parsedEndpointUrl != null) { baseAddresses = FilterByEndpointUrl(parsedEndpointUrl, baseAddresses); } // check if nothing to do. if (baseAddresses.Count == 0) { servers = new ApplicationDescriptionCollection(); return CreateResponse(requestHeader, StatusCodes.Good); } // build list of unique servers. Dictionary<string,ApplicationDescription> uniqueServers = new Dictionary<string,ApplicationDescription>(); foreach (EndpointDescription description in GetEndpoints()) { ApplicationDescription server = description.Server; // skip servers that have been processed. if (uniqueServers.ContainsKey(server.ApplicationUri)) { continue; } // check client is filtering by server uri. if (serverUris != null && serverUris.Count > 0) { if (!serverUris.Contains(server.ApplicationUri)) { continue; } } // localize the application name if requested. LocalizedText applicationName = server.ApplicationName; if (localeIds != null && localeIds.Count > 0) { applicationName = m_serverInternal.ResourceManager.Translate(localeIds, applicationName); } // get the application description. ApplicationDescription application = TranslateApplicationDescription( parsedEndpointUrl, server, baseAddresses, applicationName); uniqueServers.Add(server.ApplicationUri, application); // add to list of servers to return. servers.Add(application); } } return CreateResponse(requestHeader, StatusCodes.Good); }
public virtual bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver: " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; IntlStrings intl; String strLoc = "Loc_000oo"; StringCollection sc; string itm; string [] values = { "", " ", "a", "aa", "text", " spaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; try { intl = new IntlStrings(); Console.WriteLine("--- create collection ---"); strLoc = "Loc_001oo"; iCountTestcases++; sc = new StringCollection(); Console.WriteLine("1. set Item on empty collection"); Console.WriteLine(" (-1)th"); strLoc = "Loc_001oo"; itm = intl.GetString(MAX_LEN, true, true, true); iCountTestcases++; try { sc[-1] = itm; iCountErrors++; Console.WriteLine("Err_0001a, no exception"); } catch (ArgumentOutOfRangeException ex) { Console.WriteLine(" expected exception: " + ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0001b, unexpected exception: {0}", e.ToString()); } Console.WriteLine(" 0th to string"); iCountTestcases++; try { sc[0] = itm; iCountErrors++; Console.WriteLine("Err_0001c, no exception"); } catch (ArgumentOutOfRangeException ex) { Console.WriteLine(" expected exception: " + ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0001d, unexpected exception: {0}", e.ToString()); } Console.WriteLine(" 0th to null"); iCountTestcases++; try { sc[0] = null; iCountErrors++; Console.WriteLine("Err_0001e, no exception"); } catch (ArgumentOutOfRangeException ex) { Console.WriteLine(" expected exception: " + ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0001f, unexpected exception: {0}", e.ToString()); } Console.WriteLine("2. set Item on collection with simple strings"); strLoc = "Loc_002oo"; sc.Clear(); iCountTestcases++; sc.AddRange(values); int cnt = values.Length; if (sc.Count != cnt) { iCountErrors++; Console.WriteLine("Err_0002a, count is {0} instead of {1}", sc.Count, cnt); } for (int i = 0; i < cnt; i++) { iCountTestcases++; sc[i] = values[cnt-i-1]; if (String.Compare(sc[i], values[cnt-i-1], false) != 0) { iCountErrors++; Console.WriteLine("Err_0002_{0}b, value is {1} instead of {2}", i, sc[i], values[cnt-i-1]); } } Console.WriteLine("3. get Item on collection with intl strings"); strLoc = "Loc_003oo"; string [] intlValues = new string [values.Length]; for (int i = 0; i < values.Length; i++) { string val = intl.GetString(MAX_LEN, true, true, true); while (Array.IndexOf(intlValues, val) != -1 ) val = intl.GetString(MAX_LEN, true, true, true); intlValues[i] = val; } int len = values.Length; Boolean caseInsensitive = false; for (int i = 0; i < len; i++) { if(intlValues[i].Length!=0 && intlValues[i].ToLower()==intlValues[i].ToUpper()) caseInsensitive = true; } iCountTestcases++; sc.Clear(); cnt = intlValues.Length; sc.AddRange(intlValues); if ( sc.Count != intlValues.Length ) { iCountErrors++; Console.WriteLine("Err_0003a, count is {0} instead of {1}", sc.Count, intlValues.Length); } for (int i = cnt; i < cnt; i++) { iCountTestcases++; sc[i] = intlValues[cnt-i-1]; iCountTestcases++; if (String.Compare(sc[i], intlValues[cnt-i-1], false) != 0) { iCountErrors++; Console.WriteLine("Err_0003_{0}b, actual item is {1} instead of {2}", i, sc[i], intlValues[cnt-i-1]); } } Console.WriteLine("4. case sensitivity"); strLoc = "Loc_004oo"; string intlStrUpper = intlValues[0]; intlStrUpper = intlStrUpper.ToUpper(); string intlStrLower = intlStrUpper.ToLower(); sc.Clear(); sc.AddRange(values); sc.Add(intlStrUpper); iCountTestcases++; if ( sc.Count != values.Length + 1 ) { iCountErrors++; Console.WriteLine("Err_0004a, count is {0} instead of {1}", sc.Count, values.Length + 1); } sc[0] = intlStrLower; iCountTestcases++; if (!caseInsensitive && (String.Compare(sc[0], intlStrUpper, false) == 0)) { iCountErrors++; Console.WriteLine("Err_0004b, set to uppercase when should have to lower"); } iCountTestcases++; if (String.Compare(sc[0], intlStrLower, false) != 0) { iCountErrors++; Console.WriteLine("Err_0004c, disn't set to lower"); } sc[sc.Count - 1] = intlStrLower; iCountTestcases++; if (!caseInsensitive && (String.Compare(sc[sc.Count - 1], intlStrUpper, false) == 0)) { iCountErrors++; Console.WriteLine("Err_0004b, didn't set from uppercase to lowercase "); } iCountTestcases++; if (String.Compare(sc[sc.Count - 1], intlStrLower, false) != 0) { iCountErrors++; Console.WriteLine("Err_0004c, disn't set to lower"); } Console.WriteLine("5. set to null"); strLoc = "Loc_005oo"; if (sc.Count < 1) sc.AddRange(values); int ind = sc.Count / 2; sc[ind] = null; iCountTestcases++; if (sc[ind] != null) { iCountErrors++; Console.WriteLine("Err_0005a, failed to set to null"); } iCountTestcases++; if (!sc.Contains(null)) { iCountErrors++; Console.WriteLine("Err_0005b, Contains() didn't return truw for null"); } iCountTestcases++; if (sc.IndexOf(null) != ind) { iCountErrors++; Console.WriteLine("Err_0005c, IndexOf() returned {0} instead of {1}", sc.IndexOf(null), ind); } Console.WriteLine("6. set [-1] to string"); sc.Clear(); sc.AddRange(intlValues); Console.WriteLine(" collection contains {0} items", sc.Count); strLoc = "Loc_006oo"; iCountTestcases++; try { sc[-1] = intlStrUpper; iCountErrors++; Console.WriteLine("Err_0006a, no exception"); } catch (ArgumentOutOfRangeException ex) { Console.WriteLine(" expected exception: " + ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0006b, unexpected exception: {0}", e.ToString()); } Console.WriteLine("7. set [Count] to string"); strLoc = "Loc_007oo"; iCountTestcases++; try { sc[sc.Count] = intlStrUpper; iCountErrors++; Console.WriteLine("Err_0007a, no exception"); } catch (ArgumentOutOfRangeException ex) { Console.WriteLine(" expected exception: " + ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0007b, unexpected exception: {0}", e.ToString()); } Console.WriteLine("8. set (Count + 1) to string"); strLoc = "Loc_008oo"; iCountTestcases++; try { sc[sc.Count + 1] = intlStrUpper; iCountErrors++; Console.WriteLine("Err_0008a, no exception"); } catch (ArgumentOutOfRangeException ex) { Console.WriteLine(" expected exception: " + ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0008b, unexpected exception: {0}", e.ToString()); } Console.WriteLine("9. set [Count] to null"); strLoc = "Loc_009oo"; iCountTestcases++; try { sc[sc.Count] = null; iCountErrors++; Console.WriteLine("Err_0009a, no exception"); } catch (ArgumentOutOfRangeException ex) { Console.WriteLine(" expected exception: " + ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0009b, unexpected exception: {0}", e.ToString()); } } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_general! strLoc=="+ strLoc +", exc_general==\n"+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "Pass. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.WriteLine("Fail! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }
/// <summary> /// This can be used to write a calendar to a PDI data stream /// </summary> /// <param name="tw">A <see cref="System.IO.TextWriter"/> derived class to which the calendar is /// written.</param> /// <param name="sb">A <see cref="System.Text.StringBuilder"/> used by the properties as a temporary /// buffer. This can be null if the TextWriter is a <see cref="System.IO.StringWriter"/>.</param> /// <remarks>This is called by <see cref="CalendarObject.ToString"/> as well as owning objects when they /// convert themselves to a string or write themselves to a PDI data stream.</remarks> public override void WriteToStream(TextWriter tw, StringBuilder sb) { PropagateVersion(); tw.Write("BEGIN:VCALENDAR\r\n"); if(this.Version == SpecificationVersions.vCalendar10) tw.Write("VERSION:1.0\r\n"); else tw.Write("VERSION:2.0\r\n"); // The product ID is required for iCalendar 2.0 so we'll enforce it for both specs BaseProperty.WriteToStream(this.ProductId, sb, tw); // Save version-specific properties if(this.Version == SpecificationVersions.vCalendar10) { BaseProperty.WriteToStream(daylight, sb, tw); BaseProperty.WriteToStream(geo, sb, tw); BaseProperty.WriteToStream(tz, sb, tw); } else { BaseProperty.WriteToStream(calScale, sb, tw); BaseProperty.WriteToStream(method, sb, tw); // Time zones are usually listed first. Build a list to see which time zones are needed and // stream only those. StringCollection tzIds = new StringCollection(); this.TimeZonesUsed(tzIds); if(tzIds.Count != 0) { // Lock it while we write the collection out timeZones.Lock.AcquireReaderLock(250); try { foreach(VTimeZone tz in timeZones) if(tzIds.Contains(tz.TimeZoneId.Value)) tz.WriteToStream(tw, sb); } finally { timeZones.Lock.ReleaseReaderLock(); } } if(journals != null && journals.Count != 0) foreach(VJournal j in journals) j.WriteToStream(tw, sb); if(freebusy != null && freebusy.Count != 0) foreach(VFreeBusy f in freebusy) f.WriteToStream(tw, sb); } if(events != null && events.Count != 0) foreach(VEvent v in events) v.WriteToStream(tw, sb); if(todos != null && todos.Count != 0) foreach(VToDo t in todos) t.WriteToStream(tw, sb); if(customProps != null && customProps.Count != 0) foreach(CustomProperty c in customProps) BaseProperty.WriteToStream(c, sb, tw); tw.Write("END:VCALENDAR\r\n"); }
public static void Remove_IListTest(StringCollection collection, string[] data) { Assert.All(data, element => { Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); ((IList)collection).Remove(element); Assert.False(collection.Contains(element)); Assert.False(((IList)collection).Contains(element)); }); Assert.Equal(0, collection.Count); }
public virtual bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver: " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; IntlStrings intl; String strLoc = "Loc_000oo"; StringCollection sc; string [] values = { "", " ", "a", "aa", "text", " spaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; int cnt = 0; int ind = 0; try { intl = new IntlStrings(); Console.WriteLine("--- create collection ---"); strLoc = "Loc_001oo"; iCountTestcases++; sc = new StringCollection(); Console.WriteLine("1. add simple strings"); for (int i = 0; i < values.Length; i++) { iCountTestcases++; cnt = sc.Count; sc.Add(values[i]); if (sc.Count != cnt+1) { iCountErrors++; Console.WriteLine("Err_0001_{0}a, count is {1} instead of {2}", i, sc.Count, cnt+1); } iCountTestcases++; if (!sc.Contains(values[i])) { iCountErrors++; Console.WriteLine("Err_0001_{0}b, collection doesn't contain new item", i); } iCountTestcases++; ind = sc.IndexOf(values[i]); if (ind != sc.Count - 1) { iCountErrors++; Console.WriteLine("Err_0001_{0}c, returned index {1} instead of {2}", i, ind, sc.Count - 1); } if (ind != -1) { iCountTestcases++; if (String.Compare(sc[ind], values[i], false) != 0) { iCountErrors++; Console.WriteLine("Err_0001_{0}d, returned item \"{1}\" instead of \"{2}\"", i, sc[ind], values[i]); } } } Console.WriteLine("2. add intl strings"); string [] intlValues = new string [values.Length]; for (int i = 0; i < values.Length; i++) { string val = intl.GetString(MAX_LEN, true, true, true); while (Array.IndexOf(intlValues, val) != -1 ) val = intl.GetString(MAX_LEN, true, true, true); intlValues[i] = val; } Console.WriteLine(" initial number of items: " + sc.Count); strLoc = "Loc_002oo"; for (int i = 0; i < intlValues.Length; i++) { iCountTestcases++; cnt = sc.Count; sc.Add(intlValues[i]); if (sc.Count != cnt+1) { iCountErrors++; Console.WriteLine("Err_0002_{0}a, count is {1} instead of {2}", i, sc.Count, cnt+1); } iCountTestcases++; if (!sc.Contains(intlValues[i])) { iCountErrors++; Console.WriteLine("Err_0002_{0}b, collection doesn't contain new item", i); } iCountTestcases++; ind = sc.IndexOf(intlValues[i]); if (ind != sc.Count - 1) { iCountErrors++; Console.WriteLine("Err_0002_{0}c, returned index {1} instead of {2}", i, ind, sc.Count - 1); } if (ind != -1) { iCountTestcases++; if (String.Compare(sc[ind], intlValues[i], false) != 0) { iCountErrors++; Console.WriteLine("Err_0002_{0}d, returned item \"{1}\" instead of \"{2}\"", i, sc[ind], intlValues[i]); } } } Console.WriteLine("3. Add a very long string"); strLoc = "Loc_003oo"; iCountTestcases++; cnt = sc.Count; string intlStr = intlValues[0]; while (intlStr.Length < 10000) intlStr += intlStr; Console.WriteLine(" - add string of Length " + intlStr.Length); sc.Add(intlStr); if (sc.Count != cnt+1) { iCountErrors++; Console.WriteLine("Err_0003a, count is {1} instead of {2}", sc.Count, cnt+1); } iCountTestcases++; if (!sc.Contains(intlStr)) { iCountErrors++; Console.WriteLine("Err_0003b, collection doesn't contain new item"); } iCountTestcases++; ind = sc.IndexOf(intlStr); if (ind != sc.Count - 1) { iCountErrors++; Console.WriteLine("Err_0003c, returned index {1} instead of {2}", ind, sc.Count - 1); } if (ind != -1) { iCountTestcases++; if (String.Compare(sc[ind], intlStr, false) != 0) { iCountErrors++; Console.WriteLine("Err_0003d, returned item \"{1}\" instead of \"{2}\"", sc[ind], intlStr); } } } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_general! strLoc=="+ strLoc +", exc_general==\n"+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "Pass. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.WriteLine("Fail! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }
public virtual bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver: " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; StringCollection sc; try { Console.WriteLine("--- default ctor ---"); strLoc = "Loc_001oo"; iCountTestcases++; sc = new StringCollection(); Console.WriteLine("1. compare to null"); iCountTestcases++; if (sc == null) { iCountErrors++; Console.WriteLine("Err_0001, collection is null after default ctor"); } Console.WriteLine("2. check Count"); iCountTestcases++; if (sc.Count != 0) { iCountErrors++; Console.WriteLine("Err_0002, Count = {0} after default ctor", sc.Count); } Console.WriteLine("3. check Contains()"); iCountTestcases++; if (sc.Contains("string")) { iCountErrors++; Console.WriteLine("Err_0003, Contains() returned true after default ctor"); } Console.WriteLine("4. check ToString()"); iCountTestcases++; string temp = sc.ToString(); Console.WriteLine(" ToString(): " + temp); if (temp.IndexOf("StringCollection") == -1) { iCountErrors++; Console.WriteLine("Err_0004, ToString() doesn't contain \"StringCollection\""); } Console.WriteLine("5. check returned Type"); iCountTestcases++; temp = sc.GetType().ToString().Trim(); Console.WriteLine(" GetType(): " + temp); if (temp.IndexOf("StringCollection") == -1) { iCountErrors++; Console.WriteLine("Err_0005: returned type doesn't contain \"StringCollection\""); } Console.WriteLine("6. compare returned Type of two collection"); iCountTestcases++; string temp1 = (new StringCollection()).GetType().ToString().Trim(); if (String.Compare(temp, temp1) != 0) { iCountErrors++; Console.WriteLine("Err_0006: returned types of two collections differ"); } Console.WriteLine("7. check IsReadOnly"); iCountTestcases++; Console.WriteLine(" IsReadOnly: " + sc.IsReadOnly); if (sc.IsReadOnly) { iCountErrors++; Console.WriteLine("Err_0007: IsReadOnly returned {0}", sc.IsReadOnly); } Console.WriteLine("8. check IsSynchronized"); iCountTestcases++; Console.WriteLine(" IsSynchronized: " + sc.IsSynchronized); if (sc.IsSynchronized) { iCountErrors++; Console.WriteLine("Err_0008: IsSynchronized returned {0}", sc.IsSynchronized); } } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_general! strLoc=="+ strLoc +", exc_general==\n"+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "Pass. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.WriteLine("Fail! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }
public virtual bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver: " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; IntlStrings intl; String strLoc = "Loc_000oo"; StringCollection sc; string [] values = { "", " ", "a", "aa", "text", " spaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; int cnt = 0; try { intl = new IntlStrings(); Console.WriteLine("--- create collection ---"); strLoc = "Loc_001oo"; iCountTestcases++; sc = new StringCollection(); Console.WriteLine("1. Remove() from empty collection"); for (int i = 0; i < values.Length; i++) { iCountTestcases++; sc.Remove(values[i]); if (sc.Count != 0) { iCountErrors++; Console.WriteLine("Err_0001_{0}, Remove changed Count for empty collection", i); } } Console.WriteLine("2. add simple strings and test Remove()"); strLoc = "Loc_002oo"; iCountTestcases++; sc.Clear(); sc.AddRange(values); if (sc.Count != values.Length) { iCountErrors++; Console.WriteLine("Err_0002a, count is {0} instead of {1}", sc.Count, values.Length); } for (int i = 0; i < values.Length; i++) { iCountTestcases++; if (!sc.Contains(values[i])) { iCountErrors++; Console.WriteLine("Err_0002_{0}b, doesn't contain {0} item", i); } cnt = sc.Count; iCountTestcases++; sc.Remove(values[i]); if (sc.Count != cnt - 1) { iCountErrors++; Console.WriteLine("Err_0002_{0}c, didn't remove anything", i); } if (sc.Contains(values[i])) { iCountErrors++; Console.WriteLine("Err_0002_{0}d, removed wrong item", i); } } Console.WriteLine("3. add intl strings and test Remove()"); strLoc = "Loc_003oo"; string [] intlValues = new string [values.Length]; for (int i = 0; i < values.Length; i++) { string val = intl.GetString(MAX_LEN, true, true, true); while (Array.IndexOf(intlValues, val) != -1 ) val = intl.GetString(MAX_LEN, true, true, true); intlValues[i] = val; } int len = values.Length; Boolean caseInsensitive = false; for (int i = 0; i < len; i++) { if(intlValues[i].Length!=0 && intlValues[i].ToLower()==intlValues[i].ToUpper()) caseInsensitive = true; } iCountTestcases++; sc.Clear(); sc.AddRange(intlValues); if ( sc.Count != intlValues.Length ) { iCountErrors++; Console.WriteLine("Err_0003a, count is {0} instead of {1}", sc.Count, intlValues.Length); } for (int i = 0; i < intlValues.Length; i++) { iCountTestcases++; if (!sc.Contains(intlValues[i])) { iCountErrors++; Console.WriteLine("Err_0002_{0}b, doesn't contain {0} item", i); } cnt = sc.Count; iCountTestcases++; sc.Remove(intlValues[i]); if (sc.Count != cnt - 1) { iCountErrors++; Console.WriteLine("Err_0002_{0}c, didn't remove anything", i); } if (sc.Contains(intlValues[i])) { iCountErrors++; Console.WriteLine("Err_0002_{0}d, removed wrong item", i); } } Console.WriteLine("4. duplicate strings "); strLoc = "Loc_004oo"; iCountTestcases++; sc.Clear(); string intlStr = intlValues[0]; sc.Add(intlStr); sc.AddRange(values); sc.AddRange(intlValues); cnt = values.Length + 1 + intlValues.Length; if (sc.Count != cnt) { iCountErrors++; Console.WriteLine("Err_0004a, count is {1} instead of {2}", sc.Count, cnt); } iCountTestcases++; if (sc.IndexOf(intlStr) != 0) { iCountErrors++; Console.WriteLine("Err_0004b, IndexOf returned {0} instead of {1}", sc.IndexOf(intlStr), 0); } iCountTestcases++; sc.Remove(intlStr); if (!sc.Contains(intlStr)) { iCountErrors++; Console.WriteLine("Err_0004c, removed both duplicates"); } if (sc.IndexOf(intlStr) != values.Length) { iCountErrors++; Console.WriteLine("Err_0004d, IndexOf returned {0} instead of {1}", sc.IndexOf(intlStr), values.Length); } for (int i = 0; i < values.Length; i++) { if (sc.IndexOf(values[i]) != i) { iCountErrors++; Console.WriteLine("Err_0004e_{0}, IndexOf {0} item returned {1} ", i, sc.IndexOf(values[i])); } if (sc.IndexOf(intlValues[i]) != i+values.Length) { iCountErrors++; Console.WriteLine("Err_0004f_{0}, IndexOf {1} item returned {2} ", i, i+values.Length, sc.IndexOf(intlValues[i])); } } Console.WriteLine("5. Case sensitivity"); strLoc = "Loc_005oo"; iCountTestcases++; sc.Clear(); sc.Add(intlStr.ToUpper()); sc.AddRange(values); sc.Add(intlStr.ToLower()); cnt = values.Length + 2; if (sc.Count != cnt) { iCountErrors++; Console.WriteLine("Err_0005a, count is {1} instead of {2} ", sc.Count, cnt); } intlStr = intlStr.ToLower(); iCountTestcases++; Console.WriteLine(" - remove lowercase" ); cnt = sc.Count; sc.Remove(intlStr); if (sc.Count != cnt-1) { iCountErrors++; Console.WriteLine("Err_0005b, didn't remove anything"); } if (!caseInsensitive && sc.Contains(intlStr)) { iCountErrors++; Console.WriteLine("Err_0005c, didn't remove lowercase "); } if (!sc.Contains(intlValues[0].ToUpper())) { iCountErrors++; Console.WriteLine("Err_0005d, removed uppercase "); } Console.WriteLine("6. Remove() non-existing item"); strLoc = "Loc_006oo"; iCountTestcases++; sc.Clear(); sc.AddRange(values); cnt = values.Length; if (sc.Count != cnt) { iCountErrors++; Console.WriteLine("Err_0006a, count is {1} instead of {2} ", sc.Count, cnt); } intlStr = "Hello"; iCountTestcases++; cnt = sc.Count; sc.Remove(intlStr); if (sc.Count != cnt) { iCountErrors++; Console.WriteLine("Err_0005b, removed something"); } } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_general! strLoc=="+ strLoc +", exc_general==\n"+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "Pass. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.WriteLine("Fail! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }
private void PrepareIds(out StringCollection targetIds, out StringCollection filteredIds, out StringCollection selectionIds) { targetIds = _appState.TargetIds.Clone(); selectionIds = _appState.SelectionIds.Clone(); // segregate the target IDs that pass through the query from // those that do not if (String.IsNullOrEmpty(_appState.Query)) { filteredIds = new StringCollection(); } else { Configuration config = AppContext.GetConfiguration(); Configuration.QueryRow query = config.Query.FindByQueryID(_appState.Query); using (OleDbCommand command = query.GetDatabaseCommand()) { command.Parameters[0].Value = _appState.TargetIds.Join(","); if (command.Parameters.Count > 1) { command.Parameters[1].Value = AppUser.GetRole(); } using (OleDbDataReader reader = command.ExecuteReader()) { int mapIdColumn = reader.GetOrdinal("MapID"); filteredIds = targetIds; targetIds = new StringCollection(); while (reader.Read()) { if (!reader.IsDBNull(mapIdColumn)) { string mapId = reader.GetValue(mapIdColumn).ToString(); filteredIds.Remove(mapId); if (!targetIds.Contains(mapId)) { targetIds.Add(mapId); } } } } command.Connection.Dispose(); } } if (targetIds.Count > 0) { // remove the active ID from the targets if (_appState.ActiveMapId.Length > 0) { targetIds.Remove(_appState.ActiveMapId); } // remove the selection IDs from the targets if necessary if (_appState.TargetLayer == _appState.SelectionLayer && _appState.SelectionIds.Count > 0) { if (_appState.ActiveMapId.Length > 0) { selectionIds.Remove(_appState.ActiveMapId); } foreach (string selectionId in _appState.SelectionIds) { targetIds.Remove(selectionId); } } } }
/// <summary> /// This helper method can be used to add a time zone ID to the string collection when one is used on the /// passed property. /// </summary> /// <param name="dateProp">The date/time property to check.</param> /// <param name="timeZoneIds">The string collection to which the time zone ID is added if there is one on /// the date/time property and it is not already in the collection.</param> /// <remarks>If the date/time property has no time zone ID or if it is set to <see cref="DateTime.MinValue"/>, /// the collection is not modified.</remarks> protected static void AddTimeZoneIfUsed(BaseDateTimeProperty dateProp, StringCollection timeZoneIds) { if(dateProp != null && dateProp.TimeZoneDateTime != DateTime.MinValue) { string tzId = dateProp.TimeZoneId; if(tzId != null && !timeZoneIds.Contains(tzId)) timeZoneIds.Add(tzId); } }
public static void Constructor_DefaultTest() { StringCollection sc = new StringCollection(); Assert.Equal(0, sc.Count); Assert.False(sc.Contains(null)); Assert.False(sc.Contains("")); }
public static void ContainsTest(StringCollection collection, string[] data) { Assert.All(data, element => Assert.True(collection.Contains(element))); Assert.All(data, element => Assert.True(((IList)collection).Contains(element))); Assert.False(collection.Contains(ElementNotPresent)); Assert.False(((IList)collection).Contains(ElementNotPresent)); }
public virtual bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver: " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; IntlStrings intl; String strLoc = "Loc_000oo"; StringCollection sc; string [] values = { "", " ", "a", "aa", "text", " spaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; int cnt = 0; try { intl = new IntlStrings(); Console.WriteLine("--- create collection ---"); strLoc = "Loc_001oo"; iCountTestcases++; sc = new StringCollection(); Console.WriteLine("1. Check for empty collection"); for (int i = 0; i < values.Length; i++) { iCountTestcases++; if (sc.Contains(values[i])) { iCountErrors++; Console.WriteLine("Err_0001_{0}, returned true for empty collection", i); } } Console.WriteLine("2. add simple strings and verify Contains()"); strLoc = "Loc_002oo"; iCountTestcases++; cnt = sc.Count; sc.AddRange(values); if (sc.Count != values.Length) { iCountErrors++; Console.WriteLine("Err_0002a, count is {0} instead of {1}", sc.Count, values.Length); } for (int i = 0; i < values.Length; i++) { iCountTestcases++; if (!sc.Contains(values[i])) { iCountErrors++; Console.WriteLine("Err_0002_{0}b, collection doesn't contain item \"{1}\"", i, values[i]); } } Console.WriteLine("3. add intl strings and verify Contains()"); strLoc = "Loc_003oo"; string [] intlValues = new string [values.Length]; for (int i = 0; i < values.Length; i++) { string val = intl.GetString(MAX_LEN, true, true, true); while (Array.IndexOf(intlValues, val) != -1 ) val = intl.GetString(MAX_LEN, true, true, true); intlValues[i] = val; } int len = values.Length; Boolean caseInsensitive = false; for (int i = 0; i < len; i++) { if(intlValues[i].Length!=0 && intlValues[i].ToLower()==intlValues[i].ToUpper()) caseInsensitive = true; } iCountTestcases++; cnt = sc.Count; sc.AddRange(intlValues); if ( sc.Count != (cnt + intlValues.Length) ) { iCountErrors++; Console.WriteLine("Err_0003a, count is {0} instead of {1}", sc.Count, cnt + intlValues.Length); } for (int i = 0; i < intlValues.Length; i++) { iCountTestcases++; if (!sc.Contains(intlValues[i])) { iCountErrors++; Console.WriteLine("Err_0003_{0}b, collection doesn't contain item \"{1}\"", i, intlValues[i]); } } Console.WriteLine("4. Add a very long string and verify Contains()"); strLoc = "Loc_004oo"; iCountTestcases++; cnt = sc.Count; string intlStr = intlValues[0]; while (intlStr.Length < 10000) intlStr += intlStr; Console.WriteLine(" - add string of Length " + intlStr.Length); sc.Add(intlStr); if (sc.Count != cnt+1) { iCountErrors++; Console.WriteLine("Err_0004a, count is {1} instead of {2}", sc.Count, cnt+1); } iCountTestcases++; if (!sc.Contains(intlStr)) { iCountErrors++; Console.WriteLine("Err_0004b, collection doesn't contain new item"); } Console.WriteLine("5. Case sensitivity"); strLoc = "Loc_003oo"; iCountTestcases++; sc.Clear(); if (sc.Count != 0) { iCountErrors++; Console.WriteLine("Err_0005, count is {1} instead of {2} after Clear()", sc.Count, 0); } intlStr = intlValues[0].ToUpper(); iCountTestcases++; sc.Add(intlStr); if (sc.Count != 1) { iCountErrors++; Console.WriteLine("Err_0005a, count is {1} instead of {2}", sc.Count, 1); } iCountTestcases++; if (!sc.Contains(intlStr)) { iCountErrors++; Console.WriteLine("Err_0005b, Contains() returned false "); } intlStr = intlValues[0].ToLower(); iCountTestcases++; if (!caseInsensitive && sc.Contains(intlStr)) { iCountErrors++; Console.WriteLine("Err_0005c, Contains() returned true for lowercase version"); } } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_general! strLoc=="+ strLoc +", exc_general==\n"+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "Pass. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.WriteLine("Fail! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }
public static void Remove_Duplicate_IListTest(StringCollection collection, string[] data) { // Only the first element will be removed. string[] first = data.Distinct().ToArray(); Assert.All(first, element => { Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); ((IList)collection).Remove(element); Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); }); Assert.Equal(data.Length - first.Length, collection.Count); for (int i = first.Length; i < data.Length; i++) { string element = data[i]; Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); ((IList)collection).Remove(element); bool stillPresent = i < data.Length - first.Length; Assert.Equal(stillPresent, collection.Contains(element)); Assert.Equal(stillPresent, ((IList)collection).Contains(element)); } Assert.Equal(0, collection.Count); }
public virtual bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver: " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; IntlStrings intl; String strLoc = "Loc_000oo"; StringCollection sc; string [] values = { "", " ", "a", "aa", "text", " spaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; try { intl = new IntlStrings(); Console.WriteLine("--- create collection ---"); strLoc = "Loc_001oo"; iCountTestcases++; sc = new StringCollection(); Console.WriteLine("1. RemoveAt() from empty collection"); iCountTestcases++; if (sc.Count > 0) sc.Clear(); try { sc.RemoveAt(0); iCountErrors++; Console.WriteLine("Err_0001_{0}a, no exception"); } catch (ArgumentOutOfRangeException ex) { Console.WriteLine(" expected exception: " + ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0001_{0}b, unexpected exception: " + e.ToString()); } Console.WriteLine("2. RemoveAt() on filled collection"); strLoc = "Loc_002oo"; Console.WriteLine(" - at the beginning"); iCountTestcases++; sc.Clear(); sc.AddRange(values); if (sc.Count != values.Length) { iCountErrors++; Console.WriteLine("Err_0002a, count is {0} instead of {1}", sc.Count, values.Length); } iCountTestcases++; sc.RemoveAt(0); if (sc.Count != values.Length - 1) { iCountErrors++; Console.WriteLine("Err_0002b, Count returned {0} instead of {1}", sc.Count, values.Length - 1); } iCountTestcases++; if (sc.Contains(values[0])) { iCountErrors++; Console.WriteLine("Err_0002c, removed wrong item"); } for (int i = 0; i < values.Length; i++) { iCountTestcases++; if (sc.IndexOf(values[i]) != i-1) { iCountErrors++; Console.WriteLine("Err_0002_{0}d, IndexOf returned {1} instead of {2}", i, sc.IndexOf(values[i]), i-1); } } Console.WriteLine(" - at the end"); iCountTestcases++; sc.Clear(); sc.AddRange(values); if (sc.Count != values.Length) { iCountErrors++; Console.WriteLine("Err_0002e, count is {0} instead of {1}", sc.Count, values.Length); } iCountTestcases++; sc.RemoveAt(values.Length-1); if (sc.Count != values.Length - 1) { iCountErrors++; Console.WriteLine("Err_0002f, Count returned {0} instead of {1}", sc.Count, values.Length - 1); } iCountTestcases++; if (sc.Contains(values[values.Length - 1])) { iCountErrors++; Console.WriteLine("Err_0002g, removed wrong item"); } for (int i = 0; i < values.Length-1; i++) { iCountTestcases++; if (sc.IndexOf(values[i]) != i) { iCountErrors++; Console.WriteLine("Err_0002_{0}h, IndexOf returned {1} instead of {2}", i, sc.IndexOf(values[i]), i); } } Console.WriteLine(" - at the middle"); iCountTestcases++; sc.Clear(); sc.AddRange(values); if (sc.Count != values.Length) { iCountErrors++; Console.WriteLine("Err_0002i, count is {0} instead of {1}", sc.Count, values.Length); } iCountTestcases++; sc.RemoveAt(values.Length/2); if (sc.Count != values.Length - 1) { iCountErrors++; Console.WriteLine("Err_0002j, Count returned {0} instead of {1}", sc.Count, values.Length - 1); } iCountTestcases++; if (sc.Contains(values[values.Length/2])) { iCountErrors++; Console.WriteLine("Err_0002g, removed wrong item"); } for (int i = 0; i < values.Length; i++) { iCountTestcases++; 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) { iCountErrors++; Console.WriteLine("Err_0002_{0}k, IndexOf returned {1} instead of {2}", i, sc.IndexOf(values[i]), expected); } } Console.WriteLine("3. RemoveAt() on collection with duplicate strings "); strLoc = "Loc_003oo"; iCountTestcases++; sc.Clear(); string intlStr = intl.GetString(MAX_LEN, true, true, true); sc.Add(intlStr); sc.AddRange(values); sc.Add(intlStr); if (sc.Count != values.Length + 2) { iCountErrors++; Console.WriteLine("Err_0003a, count is {1} instead of {2}", sc.Count, values.Length + 2); } iCountTestcases++; sc.RemoveAt(values.Length + 1); if (!sc.Contains(intlStr)) { iCountErrors++; Console.WriteLine("Err_0003b, removed both duplicates"); } if (sc.IndexOf(intlStr) != 0) { iCountErrors++; Console.WriteLine("Err_0003c, removed 1st instance"); } Console.WriteLine("4. RemoveAt(-1)"); strLoc = "Loc_004oo"; iCountTestcases++; sc.Clear(); sc.AddRange(values); try { sc.RemoveAt(-1); iCountErrors++; Console.WriteLine("Err_0004a, no exception"); } catch (ArgumentOutOfRangeException ex) { Console.WriteLine(" expected exception: " + ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0004b, unexpected exception: {0}", e.ToString()); } Console.WriteLine("5. RemoveAt(Count)"); strLoc = "Loc_005oo"; iCountTestcases++; sc.Clear(); sc.AddRange(values); try { sc.RemoveAt(sc.Count); iCountErrors++; Console.WriteLine("Err_0005a, no exception"); } catch (ArgumentOutOfRangeException ex) { Console.WriteLine(" expected exception: " + ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0005b, unexpected exception: {0}", e.ToString()); } Console.WriteLine("6. RemoveAt(Count+1)"); strLoc = "Loc_006oo"; iCountTestcases++; sc.Clear(); sc.AddRange(values); try { sc.RemoveAt(sc.Count+1); iCountErrors++; Console.WriteLine("Err_0006a, no exception"); } catch (ArgumentOutOfRangeException ex) { Console.WriteLine(" expected exception: " + ex.Message); } catch (Exception e) { iCountErrors++; Console.WriteLine("Err_0006b, unexpected exception: {0}", e.ToString()); } } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_general! strLoc=="+ strLoc +", exc_general==\n"+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "Pass. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.WriteLine("Fail! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }
/// <summary> /// Delete a time zone component /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void btnDelete_Click(object sender, EventArgs e) { if(dgvCalendar.CurrentCellAddress.Y == -1) { MessageBox.Show("Please select an item to delete", "No Item", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } StringCollection timeZonesUsed = new StringCollection(); string timeZoneId = (string)dgvCalendar[0, dgvCalendar.CurrentCellAddress.Y].Value; if(vCal != null) vCal.TimeZonesUsed(timeZonesUsed); if(timeZonesUsed.Contains(timeZoneId)) { MessageBox.Show("The time zone is in use and cannot be deleted", "Time Zone In Use", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } if(MessageBox.Show("Are you sure you want to delete the selected item?", "Delete Item", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes) { VCalendar.TimeZones.Remove(VCalendar.TimeZones[timeZoneId]); wasModified = true; LoadGridWithItems(); } }
/// <summary> /// Converts the specified web color (named or hex value) into a <see cref="System.Drawing.Color"/> value. /// </summary> /// <param name="webColorString"></param> /// <returns>A value of type <see cref="T:System.Drawing.Color"/> matching the provided web color.</returns> public static System.Drawing.Color GetSystemColor(string webColorString) { // First, try and determine if the user passed the name of a known color. StringCollection strCol = new StringCollection(Enum.GetNames(typeof(System.Drawing.KnownColor))); // If so, create a new Color object using the known color name. if (strCol.Contains(webColorString)) return System.Drawing.Color.FromKnownColor((System.Drawing.KnownColor)Enum.Parse(typeof(System.Drawing.KnownColor), webColorString)); // If that failed, assume it's a RGB hex value. First we have to make sure it's 6 digits long. string parseClr = webColorString.ToLower().TrimStart('#'); if (parseClr.Length != 6) throw new ArgumentException("Value must be a known color name or a valid hexadecimal RGB web color value.", "webColorString"); // Break the string value up and pass it to the Hex.GetSystemColor(string, string, string) method. return Hex.GetSystemColor(parseClr.Substring(0, 2), parseClr.Substring(2, 2), parseClr.Substring(4, 2)); }
/// /// Removes stop words from the text. /// public static string RemoveStopWords(string inputText) { inputText = inputText .Replace("\\", string.Empty) .Replace("|", string.Empty) .Replace("(", string.Empty) .Replace(")", string.Empty) .Replace("[", string.Empty) .Replace("]", string.Empty) .Replace("*", string.Empty) .Replace("?", string.Empty) .Replace("}", string.Empty) .Replace("{", string.Empty) .Replace("^", string.Empty) .Replace("+", string.Empty); // transform given text into array of words char[] wordSeparators = new char[] { ' ', '\n', '\r', ',', ';', '.', '!', '?', '-', ' ', '"', '\'' }; string[] words = inputText.Split(wordSeparators, StringSplitOptions.RemoveEmptyEntries); // Create and initializes a new StringCollection. StringCollection myStopWordsCol = new StringCollection(); // Add a range of elements from an array to the end of the StringCollection. myStopWordsCol.AddRange(stopWordsArrary); StringBuilder sb = new StringBuilder(); for (int i = 0; i < words.Length; i++) { string word = words[i].ToLowerInvariant().Trim(); if (word.Length > 1 && !myStopWordsCol.Contains(word)) sb.Append(word + " "); } return sb.ToString(); }
/// <summary> /// This is used to get a list of time zones used by all owned objects /// </summary> /// <param name="timeZoneIds">A <see cref="StringCollection"/> that will be used to store the list of /// unique time zone IDs used by the calendar objects.</param> public override void TimeZonesUsed(StringCollection timeZoneIds) { string timeZoneId; if(rDates != null) foreach(RDateProperty rdt in rDates) if(rdt.ValueLocation == ValLocValue.DateTime && rdt.TimeZoneDateTime != DateTime.MinValue) { timeZoneId = rdt.TimeZoneId; if(timeZoneId != null && !timeZoneIds.Contains(timeZoneId)) timeZoneIds.Add(timeZoneId); } if(exDates != null) foreach(ExDateProperty edt in exDates) CalendarObject.AddTimeZoneIfUsed(edt, timeZoneIds); }