public Listener( int port ) { m_ThisPort = port; m_Disposed = false; m_Accepted = new Queue(); m_OnAccept = new AsyncCallback( OnAccept ); m_Listener = Bind( IPAddress.Any, port ); try { IPHostEntry iphe = Dns.Resolve( Dns.GetHostName() ); ArrayList list = new ArrayList(); list.Add( IPAddress.Loopback ); Console.WriteLine( "Address: {0}:{1}", IPAddress.Loopback, port ); IPAddress[] ips = iphe.AddressList; for ( int i = 0; i < ips.Length; ++i ) { if ( !list.Contains( ips[i] ) ) { list.Add( ips[i] ); Console.WriteLine( "Address: {0}:{1}", ips[i], port ); } } } catch { } }
/// <summary> /// Gets the array of SQL servers that are available on the LAN. /// </summary> /// <returns>string[] of SQL server names</returns> public static string[] GetSQLServers() { string[] retval = null; DataTable dt = null; System.Data.Sql.SqlDataSourceEnumerator sds = System.Data.Sql.SqlDataSourceEnumerator.Instance; dt = sds.GetDataSources(); ArrayList al = new ArrayList(); if (retval != null) { for (int zz = 0; zz < retval.Length; zz++) { if (!al.Contains(retval[zz])) { al.Add(retval[zz]); } } } if (dt != null) { foreach (DataRow row in dt.Rows) { string name = row["ServerName"].ToString() + (row["InstanceName"].ToString().Trim().Length != 0 ? "\\" + row["InstanceName"].ToString() : ""); if (!al.Contains(name)) { al.Add(name); } } dt.Dispose(); } al.Sort(); return (string[])al.ToArray(typeof(string)); }
public void ExecuteAssemblies( [UsingFactories("AssemblyNames")] string name, [UsingFactories("AssemblyNames")] string secondName, [UsingFactories("AssemblyNames")] string thirdName ) { int successCount = 0; ArrayList names = new ArrayList(); names.Add(name); names.Add(secondName); names.Add(thirdName); if (names.Contains("ChildAssembly")) { if (!names.Contains("SickParentAssembly")) successCount++; } if (names.Contains("ParentAssembly")) successCount++; string[] files = new string[] { name + ".dll", secondName + ".dll", thirdName + ".dll" }; using (TestDomainDependencyGraph graph = TestDomainDependencyGraph.BuildGraph(files,null, MbUnit.Core.Filters.FixtureFilters.Any, false)) { ReportResult result = graph.RunTests(); Assert.AreEqual(successCount, result.Counter.SuccessCount); } }
public ArrayList ProduceAddEx(int volume, int maxFactor, double fillInBlankPercentage) { string operation = "+"; if (fillInBlankPercentage > 1) fillInBlankPercentage = 1; else if (fillInBlankPercentage < 0) fillInBlankPercentage = 0; int blankVolume = (int)(volume * fillInBlankPercentage); int nonBlankVolume = volume - blankVolume; ArrayList exList = new ArrayList(); if (maxFactor < 1) { return exList; } // 如果难度超过20就不出现因子0、1这种简单题目了 int minFactor = (maxFactor > 20 ? 2 : 0); // 减少重复题目,如果发现重复则再试一次 // 另外如果难度太低可能会导致无法保证不重复的情况下出够题目同时也考虑效率问题,只重试10次 int repeatedTimes = 0; Random random = new Random(); for (int i = 0; i < nonBlankVolume; ) { int factor1 = random.Next(minFactor, maxFactor - minFactor); int factor2 = random.Next(minFactor, Math.Max(minFactor + 1, maxFactor - factor1)); string equation = factor1 + operation + factor2 + "="; if (repeatedTimes > 10 || !exList.Contains(equation)) { exList.Add(equation); repeatedTimes = 0; i++; } else { repeatedTimes++; } } for (int i = 0; i < blankVolume; ) { int factor1 = random.Next(minFactor, maxFactor - minFactor); int factor2 = random.Next(minFactor, Math.Max(minFactor + 1, maxFactor - factor1)); string equation; if (random.Next() % 2 == 0) equation = factor1 + operation + "( )" + "=" + (factor1 + factor2); else equation = "( )" + operation + factor2 + "=" + (factor1 + factor2); if (repeatedTimes > 10 || !exList.Contains(equation)) { exList.Add(equation); repeatedTimes = 0; i++; } else { repeatedTimes++; } } return exList; }
public void ExecuteAssemblies( [UsingFactories("AssemblyNames")] string name, [UsingFactories("AssemblyNames")] string secondName ) { int successCount = 0; ArrayList names = new ArrayList(); names.Add(Path.GetFileNameWithoutExtension(name)); names.Add(Path.GetFileNameWithoutExtension(secondName)); if (names.Contains("SickParentAssembly")) { if (names.Contains("ParentAssembly")) successCount++; } else { if (names.Contains("ChildAssembly")) successCount++; if (names.Contains("ParentAssembly")) successCount++; } string[] files = new string[] { name, secondName }; using (TestDomainDependencyGraph graph = TestDomainDependencyGraph.BuildGraph(files,null, MbUnit.Core.Filters.FixtureFilters.Any, true)) { ReportResult result = graph.RunTests(); Assert.AreEqual(successCount, result.Counter.SuccessCount); } }
public static string[] GetWhisperKeywords() { ArrayList keywords = new ArrayList(); String whisperKeyword = null; foreach (DataRow row in DB.ActionTable.Rows) { if (row[DB.COL_QUESTPARTACTION_P] is string && ((string)row[DB.COL_QUESTPARTACTION_P]).Contains("[")) { MatchCollection matches = Regex.Matches((string)row[DB.COL_QUESTPARTACTION_P], "\\[([^\\]])*\\]", RegexOptions.Compiled); foreach (Match match in matches) { whisperKeyword = match.Value.Trim(WHISPER_TRIMS); if (!keywords.Contains(whisperKeyword)) keywords.Add(whisperKeyword); } } if (row[DB.COL_QUESTPARTACTION_Q] is string && ((string)row[DB.COL_QUESTPARTACTION_Q]).Contains("[")) { MatchCollection matches = Regex.Matches((string)row[DB.COL_QUESTPARTACTION_Q], "\\[([^\\]])*\\]", RegexOptions.Compiled); foreach (Match match in matches) { whisperKeyword = match.Value.Trim(WHISPER_TRIMS); if (!keywords.Contains(whisperKeyword)) keywords.Add(whisperKeyword); } } } return (string[])keywords.ToArray(typeof(string)); }
public void MaxSize() { IKernel kernel = new DefaultKernel(); kernel.AddComponent("a", typeof(PoolableComponent1)); ArrayList instances = new ArrayList(); instances.Add(kernel["a"] as PoolableComponent1); instances.Add(kernel["a"] as PoolableComponent1); instances.Add(kernel["a"] as PoolableComponent1); instances.Add(kernel["a"] as PoolableComponent1); instances.Add(kernel["a"] as PoolableComponent1); PoolableComponent1 other1 = kernel["a"] as PoolableComponent1; Assert.IsNotNull(other1); Assert.IsTrue(!instances.Contains(other1)); foreach(object inst in instances) { kernel.ReleaseComponent(inst); } kernel.ReleaseComponent(other1); PoolableComponent1 other2 = kernel["a"] as PoolableComponent1; Assert.IsNotNull(other2); Assert.IsTrue(other1 != other2); Assert.IsTrue(instances.Contains(other2)); kernel.ReleaseComponent(other2); }
internal System.String SelectNegotiatedComponent(System.String locallist, System.String remotelist) { System.Collections.ArrayList r = new System.Collections.ArrayList(); int idx; System.String name; while ((idx = remotelist.IndexOf(",")) > -1) { r.Add(remotelist.Substring(0, (idx) - (0))); remotelist = remotelist.Substring(idx + 1); } r.Add(remotelist); while ((idx = locallist.IndexOf(",")) > -1) { name = locallist.Substring(0, (idx) - (0)); if (r.Contains(name)) { return(name); } locallist = locallist.Substring(idx + 1); } if (r.Contains(locallist)) { return(locallist); } throw new SSHException("Failed to negotiate a transport component [" + locallist + "] [" + remotelist + "]", SSHException.KEY_EXCHANGE_FAILED); }
public MultiFormatOneDReader(System.Collections.Hashtable hints) { System.Collections.ArrayList possibleFormats = hints == null ? null : (System.Collections.ArrayList)hints[DecodeHintType.POSSIBLE_FORMATS]; bool useCode39CheckDigit = hints != null && hints[DecodeHintType.ASSUME_CODE_39_CHECK_DIGIT] != null; readers = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); if (possibleFormats != null) { if (possibleFormats.Contains(BarcodeFormat.EAN_13) || possibleFormats.Contains(BarcodeFormat.UPC_A) || possibleFormats.Contains(BarcodeFormat.EAN_8) || possibleFormats.Contains(BarcodeFormat.UPC_E)) { readers.Add(new MultiFormatUPCEANReader(hints)); } if (possibleFormats.Contains(BarcodeFormat.CODE_39)) { readers.Add(new Code39Reader(useCode39CheckDigit)); } if (possibleFormats.Contains(BarcodeFormat.CODE_128)) { readers.Add(new Code128Reader()); } if (possibleFormats.Contains(BarcodeFormat.ITF)) { readers.Add(new ITFReader()); } } if ((readers.Count == 0)) { readers.Add(new MultiFormatUPCEANReader(hints)); readers.Add(new Code39Reader()); readers.Add(new Code128Reader()); readers.Add(new ITFReader()); } }
public MultiFormatUPCEANReader(System.Collections.Hashtable hints) { System.Collections.ArrayList possibleFormats = hints == null?null:(System.Collections.ArrayList)hints[DecodeHintType.POSSIBLE_FORMATS]; readers = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); if (possibleFormats != null) { if (possibleFormats.Contains(BarcodeFormat.EAN_13)) { readers.Add(new EAN13Reader()); } else if (possibleFormats.Contains(BarcodeFormat.UPC_A)) { readers.Add(new UPCAReader()); } if (possibleFormats.Contains(BarcodeFormat.EAN_8)) { readers.Add(new EAN8Reader()); } if (possibleFormats.Contains(BarcodeFormat.UPC_E)) { readers.Add(new UPCEReader()); } } if ((readers.Count == 0)) { readers.Add(new EAN13Reader()); // UPC-A is covered by EAN-13 readers.Add(new EAN8Reader()); readers.Add(new UPCEReader()); } }
protected override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); var todoBD = db.TODOes.ToList().Where(m=>m.done_date == null).OrderBy(m=> m.project_name).OrderBy(m=> m.add_date); ArrayList lista_projektow = new ArrayList(); Hashtable lista_todo_do_zrobienia = new Hashtable(); if (todoBD != null) { foreach (TODO todo in todoBD) { if (!lista_projektow.Contains(todo.project_name)) lista_projektow.Add(todo.project_name); } foreach (string nazwa_projektu in lista_projektow) { ArrayList lista_zadan_do_wykonania = new ArrayList(); foreach (TODO todo in todoBD) { if (todo.project_name == nazwa_projektu) lista_zadan_do_wykonania.Add(todo); } lista_todo_do_zrobienia.Add(nazwa_projektu, lista_zadan_do_wykonania); } } todoBD = db.TODOes.ToList().Where(m => m.done_date != null).OrderBy(m => m.project_name).OrderByDescending(m => m.done_date); Hashtable lista_todo_zrobione = new Hashtable(); if (todoBD != null) { lista_projektow.Clear(); foreach (TODO todo in todoBD) { if (!lista_projektow.Contains(todo.project_name)) lista_projektow.Add(todo.project_name); } foreach (string nazwa_projektu in lista_projektow) { ArrayList lista_zadan_wykonanych = new ArrayList(); foreach (TODO todo in todoBD) { if (todo.project_name == nazwa_projektu) lista_zadan_wykonanych.Add(todo); } lista_todo_zrobione.Add(nazwa_projektu, lista_zadan_wykonanych); } } ViewData.Add("lista_todo_do_zrobienia", lista_todo_do_zrobienia); ViewData.Add("lista_todo_zrobione", lista_todo_zrobione); }
public void HasMultipleCategories() { XmlNodeList categories = resultDoc.SelectNodes("//test-case[@name=\"NUnit.Tests.Assemblies.MockTestFixture.MockTest3\"]/categories/category"); Assert.IsNotNull(categories); Assert.AreEqual(2, categories.Count); ArrayList names = new ArrayList(); names.Add( categories[0].Attributes["name"].Value ); names.Add( categories [1].Attributes["name"].Value); Assert.IsTrue( names.Contains( "AnotherCategory" ), "AnotherCategory" ); Assert.IsTrue( names.Contains( "MockCategory" ), "MockCategory" ); }
public static void EventSink_PlayerDeath( PlayerDeathEventArgs e ) { Mobile m = e.Mobile; ArrayList killers = new ArrayList(); ArrayList toGive = new ArrayList(); foreach ( AggressorInfo ai in m.Aggressors ) { //bounty system edit // orig if ( ai.Attacker.Player && ai.CanReportMurder && !ai.Reported ) if ( ai.Attacker.Player && ai.CanReportMurder && !ai.Reported && !BountyBoard.Attackable( ai.Attacker, e.Mobile ) ) // end bounty system edit { killers.Add( ai.Attacker ); ai.Reported = true; } if ( ai.Attacker.Player && (DateTime.Now - ai.LastCombatTime) < TimeSpan.FromSeconds( 30.0 ) && !toGive.Contains( ai.Attacker ) ) toGive.Add( ai.Attacker ); } foreach ( AggressorInfo ai in m.Aggressed ) { if ( ai.Defender.Player && (DateTime.Now - ai.LastCombatTime) < TimeSpan.FromSeconds( 30.0 ) && !toGive.Contains( ai.Defender ) ) toGive.Add( ai.Defender ); } foreach ( Mobile g in toGive ) { int n = Notoriety.Compute( g, m ); int theirKarma = m.Karma, ourKarma = g.Karma; bool innocent = ( n == Notoriety.Innocent ); bool criminal = ( n == Notoriety.Criminal || n == Notoriety.Murderer ); int fameAward = m.Fame / 200; int karmaAward = 0; if ( innocent ) karmaAward = ( ourKarma > -2500 ? -850 : -110 - (m.Karma / 100) ); else if ( criminal ) karmaAward = 50; Titles.AwardFame( g, fameAward, false ); Titles.AwardKarma( g, karmaAward, true ); } if ( m is PlayerMobile && ((PlayerMobile)m).NpcGuild == NpcGuild.ThievesGuild ) return; if ( killers.Count > 0 ) new GumpTimer( m, killers ).Start(); }
/// <summary> /// Writes the log. /// </summary> /// <param name="context">The context.</param> /// <param name="stream">The stream.</param> /// <param name="callback">The callback for UI updates.</param> public void WriteLog(IExecutionContext context, Stream stream, ProgressCallback callback) { TimeSpan baseTime = new TimeSpan(0); ArrayList oids = new ArrayList(); Hashtable bitsByOid = new Hashtable(); using (StreamWriter s = new StreamWriter(stream)) { foreach (PacketLog log in context.LogManager.Logs) { for (int i = 0; i < log.Count; i++) { if (callback != null && (i & 0xFFF) == 0) // update progress every 4096th packet callback(i, log.Count - 1); StoC_0xA1_NpcUpdate npcUpdate = log[i] as StoC_0xA1_NpcUpdate; if (npcUpdate == null) continue; if ((npcUpdate.Temp & 0xF000) == 0) continue; if ((npcUpdate.Temp & 0x0FFF) != 0) continue; s.WriteLine(npcUpdate.ToHumanReadableString(baseTime, true)); if (!oids.Contains(npcUpdate.NpcOid)) oids.Add(npcUpdate.NpcOid); ArrayList bitsList = (ArrayList) bitsByOid[npcUpdate.NpcOid]; if (bitsList == null) { bitsList = new ArrayList(); bitsByOid[npcUpdate.NpcOid] = bitsList; } int bits = npcUpdate.Temp >> 12; if (!bitsList.Contains(bits)) bitsList.Add(bits); } int regionId; int zoneId; SortedList oidInfo = ShowKnownOidAction.MakeOidList(log.Count - 1, log, out regionId, out zoneId); s.WriteLine("\n\noids for region {0}, zone {1}\n", regionId, zoneId); foreach (DictionaryEntry entry in oidInfo) { ushort oid = (ushort) entry.Key; if (!oids.Contains(oid)) continue; ShowKnownOidAction.ObjectInfo objectInfo = (ShowKnownOidAction.ObjectInfo) entry.Value; s.Write("0x{0:X4}: ", oid); s.Write(objectInfo.ToString()); foreach (int bits in (ArrayList) bitsByOid[oid]) { s.Write("\t0b{0}", Convert.ToString(bits, 2)); } s.WriteLine(); } } } }
public void GetPropertiesTest() { Collection<PropertyInfo> properties = _objectUtility.GetProperties(typeof(DummyObject)); ArrayList propertyNames = new ArrayList(); foreach (PropertyInfo property in properties) propertyNames.Add(property.Name); Assert.That(propertyNames.Contains("StringProperty")); Assert.That(propertyNames.Contains("IntProperty")); Assert.That(propertyNames.Contains("DecimalProperty")); Assert.That(propertyNames.Contains("ObjectProperty")); }
public override void OnResponse(NetState sender, RelayInfo info) { Mobile from = sender.Mobile; this.caller = sender.Mobile; switch (info.ButtonID) { case 1: { TextRelay entrySphereAcc = info.GetTextEntry(10); this.textSphereAcc = (entrySphereAcc == null ? "" : entrySphereAcc.Text.Trim()); TextRelay entrySphereChar = info.GetTextEntry(11); this.textSphereChar = (entrySphereChar == null ? "" : entrySphereChar.Text.Trim()); TextRelay entryRunUOAcc = info.GetTextEntry(12); this.textRunUOAcc = (entryRunUOAcc == null ? "" : entryRunUOAcc.Text.Trim()); TextRelay entryRunUOChar = info.GetTextEntry(13); this.textRunUOChar = (entryRunUOChar == null ? "" : entryRunUOChar.Text.Trim()); ArrayList Selections = new ArrayList(info.Switches); if (Selections.Contains(20)) this.importSkills = true; else this.importSkills = false; if (Selections.Contains(21)) this.importItensToPlayer = true; else this.importItensToPlayer = false; if (Selections.Contains(22)) this.importItensToStaff = true; else this.importItensToStaff = false; StartImport(); break; } case 0: default: caller.SendMessage("Importacao CANCELADA."); break; } }
public void GetSubstitutionsImplicitly() { XmlNode node = _document.DocumentElement.FirstChild; var templater = new XmlTemplater(node); string[] substitutions = templater.Substitutions; Assert.AreEqual(4, substitutions.Length); var list = new ArrayList(substitutions); Assert.IsTrue(list.Contains("color")); Assert.IsTrue(list.Contains("name")); Assert.IsTrue(list.Contains("state")); Assert.IsTrue(list.Contains("direction")); }
public void GetSubstititionsExplicitly() { XmlNode node = _document.DocumentElement.FirstChild; var element = (XmlElement) node; element.SetAttribute(InstanceMemento.SUBSTITUTIONS_ATTRIBUTE, "direction,color"); var templater = new XmlTemplater(node); string[] substitutions = templater.Substitutions; Assert.AreEqual(2, substitutions.Length); var list = new ArrayList(substitutions); Assert.IsTrue(list.Contains("color")); Assert.IsTrue(list.Contains("direction")); }
/// <summary> /// Does the passed data object have this format? /// </summary> /// <param name="dataObject">data object</param> /// <returns>true if the data object has the format, otherwise false</returns> public bool CanCreateFrom(IDataObject dataObject) { // GetDataPresent is not always a reliable indicator of what data is // actually available. For Outlook Express, if you call GetDataPresent on // FileGroupDescriptor it returns false however if you actually call GetData // you will get the FileGroupDescriptor! Therefore, we are going to // enumerate the available formats and check that list rather than // checking GetDataPresent ArrayList formats = new ArrayList(dataObject.GetFormats()); // check for FileContents return (formats.Contains(DataFormatsEx.FileGroupDescriptorFormat) || formats.Contains(DataFormatsEx.FileGroupDescriptorWFormat)) && formats.Contains(DataFormatsEx.FileContentsFormat); }
public static string GetStringAsSetUsingDelimiter(string key, char separator, string defaultValue) { string list = EncryptedPlayerPrefs.GetString(key, ""); if (list.Equals("")) { return(defaultValue); } string[] entries = list.Split(separator); System.Collections.ArrayList newList = new System.Collections.ArrayList(); foreach (string str in entries) { if (!newList.Contains(str)) { newList.Add(str); } } string result = ""; foreach (string entry in newList) { result = result + entry + separator; } result.TrimEnd(separator); return(result); }
public static string[] Split( string src, char delimiter, params char[] quotedelims ) { ArrayList strings = new ArrayList(); StringBuilder sb = new StringBuilder(); ArrayList ar = new ArrayList(quotedelims); char quote_open = Char.MinValue; foreach (char c in src) { if (c == delimiter && quote_open == Char.MinValue) { strings.Add( sb.ToString() ); sb.Remove( 0, sb.Length ); } else if (ar.Contains(c)) { if (quote_open == Char.MinValue) quote_open = c; else if (quote_open == c) quote_open = Char.MinValue; sb.Append(c); } else sb.Append( c ); } if (sb.Length > 0) strings.Add( sb.ToString()); return (string[])strings.ToArray(typeof(string)); }
/* === MANAGING OBSERVERS === */ public void registerStateObserver(FormElementStateListener qsl) { if (!observers.Contains(qsl)) { observers.Add(qsl); } }
/// <summary> /// 调用LottoNumbers方法,来随机选择数字 /// </summary> /// <returns>6 random numbers </returns> private static string LottoNumbers() //static静态方法,方便调用,但效率不高 { ArrayList list = new ArrayList(); //要添加using System.Collections命名空间 Random r = new Random(); for (int i = 0; i < 6; i++) { int lottoInt = r.Next(1, 41); if (list.Contains(lottoInt)) //Contains()方法:判断ArrayList数组中是否存在某个元素 { i--; //若数组中存在该元素,则i自动减1,本次循环不算 } else //数组中不存在该随机数 { list.Add(lottoInt); //把该随机数添加到数组中 } } //把该数组从小到大排列 list.Sort(); //依次把数组中元素赋值给一个变量,并在每个数字用-连接 string lottoNumbers = ""; for (int i = 0; i < list.Count; i++) { lottoNumbers = lottoNumbers + list[i].ToString() + "-"; } return lottoNumbers.Substring(0, lottoNumbers.Length - 1); }
private Boolean is_anagram(string word1, string word2) { int i; ArrayList array_word1 = new ArrayList(Convert.ToInt32(word1.Length)); ArrayList array_word2 = new ArrayList(Convert.ToInt32(word2.Length)); word1 = word1.ToLower(); word2 = word2.ToLower(); if (word1.Length != word2.Length) return false; for (i = 0; i < word1.Length; i++) array_word1.Add(word1[i].ToString()); for (i = 0; i < word2.Length; i++) array_word2.Add(word2[i].ToString()); foreach (string val in array_word1) { if (array_word2.Contains(val)) array_word2.Remove(val); } if (array_word2.Count == 0) return true; else return false; }
static void Main(string[] args) { IList list1 = new ArrayList(); list1.Add("Hello, "); list1.Add("my "); list1.Add("dear "); list1.Add("old "); list1.Add("friend! "); IList list2 = new ArrayList(); list2.Add("my "); list2.Add("dear "); list2.Add("old "); foreach (var value in list2) { while (list1.Contains(value)) { list1.Remove(value); } } foreach (var v in list1) { Console.Write(v); } }
/// <summary> /// Retains the elements in the target collection that are contained in the specified collection /// </summary> /// <param name="target">Collection where the elements will be removed.</param> /// <param name="c">Elements to be retained in the target collection.</param> /// <returns>true</returns> public static bool RetainAll(System.Collections.ICollection target, System.Collections.ICollection c) { System.Collections.IEnumerator e = new System.Collections.ArrayList(target).GetEnumerator(); System.Collections.ArrayList al = new System.Collections.ArrayList(c); //Reflection. Invoke "RetainAll" method for proprietary classes or "Remove" for each element in the collection System.Reflection.MethodInfo method; try { method = c.GetType().GetMethod("RetainAll"); if (method != null) { method.Invoke(target, new System.Object[] { c }); } else { method = c.GetType().GetMethod("Remove"); while (e.MoveNext() == true) { if (al.Contains(e.Current) == false) { method.Invoke(target, new System.Object[] { e.Current }); } } } } catch (System.Exception ex) { throw ex; } return(true); }
private void FillContract() { const string METHOD_NAME = "FillContract"; try { ArrayList listIDs = new System.Collections.ArrayList(_contractList.Split(new char[] { ',' })); ListBox lst = lstFaContract; lst.Items.Clear(); List<ListBeetContractIDItem> stateList = WSCReportsExec.ContractListByStations(_stationList); foreach (ListBeetContractIDItem state in stateList) { ListItem item = new ListItem(state.ContractNumber, state.ContractID); lst.Items.Add(item); if (listIDs.Contains(item.Value)) { lst.Items[lst.Items.Count - 1].Selected = true; } } } catch (Exception ex) { Common.CException wex = new Common.CException(MOD_NAME + METHOD_NAME, ex); throw (wex); } }
//合并 public void combine(PropertyTypesManager srcPropertyTypesManager, ArrayList ids) { for (int i = 0; i < srcPropertyTypesManager.getElementCount(); i++) { if (ids == null || !ids.Contains(i)) { continue; } PropertyTypeElement srcPropertyTypeElement = (PropertyTypeElement)srcPropertyTypesManager.getElement(i); //寻找相同的属性类型单元 PropertyTypeElement localPropertyTypeElement = null; for (int j = 0; j < getElementCount(); j++) { PropertyTypeElement tempPropertyTypeElement = (PropertyTypeElement)getElement(j); if (tempPropertyTypeElement.name.Equals(srcPropertyTypeElement.name)) { localPropertyTypeElement = tempPropertyTypeElement; break; } } //找到相同名称的本地单元 if (localPropertyTypeElement != null) { localPropertyTypeElement.combine(srcPropertyTypeElement); } else//并入本容器 { srcPropertyTypeElement.combineTo(this); } } }
private static void IndexOneClassifier(Classifier aCls, string aPrefix) { if ((aCls != null) && !aCls.IsShortcut()) { ArrayList list = new ArrayList(); string code = aCls.Code; Classifier item = aCls; while (true) { if (list.Contains(item)) { break; } list.Add(item); PdOOM.BaseObject containerClassifier = item.ContainerClassifier; if (containerClassifier == null) { break; } item = (Classifier) containerClassifier; code = item.Code + "+" + code; } if (aPrefix != "") { code = aPrefix + "." + code; } TypeMapping.DefineExtraType(code, aCls); } }
private void FillContract() { const string METHOD_NAME = "FillContract"; try { string cropYear = ((MasterReportTemplate)Master).CropYear; ArrayList listIDs = new System.Collections.ArrayList(_contractList.Split(new char[] { ',' })); ListBox lst = lstTxContract; lst.Items.Clear(); List <ListBeetContractIDItem> stateList = WSCReportsExec.ContractsByContractStationNo(Convert.ToInt32(cropYear), _stationList); foreach (ListBeetContractIDItem state in stateList) { ListItem item = new ListItem(state.ContractNumber, state.ContractNumber); lst.Items.Add(item); if (listIDs.Contains(item.Value)) { lst.Items[lst.Items.Count - 1].Selected = true; } } } catch (Exception ex) { Common.CException wex = new Common.CException(MOD_NAME + METHOD_NAME, ex); throw (wex); } }
/// <summary> /// 得到一个数据库中的所有表名称 /// </summary> public ArrayList GetAllTableNames() { System.Collections.ArrayList tableNames = new System.Collections.ArrayList(); string strcmd = "2AllTablesぺ" + this.Connstr + "ぺ"; string str = this.tsp.TCPString(strcmd); if (str.StartsWith("Error")) { StringOperate.Alert(str); } else { string[] strArr = str.Split(new char[] { 'ぺ' }); foreach (string s in strArr) { if (s.Length > 0 && !tableNames.Contains(s)) { tableNames.Add(s); } } } return(tableNames); }
public String Calculate(DateTime dateCalculate, ref DataTable inputPlan) { String errMessage = ""; try { inputPlan.PrimaryKey = new DataColumn[] { inputPlan.Columns["Date"], inputPlan.Columns["PartNumber"] }; ArrayList arrSubLine = new ArrayList(); for (int i = 0; i < inputPlan.Rows.Count; i++) { UpdateRowInformation(ref inputPlan, inputPlan.Rows[i], true); String subLineId = Utils.ObjectToString(inputPlan.Rows[i]["SubLine_ID"]); if (!arrSubLine.Contains(subLineId) && !String.IsNullOrEmpty(subLineId)) { arrSubLine.Add(subLineId); } } // for (int i = 0; i < arrSubLine.Count && String.IsNullOrEmpty(errMessage); i++) for (int i = 0; i < arrSubLine.Count; i++) { errMessage += FillShiftNameFromAndToTime(dateCalculate, arrSubLine[i].ToString(), ref inputPlan); } } catch (Exception ex) { errMessage += ex.Message; Logger.GetInstance().WriteException("Calculate", ex); } return errMessage; }
internal void AddRef(ArrayList list, XmlSchemaObject o) { if (((((o != null) && !this.schemas.IsReference(o)) && (o.Parent is XmlSchema)) && (((XmlSchema) o.Parent).TargetNamespace != "http://www.w3.org/2001/XMLSchema")) && !list.Contains(o)) { list.Add(o); } }
private static ArrayList threeSums(int[] numbers) { var sums = new ArrayList(); for (int i = 0; i < numbers.Length - 1; i++) { int j = i + 1; // start from i+1 int k = numbers.Length - 1; //start from end while (j < k) // pointer positions { int sum = numbers[i] + numbers[j] + numbers[k]; if (sum == 0) { var sumZeroList = new ArrayList {numbers[i], numbers[j], numbers[k]}; if (!sums.Contains(sumZeroList)) //duplicates not allowed { sums.Add(sumZeroList); } } if (sum < 0) // core logic { j++; //since sum is less than zero search for higher order number } else { k--; // since sum is greater than zero search for lower order numbers } } } return sums; }
public void scanning() { processesIds = new ArrayList(); while (true) { Process[] processes; processes = Process.GetProcesses(); for (int i = 0; i < processes.Length; i++) { if (processes[i].ProcessName == processName) { Cliente cliente = new Cliente(processes[i]); if (cliente.version() == version) { if (!(processesIds.Contains(cliente.id())) || processesIds.Count == 0) { processesIds.Add(cliente.id()); BackgroundWorker tibiaWorker = new BackgroundWorker(); tibiaWorker.DoWork += new DoWorkEventHandler(tibiaWorker_DoWork); tibiaWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(tibiaWorker_RunWorkerCompleted); tibiaWorker.RunWorkerAsync(cliente); } } } } Thread.Sleep(15000); } }
/// <summary> If we are leaving, we have to wait for the view change (last msg in the current view) that /// excludes us before we can leave. /// </summary> /// <param name="new_view">The view to be installed /// </param> /// <param name="digest"> If view is a MergeView, digest contains the seqno digest of all members and has to /// be set by GMS /// </param> public override void handleViewChange(View new_view, Digest digest) { if (gms.Stack.NCacheLog.IsInfoEnabled) { gms.Stack.NCacheLog.Info("ParticipentGMSImpl.handleViewChange", "received view"); } System.Collections.ArrayList mbrs = new_view.Members; gms.Stack.NCacheLog.Debug("view=");// + new_view); suspected_mbrs.Clear(); if (leaving && !mbrs.Contains(gms.local_addr)) { // received a view in which I'm not member: ignore return; } ViewId vid = gms.view_id != null?gms.view_id.Copy() : null; if (vid != null) { int rc = vid.CompareTo(new_view.Vid); if (rc < 0) { isNewMember = false; if (gms.Stack.NCacheLog.IsInfoEnabled) { gms.Stack.NCacheLog.Info("ParticipantGmsImp", "isNewMember : " + isNewMember); } } } gms.installView(new_view, digest); }
public DataTable GetBillingAccountsByBillingPeriodID(Int32 id) { EmployeeTimesheetInfoCollection col = FetchByBillingPeriodID(id); System.Collections.ArrayList accounts = new System.Collections.ArrayList(); DataTable accountstable = new DataTable(); accountstable.Columns.Add("AccountName"); accountstable.Columns.Add("AccountID"); foreach (EmployeeTimesheetInfo timesheetinfo in col) { if (accounts.Contains(timesheetinfo.Billingaccountid)) { continue; } DataRow newrow = accountstable.NewRow(); newrow["AccountName"] = timesheetinfo.Accountname; newrow["AccountID"] = timesheetinfo.Billingaccountid; accountstable.Rows.Add(newrow); accounts.Add(timesheetinfo.Billingaccountid); } return(accountstable); }
private static void CheckLineAreEqualEx(string expectPath, string outputPath, ArrayList ex, string msg) { if (!File.Exists(expectPath) || !File.Exists(outputPath)) { Assert.Fail(expectPath + " File missing"); } try { Int32 line = 0; StreamReader expectStream = new StreamReader(expectPath); StreamReader outputStream = new StreamReader(outputPath); while (!expectStream.EndOfStream) { line += 1; var expectLine = expectStream.ReadLine(); var outputLine = outputStream.ReadLine(); if (ex != null && ex.Contains(line)) { if (expectLine != outputLine) { Assert.Fail(msg); } } } if (!outputStream.EndOfStream) Assert.Fail(msg); expectStream.Close(); outputStream.Close(); } catch (Exception) { Assert.Fail(msg); } }
public void CATEGORIES() { iCalendar iCal = iCalendar.LoadFromFile(@"Calendars\General\CATEGORIES.ics"); Program.TestCal(iCal); Event evt = (Event)iCal.Events[0]; ArrayList items = new ArrayList(); items.AddRange(new string[] { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "A string of text with nothing less than a comma, semicolon; and a newline\n." }); Hashtable found = new Hashtable(); foreach (TextCollection tc in evt.Categories) { foreach (Text text in tc.Values) { if (items.Contains(text.Value)) found[text.Value] = true; } } foreach (string item in items) Assert.IsTrue(found.ContainsKey(item), "Event should contain CATEGORY '" + item + "', but it was not found."); }
protected void fillDdlMovie() { SqlConnection conn = new SqlConnection(); conn.ConnectionString = ConfigurationManager.ConnectionStrings["Konekcija"].ConnectionString; string sqlSelect = "SELECT * from Program"; SqlCommand command = new SqlCommand(sqlSelect, conn); try { conn.Open(); SqlDataReader reader = command.ExecuteReader(); ddlMovie.Items.Clear(); ArrayList listaMovie = new ArrayList(); while (reader.Read()) { if(!listaMovie.Contains(reader["Name"].ToString())) { listaMovie.Add(reader["Name"].ToString()); } } reader.Close(); ddlMovie.DataSource = listaMovie; ddlMovie.DataBind(); ddlMovie.Items.Insert(0, new ListItem("--Select Movie--","0")); } catch (Exception err) { } finally { conn.Close(); } }
public void ReentrantConstructors () { ArrayList user_ids = new ArrayList (4); IList users = UnixUserInfo.GetLocalUsers (); foreach (UnixUserInfo user in users) { try { UnixUserInfo byName = new UnixUserInfo (user.UserName); Assert.AreEqual (user, byName, "#TRC: construct by name"); if (! user_ids.Contains (user.UserId)) user_ids.Add (user.UserId); } catch (Exception e) { Assert.Fail ( string.Format ("#TRC: Exception constructing UnixUserInfo (string): {0}", e.ToString())); } } foreach (uint uid in user_ids) { try { UnixUserInfo byId = new UnixUserInfo (uid); Assert.IsTrue (users.Contains (byId), "TRC: construct by uid"); } catch (Exception e) { Assert.Fail ( string.Format ("#TRC: Exception constructing UnixUserInfo (uint): {0}", e.ToString())); } } }
///<summary> /// Add a file to the collection /// </summary> /// <param name="Path">File path</param> /// <param name="ArchiveDirectory">Extra Path for example \folder1, Can also be empty</param> public void AddFile(String Path, String ExtraPath) { if (!FileList.Contains(Path)) { FileList.Add(Path); FileNames.Add(ExtraPath + new System.IO.FileInfo(Path).Name); } }
private void AddToHistory() { if (!history.Contains(this.QueryTextBox.Text)) { this.QueryTextBox.Items.Add(this.QueryTextBox.Text); this.history.Add(this.QueryTextBox.Text); } }
public bool Contains(TileListItem value) { // TODO: Add ControlListView.Contains implementation if (this.SelectedItem == value) { value.Selected = false; } return(controlList.Contains(value)); }
private static void Main(string[] args) { Console.Title = "Random Number Generator Based On Algorithm 2"; Console.WriteLine("Hello, It is developed by Mr. Touraj Ostovari in order university home work! \n Y: 2020"); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("\n (based on your entry number would be generated next numbers, \n when reptative or 0 numbers appeared means your algo is exposed) \n"); Console.ForegroundColor = ConsoleColor.Green; Console.Write("Enter your number ONE:: "); Int64 num1 = Int64.Parse(Console.ReadLine()); Console.Write("Enter your number TWO:: "); Int64 num2 = Int64.Parse(Console.ReadLine()); try { while (true) { string temp = (num1 * num2).ToString(); if ((temp.Length % 2) != 0) { temp = "0" + temp; } if (temp[0] == 0) { temp = "0" + temp; } string tempx = ""; for (int i = 2; i < temp.Length - 2; i++) { tempx += (temp[i]); } if (!list.Contains(tempx)) { list.Add(tempx); } else { break; } Console.WriteLine(string.Concat("0.", tempx)); num2 = Int64.Parse(tempx); } } catch (Exception) { goto End; } End: Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("if 0. appeared means algo is exposed ..."); Console.ForegroundColor = ConsoleColor.White; Console.Write("\nPress any key to exit ..."); Console.ReadKey(); }
public static void AddIfNotContains(System.Collections.ArrayList hashtable, System.Object item) { // see AddIfNotContains(Hashtable, object) for information about the lock lock (hashtable) { if (hashtable.Contains(item) == false) { hashtable.Add(item); } } }
private void vRefreshBancos(ref mdlComponentesGraficos.ListView lvBancos) { lvBancos.Items.Clear(); System.Collections.ArrayList arlCondicaoCampo = new ArrayList(); System.Collections.ArrayList arlCondicaoComparador = new ArrayList(); System.Collections.ArrayList arlCondicaoValor = new ArrayList(); // Carregando os Dados arlCondicaoCampo.Add("nIdExportador"); arlCondicaoComparador.Add(mdlDataBaseAccess.Comparador.Igual); arlCondicaoValor.Add(m_nIdExportador); mdlDataBaseAccess.Tabelas.XsdTbExportadoresBancos typDatSetExportadoresBancos = m_cls_dba_ConnectionDB.GetTbExportadoresBancos(arlCondicaoCampo, arlCondicaoComparador, arlCondicaoValor, null, null); mdlDataBaseAccess.Tabelas.XsdTbContratosCambio typDatSetContratosCambio = m_cls_dba_ConnectionDB.GetTbContratosCambio(arlCondicaoCampo, arlCondicaoComparador, arlCondicaoValor, null, null); arlCondicaoCampo.Add("strIdPe"); arlCondicaoComparador.Add(mdlDataBaseAccess.Comparador.Igual); arlCondicaoValor.Add(m_strIdCodigo); mdlDataBaseAccess.Tabelas.XsdTbProdutosBordero typDatSetProdutosBordero = m_cls_dba_ConnectionDB.GetTbProdutosBordero(arlCondicaoCampo, arlCondicaoComparador, arlCondicaoValor, null, null); System.Collections.ArrayList arlBancos = new System.Collections.ArrayList(); arlBancos.Add(m_nIdBancoExportadorFaturaComercial); foreach (mdlDataBaseAccess.Tabelas.XsdTbProdutosBordero.tbProdutosBorderoRow dtrwProduto in typDatSetProdutosBordero.tbProdutosBordero.Rows) { foreach (mdlDataBaseAccess.Tabelas.XsdTbContratosCambio.tbContratosCambioRow dtrwContratoCambio in typDatSetContratosCambio.tbContratosCambio.Rows) { if (dtrwContratoCambio.nIdContratoCambio == dtrwProduto.nIdContratoCambio) { if (!arlBancos.Contains(dtrwContratoCambio.nIdExportadorBanco)) { arlBancos.Add(dtrwContratoCambio.nIdExportadorBanco); } break; } } } System.Windows.Forms.ListViewItem lviBanco; // Inserindo Bancos dos Contratos de Cambio for (int i = 0; i < arlBancos.Count; i++) { mdlDataBaseAccess.Tabelas.XsdTbExportadoresBancos.tbExportadoresBancosRow dtrwBanco = typDatSetExportadoresBancos.tbExportadoresBancos.FindBynIdExportadornIdBanco(m_nIdExportador, Int32.Parse(arlBancos[i].ToString())); if (dtrwBanco != null) { lviBanco = lvBancos.Items.Add(dtrwBanco.strNome); lviBanco.Tag = dtrwBanco.nIdBanco; if (dtrwBanco.nIdBanco == m_nIdBancoExportadorFaturaComercial) { lviBanco.ForeColor = System.Drawing.Color.Red; } } } }
//----------------------- public void GetPointsFromPolys(System.Collections.ArrayList apolys, ref System.Collections.ArrayList run) { foreach (int idx in apolys) { Poly pol = Items[idx]; if (!(run.Contains(pol.p1))) { run.Add(pol.p1); } if (!(run.Contains(pol.p2))) { run.Add(pol.p2); } if (!(run.Contains(pol.p3))) { run.Add(pol.p3); } } }
public string[] Unique(string[] list) { System.Collections.ArrayList newList = new System.Collections.ArrayList(); foreach (string str in list) { if (!newList.Contains(str)) { newList.Add(str); } } return((string[])newList.ToArray(typeof(string))); }
/// <summary> /// remove duplicates from string Array /// </summary> /// <param name="myList"></param> /// <returns></returns> public static string[] RemoveDuplicates(string[] myList) { System.Collections.ArrayList newList = new System.Collections.ArrayList(); foreach (string str in myList) { if (!newList.Contains(str)) { newList.Add(str); } } return((string[])newList.ToArray(typeof(string))); }
/// <summary> /// Collect the appenders from an <see cref="IAppenderAttachable"/>. /// The appender may also be a container. /// </summary> /// <param name="appenderList"></param> /// <param name="appender"></param> private static void CollectAppender(System.Collections.ArrayList appenderList, Appender.IAppender appender) { if (!appenderList.Contains(appender)) { appenderList.Add(appender); IAppenderAttachable container = appender as IAppenderAttachable; if (container != null) { CollectAppenders(appenderList, container); } } }
public ulong[,] CaluateErrorMatrixSecond(int X, string ResultClassField, string RealGroundField, string StatisticField, string OnlyIdField) { DataTable dt = attributeTable; //操作的属性表 ulong[,] Matrix = new ulong[X, X]; //这里X代表的数组的维数 (3*3) 但是数组下标是从0~2 区分这个概念OK! ArrayList OnlyID = new System.Collections.ArrayList(); //ArrayList 类 第一次用 for (int i = 0; i < dt.Rows.Count; i++) //1.首先把分类结果的每个独立ID找出来,这样才能对每一块判断最大面积 { if (!OnlyID.Contains(Convert.ToInt32(dt.Rows[i][OnlyIdField].ToString()))) //contains是一个查询函数 函数 { OnlyID.Add(Convert.ToInt32(dt.Rows[i][OnlyIdField].ToString())); } } for (int j = 0; j < OnlyID.Count; j++) //2.对每一个裁剪前的结果类别小版块 进行计算,找出最大面积的小版块的属性 并赋给最终二维矩阵(属性 和 总面积) { int MatrixFirstNum = 0; //最大面积对应的类别 编号 class class_1 输出的 int MatrixSecondNum = 0; ulong maxarea = 0; //最大面积 用于确定MatrixFirstNum,MatrixLastNum ulong areaplusing = 0; //中间计算相加的面积 ulong areaSmallClass = 0; //每个小类别版块 的总面积 输出的 for (int i = 0; i < dt.Rows.Count; i++) //循环表的 所有行 { int classIDonly; //表中字段的ID classIDonly = Convert.ToInt32(dt.Rows[i][OnlyIdField].ToString()); if (Convert.ToInt32(OnlyID[j].ToString()) == classIDonly) //如果OnlyIdField字段 和 唯一ID数据组【j】 吻合 //则需要统计 最大面积的class 和class_1 以及面积总和 { areaplusing = Convert.ToUInt64(dt.Rows[i][StatisticField]); if (Convert.ToUInt64(dt.Rows[i][StatisticField]) > maxarea) //找最大面积 { maxarea = Convert.ToUInt64(dt.Rows[i][StatisticField]); //更换最大面积 MatrixFirstNum = Convert.ToInt32(dt.Rows[i][ResultClassField]); //更换最大面积对应的类别编号 MatrixSecondNum = Convert.ToInt32(dt.Rows[i][RealGroundField]); } areaSmallClass += areaplusing; //计算面积和 } } Matrix[MatrixFirstNum - 1, MatrixSecondNum - 1] += areaSmallClass;// 为矩阵加入数值 注意顺序 行和列的区分!此时 行为结果 列为真实 } return(Matrix); }
public ArrayList RemoveDuplicates(ArrayList inputArray) { System.Collections.ArrayList distinctArray = new System.Collections.ArrayList(); foreach (string element in inputArray) { if (!distinctArray.Contains(element)) { distinctArray.Add(element); } } return(distinctArray); }
//----------------------- public void GetpolysWithPoint(int midlepick, ref System.Collections.ArrayList run) { for (int i = 0; i < Items.Count; i++) { if (Items[i].p1 == midlepick || Items[i].p2 == midlepick || Items[i].p3 == midlepick) { if (!run.Contains(i)) { Items[i].active = true; run.Add(i); } } } }
static public int Contains(IntPtr l) { try { System.Collections.ArrayList self = (System.Collections.ArrayList)checkSelf(l); System.Object a1; checkType(l, 2, out a1); var ret = self.Contains(a1); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
public string[] no_chongfu(string[] zj_id) { System.Collections.ArrayList al = new System.Collections.ArrayList(); for (int j = 0; j < zj_id.Length; j++) { //判断是否已经存在 if (al.Contains(zj_id[j]) == false) { al.Add(zj_id[j]); } } zj_id = new String[al.Count]; zj_id = (string[])al.ToArray(typeof(string)); return(zj_id); }
static int Contains(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); System.Collections.ArrayList obj = (System.Collections.ArrayList)ToLua.CheckObject(L, 1, typeof(System.Collections.ArrayList)); object arg0 = ToLua.ToVarObject(L, 2); bool o = obj.Contains(arg0); LuaDLL.lua_pushboolean(L, o); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
//CREATES A ROLE LIST BASED ON ROLES SELECTED. NOTE: THERE WILL BE MANY DUPLICATES! private ArrayList RoleLogic(ArrayList roles_to_add) { //IF ADMINISTRATOR, GRANT ALL ROLES if (roles_to_add.Contains(UpdateUtils.ROLE_ADMINISTRATOR)) { return(new ArrayList(Roles.GetAllRoles())); } //IF DATA MANAGER, ALSO MUST BE A CONTIBUTOR if (roles_to_add.Contains(UpdateUtils.ROLE_DATA_MANAGER)) { if (!roles_to_add.Contains(UpdateUtils.ROLE_DATA_CONTRIBUTOR)) { roles_to_add.Add(UpdateUtils.ROLE_DATA_CONTRIBUTOR); } } //IF DATA CONTRIBUTOR, THEN DON'T NEED TO ADD ANYTHIMG //IF FULL VIEWER, THEY MUST BE INTERMEDIATE AND PUBLIC if (roles_to_add.Contains(UpdateUtils.ROLE_FULL_VIEWER)) { if (!roles_to_add.Contains(UpdateUtils.ROLE_INTERMEDIATE_VIEWER)) { roles_to_add.Add(UpdateUtils.ROLE_INTERMEDIATE_VIEWER); } if (!roles_to_add.Contains(UpdateUtils.ROLE_PUBLIC_VIEWER)) { roles_to_add.Add(UpdateUtils.ROLE_PUBLIC_VIEWER); } } //IF INTERMEDIATE, MUST BE PUBLIC if (roles_to_add.Contains(UpdateUtils.ROLE_INTERMEDIATE_VIEWER)) { if (!roles_to_add.Contains(UpdateUtils.ROLE_PUBLIC_VIEWER)) { roles_to_add.Add(UpdateUtils.ROLE_PUBLIC_VIEWER); } } //RETURN FULL LIST return(roles_to_add); }
static void Main(string[] args) { System.Collections.ArrayList list = new System.Collections.ArrayList(); list.Add("World"); list.Add("Hello"); Console.WriteLine("Count {0}", list.Count); Console.WriteLine("Capacity {0}", list.Capacity); //can set capacuty when list is created also list.Sort(); PrintCollections(list); Console.WriteLine("list[0] = {0}", list[0]); Console.WriteLine("list[1] = {0}", list[1]); Console.WriteLine("Contains Hello {0}", list.Contains("Hello")); //must walk through each item in the array to do a comparison list.BinarySearch("Hello"); //list must be sorted first, much faster than contains search }
private static int nextIndex = 1; // Used for differentiating delegate names within the assembly if necessary. /// <summary> /// This method is called by the DefineNETDelegate Mathematica function. /// </summary> /// <remarks> /// Thie method dynamically creates and returns a new delegate Type object. It does not actually create an /// instance of the type--that would be done by a later call to the Mathematica function NETNewDelegate, which /// calls the createDynamicMethod method above. /// <para> /// This is a rarely-used method. It is only needed when there is not an existing delegate type for a method signature /// you want to use as a callback to Mathematica (refer to the DefineNETDelegate Mathematica function for more information). /// </para> /// </remarks> /// internal static string defineDelegate(string name, string retTypeName, string[] paramTypeNames) { Type retType = retTypeName == null ? typeof(void) : TypeLoader.GetType(Utils.addSystemNamespace(retTypeName), true); Type[] paramTypes = new Type[paramTypeNames == null ? 0 : paramTypeNames.Length]; if (paramTypeNames != null) { for (int i = 0; i < paramTypes.Length; i++) { paramTypes[i] = TypeLoader.GetType(Utils.addSystemNamespace(paramTypeNames[i]), true); } } // Check to see if incoming name conflicts with an existing type name. This is easy to get if user reevals a // DefineNETDelegate call without changing the type name. We make the change for them. Type[] existingTypes = delegateModuleBuilder.GetTypes(); // Use an ArrayList instead of a plain array so that we can simply the name-checking logic by using the Contains() method. System.Collections.ArrayList existingNames = new System.Collections.ArrayList(existingTypes.Length); foreach (Type t in existingTypes) { existingNames.Add(t.Name); } string uniqueName = name; while (existingNames.Contains(uniqueName)) { uniqueName = name + "$" + (nextIndex++); } TypeBuilder typeBuilder = delegateModuleBuilder.DefineType(delegateNamespace + "." + uniqueName, TypeAttributes.Public | TypeAttributes.AutoLayout | TypeAttributes.AnsiClass | TypeAttributes.Sealed, typeof(MulticastDelegate)); ConstructorBuilder ctorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, new Type[] { typeof(object), typeof(int) }); ctorBuilder.SetImplementationFlags(MethodImplAttributes.Managed | MethodImplAttributes.Runtime); MethodBuilder methodBuilder = typeBuilder.DefineMethod("Invoke", MethodAttributes.Public | MethodAttributes.Virtual, retType, paramTypes); methodBuilder.SetImplementationFlags(MethodImplAttributes.Managed | MethodImplAttributes.Runtime); Type newType = typeBuilder.CreateType(); return(newType.FullName); }