public GetRange ( int index, int count ) : ArrayList | ||
index | int | |
count | int | |
return | ArrayList |
public void Test(int arg) { ArrayList items = new ArrayList(); items.Add(1); items.AddRange(1, 2, 3); items.Clear(); bool b1 = items.Contains(2); items.Insert(0, 1); items.InsertRange(1, 0, 5); items.RemoveAt(4); items.RemoveRange(4, 3); items.Remove(1); object[] newItems = items.GetRange(5, 2); object[] newItems2 = items.GetRange(5, arg); List<int> numbers = new List<int>(); numbers.Add(1); numbers.AddRange(1, 2, 3); numbers.Clear(); bool b2 = numbers.Contains(4); numbers.Insert(1, 10); numbers.InsertRange(2, 10, 3); numbers.RemoveAt(4); numbers.RemoveRange(4, 2); int[] newNumbers = items.GetRange(5, 2); int[] newNumbers2 = items.GetRange(5, arg); string[] words = new string[5]; words[0] = "hello"; words[1] = "world"; bool b3 = words.Contains("hi"); string[] newWords = words.GetRange(5, 2); string[] newWords2 = words.GetRange(5, arg); }
public ArrayList Sort(ArrayList inArray) { if (1 == inArray.Count) return inArray; int middle = inArray.Count >> 1; ArrayList left = Sort(inArray.GetRange(0, middle)); ArrayList right = Sort(inArray.GetRange(middle, inArray.Count - middle)); return Merge(left, right); }
private string Breaker(ArrayList Cell_String) { for (int i = 1; i < Cell_String.Count; i++) { if (Fun_Class.IsFunction(Cell_String[i].ToString())) { int found = 1; int start = i + 1; while (found != 0) { start++; if (Cell_String[start].ToString().Equals("(")) found++; if (Cell_String[start].ToString().Equals(")")) found--; } ArrayList atemp = new ArrayList(Cell_String.GetRange(i, start - i + 1)); Cell_String.RemoveRange(i, start - i + 1); Cell_String.Insert(i, Breaker(atemp)); } } //PrintArrayList(Cell_String); //System.Console.WriteLine(Cell_String[0].ToString()); return Fun_Class.CallFunction(Cell_String); }
public void TestGetItems() { //-------------------------------------------------------------------------- // Variable definitions. //-------------------------------------------------------------------------- ArrayList arrList = null; // // Construct array list. // arrList = new ArrayList(); // Add items to the lists. for (int ii = 0; ii < strHeroes.Length; ++ii) { arrList.Add(strHeroes[ii]); } // Verify items added to list. Assert.Equal(strHeroes.Length, arrList.Count); //Adapter, GetRange, Synchronized, ReadOnly returns a slightly different version of //BinarySearch, Following variable cotains each one of these types of array lists ArrayList[] arrayListTypes = { (ArrayList)arrList.Clone(), (ArrayList)ArrayList.Adapter(arrList).Clone(), (ArrayList)ArrayList.FixedSize(arrList).Clone(), (ArrayList)ArrayList.ReadOnly(arrList).Clone(), (ArrayList)arrList.GetRange(0, arrList.Count).Clone(), (ArrayList)ArrayList.Synchronized(arrList).Clone()}; foreach (ArrayList arrayListType in arrayListTypes) { arrList = arrayListType; // // [] Verify get method. // // Search and verify selected items. for (int ii = 0; ii < strHeroes.Length; ++ii) { // Verify get. Assert.Equal(0, ((string)arrList[ii]).CompareTo(strHeroes[ii])); } // // [] Invalid Index. // Assert.Throws<ArgumentOutOfRangeException>(() => { string str = (string)arrList[(int)arrList.Count]; }); Assert.Throws<ArgumentOutOfRangeException>(() => { string str = (string)arrList[-1]; }); } }
public override ArrayList select(ArrayList gens) { int nr; if (gens.Count >= this._newPopSize) nr = (int)(gens.Count * this._newPopSize); else nr = 1; gens.Sort((IComparer)new GenomeComparer()); return gens.GetRange(0, nr); }
static void Main(string[] args) { ArrayList al = new ArrayList(); al.Add("Paris"); al.Add("Ottowa"); al.AddRange(new string[] { "Rome", "Tokyo", "Tunis", "Canberra" }); Console.WriteLine("Count: {0}", al.Count); Console.WriteLine("Capacity: {0}", al.Capacity); Console.WriteLine("Print values using foreach"); PrintValues(al); Console.WriteLine("Print values using IEnumerator"); PrintValuesByEnumerator(al); // Get second item in list as string string str = (string)al[1]; // need to cast, would also unbox if stored type was value type Console.WriteLine("al[1] = {0}", str); // Get first three items ArrayList firstThree = al.GetRange(0, 3); PrintValues(firstThree); // Remove next two al.RemoveRange(3, 2); PrintValues(al); // Get, insert and remove object itemOne = al[1]; al.Insert(1, "Moscow"); al.RemoveAt(2); PrintValues(al); // Sort al.Sort(); PrintValues(al); // Search int targetIndex = al.BinarySearch("Moscow"); Console.WriteLine("Index of Moscow: {0}", targetIndex); // Trim capacity al.TrimToSize(); Console.WriteLine("Count: {0}", al.Count); Console.WriteLine("Capacity: {0}", al.Capacity); // Creates a new ArrayList with five elements and initialize each element with a value. ArrayList al2 = ArrayList.Repeat("Boston", 5); // static method PrintValues(al2); }
public ArrayList Recombine(ArrayList maleGenes, ArrayList femaleGenes) { double maleConstraint = random.NextDouble(); int maleCount = (int)Math.Ceiling(maleGenes.Count * maleConstraint); int femaleCount = (int)Math.Floor(femaleGenes.Count * (1-maleConstraint)); ArrayList child = new ArrayList(maleCount + femaleCount); child.InsertRange(0, maleGenes.GetRange(0, maleCount)); child.InsertRange(maleCount, femaleGenes.GetRange(femaleGenes.Count - femaleCount, femaleCount)); for (int i = 0; i < child.Count; i++) child[i] = (child[i] as IGene).Clone(); return child; }
/// <summary> /// Joins a new string with the elements of the array. /// </summary> /// <param name="joiner">The joiner.</param> /// <param name="joinees">The joinees.</param> /// <returns>The combined string.</returns> public static string Join(string joiner, ArrayList joinees) { if (joinees.Count == 0) { return string.Empty; } string joined = (string)joinees[0]; foreach (string str in joinees.GetRange(1, joinees.Count - 1)) { joined = joined + joiner + str; } return joined; }
public ArrayList Recombine(ArrayList maleGenes, ArrayList femaleGenes) { if (maleGenes.Count != femaleGenes.Count) throw new GenesIncompatibleException(); ArrayList child = new ArrayList(maleGenes.Count); int middle = maleGenes.Count / 2; child.InsertRange(0, maleGenes.GetRange(0, middle).Clone() as ArrayList); child.InsertRange(middle, femaleGenes.GetRange(middle, femaleGenes.Count - middle).Clone() as ArrayList); // Create Deep Copy for (int i = 0; i < child.Count; i++) child[i] = (child[i] as IGene).Clone(); return child; }
public static ArrayList Merge(ArrayList left, ArrayList right) { var result = new ArrayList(); int leftptr=0, rightptr=0; while (leftptr < left.Count && rightptr < right.Count) result.Add((int) left[leftptr] < (int) right[rightptr] ? left[leftptr++] : right[rightptr++]); if (leftptr < left.Count) result.AddRange(left.GetRange(leftptr, left.Count - leftptr)); if (rightptr < right.Count) result.AddRange(right.GetRange(rightptr, right.Count - rightptr)); return result; }
private void addToListBox(ArrayList list) { try { int rango = list.Count - posListBox * 10; if (rango > 10) rango = 10; foreach (Frases item in list.GetRange(posListBox * 10, rango)) { lbFrases.Items.Add(item.Autor + ": \t" + item.Frase); } } catch { } }
static public int GetRange(IntPtr l) { try { System.Collections.ArrayList self = (System.Collections.ArrayList)checkSelf(l); System.Int32 a1; checkType(l, 2, out a1); System.Int32 a2; checkType(l, 3, out a2); var ret = self.GetRange(a1, a2); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
static int GetRange(IntPtr L) { try { ToLua.CheckArgsCount(L, 3); System.Collections.ArrayList obj = (System.Collections.ArrayList)ToLua.CheckObject(L, 1, typeof(System.Collections.ArrayList)); int arg0 = (int)LuaDLL.luaL_checknumber(L, 2); int arg1 = (int)LuaDLL.luaL_checknumber(L, 3); System.Collections.ArrayList o = obj.GetRange(arg0, arg1); ToLua.PushObject(L, o); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
static void Main(string[] args) { //Create an ArrayList and add two ints ArrayList list = new ArrayList(); list.Add("bird"); list.Add("rock"); list.Add("jacket"); list.Add("shoe"); // Get Last two elements in ArrayList ArrayList range = list.GetRange(2, 2); //Display Elements foreach (string value in range) { Console.WriteLine(value); // jacket, shoe } }
public void TestArrayListWrappers() { ArrayList alst1; string strValue; Array arr1; //[] Vanila test case - ToArray returns an array of this. We will not extensively test this method as // this is a thin wrapper on Array.Copy which is extensively tested elsewhere alst1 = new ArrayList(); for (int i = 0; i < 10; i++) { strValue = "String_" + i; alst1.Add(strValue); } ArrayList[] arrayListTypes = { alst1, ArrayList.Adapter(alst1), ArrayList.FixedSize(alst1), alst1.GetRange(0, alst1.Count), ArrayList.ReadOnly(alst1), ArrayList.Synchronized(alst1)}; foreach (ArrayList arrayListType in arrayListTypes) { alst1 = arrayListType; arr1 = alst1.ToArray(typeof(string)); for (int i = 0; i < 10; i++) { strValue = "String_" + i; Assert.Equal(strValue, (string)arr1.GetValue(i)); } //[] this should be covered in Array.Copy, but lets do it for Assert.Throws<InvalidCastException>(() => { arr1 = alst1.ToArray(typeof(int)); }); Assert.Throws<ArgumentNullException>(() => { arr1 = alst1.ToArray(null); }); } //[]lets try an empty list alst1.Clear(); arr1 = alst1.ToArray(typeof(Object)); Assert.Equal(0, arr1.Length); }
/* * PBKDF2 as described in PKCS #5 v2.0 pp.8-10 */ private static byte[] PBKDF2(byte[] passphrase, byte[] salt, int c, int dkLen) { const int hLen = 20; int l = (int) Math.Ceiling((double) dkLen/hLen); //int r = dkLen - (l - 1)*hLen; ArrayList result = new ArrayList(dkLen); for (int i = 0; i < l; i++) { result.AddRange(F(passphrase, salt, c, i)); } return (byte[]) result.GetRange(0, dkLen).ToArray(Type.GetType("System.Byte")); }
private static AESInfo DeriveKeyAndIV(String passphrase, byte[] salt, int keyLen, int IVLen) { const int saltLength = 8; int k = keyLen/8; int i = IVLen/8; AESInfo result = new AESInfo(); byte[] passphraseBytes = Encoding.UTF8.GetBytes(passphrase); if (salt == null) { result.salt = new byte[saltLength]; Random random = new Random(); random.NextBytes(result.salt); } else { result.salt = salt; } ArrayList keyAndIV = new ArrayList(k + i); keyAndIV.AddRange(PBKDF2(passphraseBytes, result.salt, 10000, k + i)); result.key = (byte[]) keyAndIV.GetRange(0, k).ToArray(Type.GetType("System.Byte")); result.IV = (byte[]) keyAndIV.GetRange(k, i).ToArray(Type.GetType("System.Byte")); return result; }
public static byte[] RAWDecrypt(byte[] cipherText, String privateKey) { int ebs = RSAKeySize/8; Rijndael aes = Rijndael.Create(); ArrayList bytes = new ArrayList(cipherText); byte[] keyPart = (byte[]) bytes.GetRange(0, ebs).ToArray(Type.GetType("System.Byte")); byte[] key = RSADecrypt(keyPart, privateKey); byte[] IV = RSADecrypt((byte[]) bytes.GetRange(ebs, ebs).ToArray(Type.GetType("System.Byte")), privateKey); byte[] message = (byte[]) bytes.GetRange(ebs*2, bytes.Count - ebs*2).ToArray(Type.GetType("System.Byte")); return AESDecrypt(message, aes.CreateDecryptor(key, IV)); }
public static AESInfo Destruct(String message, String privateKey) { int ebs = RSAKeySize/8; AESInfo result = new AESInfo(); ArrayList bytes = new ArrayList(Convert.FromBase64String(StripMessage(message))); byte[] keyPart = (byte[]) bytes.GetRange(0, ebs).ToArray(Type.GetType("System.Byte")); result.key = RSADecrypt(keyPart, privateKey); result.IV = RSADecrypt((byte[]) bytes.GetRange(ebs, ebs).ToArray(Type.GetType("System.Byte")), privateKey); result.message = (byte[]) bytes.GetRange(ebs*2, bytes.Count - ebs*2).ToArray(Type.GetType("System.Byte")); return result; }
private void GetTrainPersonImages(string trainPersonName) { string strFile = m_rootPath + trainPersonName+"\\info.txt"; try { if (File.Exists(strFile)) { using (StreamReader sr = new StreamReader(strFile, Encoding.GetEncoding("gb2312"))) { ArrayList str_list = new ArrayList(); while (sr.Peek() >= 0) { string str = sr.ReadLine(); str = m_rootPath + trainPersonName + "\\"+str; str_list.Add(str); } int count = str_list.Count; m_trainPersonImagesInfo = str_list.GetRange(3, count - 3); } } } catch (System.Exception ex) { MessageBox.Show(ex.Message); } }
public void TestSetItems() { //-------------------------------------------------------------------------- // Variable definitions. //-------------------------------------------------------------------------- ArrayList arrList = null; // // Construct array list. // arrList = new ArrayList((ICollection)strHeroes); //Adapter, GetRange, Synchronized, ReadOnly returns a slightly different version of //BinarySearch, Following variable cotains each one of these types of array lists ArrayList[] arrayListTypes = { (ArrayList)arrList.Clone(), (ArrayList)ArrayList.Adapter(arrList).Clone(), (ArrayList)ArrayList.FixedSize(arrList).Clone(), (ArrayList)arrList.GetRange(0, arrList.Count).Clone(), (ArrayList)ArrayList.Synchronized(arrList).Clone()}; foreach (ArrayList arrayListType in arrayListTypes) { arrList = arrayListType; // // [] Set item in the array list. // arrList[0] = "Lone Ranger"; // Verify set. Assert.Equal(0, ((string)arrList[0]).CompareTo("Lone Ranger")); // // [] Attempt invalid Set using negative index // Assert.Throws<ArgumentOutOfRangeException>(() => { arrList[-100] = "Lone Ranger"; }); // // [] Attempt Set using out of range index=1000 // Assert.Throws<ArgumentOutOfRangeException>(() => { arrList[1000] = "Lone Ranger"; }); // // [] Attempt Set using out of range index=-1 // Assert.Throws<ArgumentOutOfRangeException>(() => { arrList[-1] = "Lone Ranger"; }); // // [] Attempt Set using null value. // arrList[0] = null; // Verify set. Assert.Null(arrList[0]); } }
/* NOT COMPLETE YET (Cell Reference,A1) * THIS NEED TO BE SOLVED BY UI! * The UI team needs to setup a mathod that takes a Cell Reference as a string and return the formula. */ private ArrayList Reformat(ArrayList Parts) { #region SECTION REMOVER () for (int i = 0; i < Parts.Count; i++) { int second = i - 1; if (second == -1) second = 0; if (Parts[i].ToString().Equals("(") && !Fun_Class.IsFunction(Parts[second].ToString()) && !IsNumber(Parts[second].ToString())) { //PrintArrayList(Parts); int found = 1; int start = i; while (found != 0) { start++; if (Parts[start].ToString().Equals("(")) found++; if (Parts[start].ToString().Equals(")")) found--; } ArrayList atemp = new ArrayList(Parts.GetRange(i + 1, start - i + 1 - 2)); Parts.RemoveRange(i, start - i + 1); Parts.InsertRange(i, Reformat(atemp)); } } #endregion #region SHORTCUT REMOVER * and / for (int i = 0; i < Parts.Count; i++) { string function; if (Parts[i].ToString().Equals("*") || Parts[i].ToString().Equals("/")) { //PrintArrayList(Parts); if (Parts[i].ToString().Equals("*")) function = "MUL"; else function = "DIV"; try { int first = i - 1, second = i + 2; if ((i + 2) >= Parts.Count) second--; if (Parts[first].ToString().Equals(")") && !Parts[second].ToString().Equals("(")) { int found = 1; int start = i - 1; while (found != 0) { start--; if (Parts[start].ToString().Equals(")")) found++; if (Parts[start].ToString().Equals("(")) found--; } Parts.Insert(i, ")"); Parts.Insert(i, Parts[i + 2]); Parts.Insert(i, ","); Parts.InsertRange(i, Parts.GetRange(start - 1, i - start + 1)); Parts.Insert(i, "("); Parts.Insert(i, function); Parts.RemoveAt(i + (i - start + 1) + 5); Parts.RemoveAt(i + (i - start + 1) + 5); Parts.RemoveRange(start - 1, i - start + 1); } else { if (!Parts[first].ToString().Equals(")") && Parts[second].ToString().Equals("(")) { int found = 1; int start = i + 2; while (found != 0) { start++; if (Parts[start].ToString().Equals("(")) found++; if (Parts[start].ToString().Equals(")")) found--; } Parts.Insert(start + i, ")"); Parts.Insert(i + 1, ","); Parts.Insert(i + 1, Parts[i - 1]); Parts.Insert(i + 1, "("); Parts.Insert(i + 1, function); Parts.RemoveAt(i - 1); Parts.RemoveAt(i - 1); } else { if (!Parts[first].ToString().Equals(")") && !Parts[second].ToString().Equals("(")) { Parts.Insert(i, ")"); Parts.Insert(i, Parts[i + 2]); Parts.Insert(i, ","); Parts.Insert(i, Parts[i - 1]); Parts.Insert(i, "("); Parts.Insert(i, function); Parts.RemoveAt(i + 6); Parts.RemoveAt(i + 6); Parts.RemoveAt(i - 1); } else { if (Parts[first].ToString().Equals(")") && Parts[second].ToString().Equals("(")) { int found = 1; int start = i + 2; while (found != 0) { start++; if (Parts[start].ToString().Equals("(")) found++; if (Parts[start].ToString().Equals(")")) found--; } Parts.Insert(start + 1, ")"); Parts[i] = ","; found = 1; start = i - 1; while (found != 0) { start--; if (Parts[start].ToString().Equals(")")) found++; if (Parts[start].ToString().Equals("(")) found--; } Parts.Insert(start - 1, "("); Parts.Insert(start - 1, function); } } } } } catch { OutFile.WriteLine("ERROR: INCORRECT INPUT STRING"); //ERROR: INCORRECT INPUT STRING Form1.Step("ERROR: INCORRECT INPUT STRING"); return Tokenize(Base_String); } } } #endregion #region SHORTCUT REMOVER + and - for (int i = 0; i < Parts.Count; i++) { //SHORTCUT REMOVER string function; if (Parts[i].ToString().Equals("+") || Parts[i].ToString().Equals("-")) { //PrintArrayList(Parts); if (Parts[i].ToString().Equals("+")) function = "ADD"; else function = "SUB"; try { int first = i - 1, second = i + 2; if ((i + 2) >= Parts.Count) second--; if (Parts[first].ToString().Equals(")") && !Parts[second].ToString().Equals("(")) { int found = 1; int start = i - 1; while (found != 0) { start--; if (Parts[start].ToString().Equals(")")) found++; if (Parts[start].ToString().Equals("(")) found--; } Parts.Insert(i, ")"); Parts.Insert(i, Parts[i + 2]); Parts.Insert(i, ","); Parts.InsertRange(i, Parts.GetRange(start - 1, i - start + 1)); Parts.Insert(i, "("); Parts.Insert(i, function); Parts.RemoveAt(i + (i - start + 1) + 5); Parts.RemoveAt(i + (i - start + 1) + 5); Parts.RemoveRange(start - 1, i - start + 1); } else { if (!Parts[first].ToString().Equals(")") && Parts[second].ToString().Equals("(")) { int found = 1; int start = i + 2; while (found != 0) { start++; if (Parts[start].ToString().Equals("(")) found++; if (Parts[start].ToString().Equals(")")) found--; } Parts.Insert(start + i, ")"); Parts.Insert(i + 1, ","); Parts.Insert(i + 1, Parts[i - 1]); Parts.Insert(i + 1, "("); Parts.Insert(i + 1, function); Parts.RemoveAt(i - 1); Parts.RemoveAt(i - 1); } else { if (!Parts[first].ToString().Equals(")") && !Parts[second].ToString().Equals("(")) { Parts.Insert(i, ")"); Parts.Insert(i, Parts[i + 2]); Parts.Insert(i, ","); Parts.Insert(i, Parts[i - 1]); Parts.Insert(i, "("); Parts.Insert(i, function); Parts.RemoveAt(i + 6); Parts.RemoveAt(i + 6); Parts.RemoveAt(i - 1); } else { if (Parts[first].ToString().Equals(")") && Parts[second].ToString().Equals("(")) { int found = 1; int start = i + 2; while (found != 0) { start++; if (Parts[start].ToString().Equals("(")) found++; if (Parts[start].ToString().Equals(")")) found--; } Parts.Insert(start + 1, ")"); Parts[i] = ","; found = 1; start = i - 1; while (found != 0) { start--; if (Parts[start].ToString().Equals(")")) found++; if (Parts[start].ToString().Equals("(")) found--; } Parts.Insert(start - 1, "("); Parts.Insert(start - 1, function); } } } } } catch { OutFile.WriteLine("ERROR: INCORRECT INPUT STRING"); //ERROR: INCORRECT INPUT STRING Form1.Step("ERROR: INCORRECT INPUT STRING"); return Tokenize(Base_String); } } } #endregion #region SHORTCUT REMOVER : for (int i = 0; i < Parts.Count; i++) { //SHORTCUT REMOVER 1 if (Parts[i].ToString().Contains(":")) { //PrintArrayList(Parts); char c = Convert.ToChar(Parts[i].ToString().Substring(0, 1)); int t1 = Convert.ToInt32(Parts[i].ToString().Split(':')[0].Substring(1)); int t2 = Convert.ToInt32(Parts[i].ToString().Split(':')[1].Substring(1)); Parts.RemoveAt(i); for (int j = t2; j >= t1; j--) { Parts.Insert(i, c + j.ToString()); if (j != t1) Parts.Insert(i, ","); } } } #endregion for (int i = 0; i < Parts.Count; i++) { //CELL REFERENCE if (Base_Cell.CompareTo(Parts[i].ToString().ToUpper()) == 0) { OutFile.WriteLine("ERROR: CIRCULAR REFERENCE"); Form1.Step("ERROR: CIRCULAR REFERENCE"); //ERROR: CIRCULAR REFERENCE return Parts; } if (IsCellReference(Parts[i].ToString())) { OutFile.WriteLine("Cell Reference"); Form1.Step("Cell Reference"); //Console.WriteLine("BaseCell= " + Base_Cell); //Console.WriteLine("CellReference= " + Parts[i].ToString()); string cell_ref = Parts[i].ToString().ToUpper(); Parts.RemoveAt(i); //string temp = "=1+2";//temp will equal the output of the UI's function string temp = Form1.getCellFormula(cell_ref); OutFile.WriteLine(cell_ref + " -> " + temp); Form1.Step(cell_ref + " -> " + temp); if (temp[0] == '=') { //Cell has a formula Parts.InsertRange(i, Reformat(Tokenize(temp))); OutFile.WriteLine("Cell has a formula"); Form1.Step("Cell has a formula"); } else { try { //Cell has a value Parts.Insert(i, Convert.ToDouble(temp)); OutFile.WriteLine("Cell has a number"); Form1.Step("Cell has a number"); } catch { OutFile.WriteLine("Cell has a string"); Form1.Step("Cell has a string"); //ERROR: Cell has a string return Parts; } } } } return Parts; }
public void GetRange_CountOverflow () { ArrayList al = new ArrayList (); al.Add (this); al.GetRange (0, Int32.MaxValue); }
public void GetRange_IndexOverflow () { ArrayList al = new ArrayList (); al.Add (this); al.GetRange (Int32.MaxValue, 0); }
public void TestGetRange () { { bool errorThrown = false; try { ArrayList a = new ArrayList (); ArrayList b = a.GetRange (-1, 1); } catch (ArgumentOutOfRangeException) { errorThrown = true; } Assert.IsTrue (errorThrown, "negative index error not thrown"); } { bool errorThrown = false; try { ArrayList a = new ArrayList (); ArrayList b = a.GetRange (1, -1); } catch (ArgumentOutOfRangeException) { errorThrown = true; } Assert.IsTrue (errorThrown, "negative index error not thrown"); } { bool errorThrown = false; try { ArrayList a = new ArrayList (); ArrayList b = a.GetRange (1, 1); } catch (ArgumentException) { errorThrown = true; } Assert.IsTrue (errorThrown, "out-of-range index error not thrown"); } { char [] chars = { 'a', 'b', 'c', 'd', 'e', 'f' }; ArrayList a = new ArrayList (chars); ArrayList b = a.GetRange (1, 3); Assert.AreEqual (3, b.Count, "GetRange returned wrong size ArrayList"); for (int i = 0; i < b.Count; i++) { Assert.AreEqual (chars [i + 1], b [i], "range didn't work"); } a [2] = '?'; // should screw up ArrayList b. bool errorThrown = false; try { int i = b.Count; } catch (InvalidOperationException) { errorThrown = true; } Assert.AreEqual (true, errorThrown, "Munging 'a' should mess up 'b'"); } { char [] chars = { 'a', 'b', 'c', 'd', 'e', 'f' }; ArrayList a = new ArrayList (chars); ArrayList b = a.GetRange (3, 3); object [] obj_chars = b.ToArray (); for (int i = 0; i < 3; i++) { char c = (char) obj_chars [i]; Assert.AreEqual (chars [i + 3], c, "range.ToArray didn't work"); } char [] new_chars = (char []) b.ToArray (typeof (char)); for (int i = 0; i < 3; i++) { Assert.AreEqual (chars [i + 3], new_chars [i], "range.ToArray with type didn't work"); } } }
public void TestArrayListWrappers() { //-------------------------------------------------------------------------- // Variable definitions. //-------------------------------------------------------------------------- ArrayList arrList = null; int start = 3; int count = 15; string[] strHeroes = { "Aquaman", "Atom", "Batman", "Black Canary", "Captain America", "Captain Atom", "Catwoman", "Cyborg", "Flash", "Green Arrow", "Green Lantern", "Hawkman", "Huntress", "Ironman", "Nightwing", "Robin", "SpiderMan", "Steel", "Superman", "Thor", "Wildcat", "Wonder Woman", }; string[] strResult = { "Aquaman", "Atom", "Batman", "Superman", "Thor", "Wildcat", "Wonder Woman", }; // // Construct array list. // // Construct ArrayList. arrList = new ArrayList((ICollection)strHeroes); //Adapter, GetRange, Synchronized, ReadOnly returns a slightly different version of //BinarySearch, Following variable cotains each one of these types of array lists ArrayList[] arrayListTypes = { (ArrayList)arrList.Clone(), (ArrayList)ArrayList.Adapter(arrList).Clone(), (ArrayList)arrList.GetRange(0, arrList.Count).Clone(), (ArrayList)ArrayList.Synchronized(arrList).Clone()}; foreach (ArrayList arrayListType in arrayListTypes) { arrList = arrayListType; // // [] Remove objects from the ArrayList. // for (int ii = 0; ii < count; ++ii) { arrList.RemoveAt(start); } // Verify the items in the array. for (int ii = 0; ii < strResult.Length; ++ii) { Assert.Equal(0, strResult[ii].CompareTo((string)arrList[ii])); } // // [] Attempt invalid remove using negative index // Assert.Throws<ArgumentOutOfRangeException>(() => arrList.RemoveAt(-100)); // // [] Attempt remove using out of range index // Assert.Throws<ArgumentOutOfRangeException>(() => arrList.RemoveAt(1000)); } }
private void PrivateTestGetRange(ArrayList arrayList) { ArrayList rangeList; arrayList.AddRange(c_TestData); rangeList = arrayList.GetRange(3, 5); Assert.IsTrue(rangeList.Count == 5, "rangeList.Count == 5"); this.VerifyContains(rangeList, new object[] {3,4,5,6,7}, "1: VerifyContains(rangeList)"); //FIXME: If items are removed from the Range, one may not iterate over it on .NET /* rangeList.Remove(7); this.VerifyContains(a2, new object[] {3,4,5,6}, "2: VerifyContains(rangeList)"); rangeList.RemoveAt(0); this.VerifyContains(a3, new object[] {4,5,6}, "3: VerifyContains(rangeList)"); rangeList.Add(7); rangeList.Add(6); rangeList.Add(3); rangeList.Add(11); Assert.IsTrue(rangeList.LastIndexOf(6) == 4, "rangeList.LastIndexOf(6) == 4"); rangeList.Sort(); this.VerifyContains(arrayList, new object[] {0, 1, 2, 3, 4, 5, 6, 6, 7, 11, 8, 9}, "4: VerifyContains(rangeList)"); */ }
private String getViewStateStringWithoutMAC() { int offset = 0; if (m_MACProtected) { offset = 20; } ArrayList tempList = new ArrayList(System.Convert.FromBase64String(m_viewStateBase64)); byte[] tempArray = new byte[tempList.Count - offset]; //the size of the MAC tempList.GetRange(0, tempList.Count - offset).CopyTo(tempArray); return System.Text.Encoding.UTF8.GetString(tempArray); }
protected override void computeMACInfo() { if (m_viewStateBase64 == "") { return; } // this whole set of steps is a little cludgly, but there doesn't seem to be a better way for now. We detect MAC info by // getting comparing the size of the original viewstate base64 decoded and the original viewstate decoded and then reencoded. If the two objects // don't match in size and the difference between before and after is 20 bytes we assume there is MAC protection. byte[] originalViewStateDeserialized = System.Convert.FromBase64String(m_viewStateBase64); int arrowCount = 0; int i = 0; for(i = 0; i < originalViewStateDeserialized.Length; i++) { if (originalViewStateDeserialized[i] == (byte)'<') arrowCount++; else if (originalViewStateDeserialized[i] == (byte)'>') arrowCount--; else continue; // if we find the closing ">" then we assume we are either at the end of the viewstate or their is trailing MAC info if (arrowCount == 0) { i++; // we bump the counter up to skip past the final ">" break; } } // if we have 20 bytes left we assume there is MAC protection if (originalViewStateDeserialized.Length - i == 20) { m_MACProtected = true; ArrayList tempList = new ArrayList(originalViewStateDeserialized); byte[] tempArray = new byte[20]; //the size of the MAC int MACIndex = originalViewStateDeserialized.Length - 20; // 20 is the size of the MAC tempList.GetRange(MACIndex, 20).CopyTo(tempArray); String hexString = BitConverter.ToString(tempArray); m_MAC = hexString.Replace("-", ""); } else { m_MACProtected = false; } }
private void GetNameList() { string strFile = m_rootPath + "Record.txt"; try { if (File.Exists(strFile)) { using (StreamReader sr = new StreamReader(strFile,Encoding.GetEncoding("gb2312"))) { ArrayList str_list = new ArrayList(); while (sr.Peek() >= 0) { string str = sr.ReadLine(); str_list.Add(str); } int count=str_list.Count; m_nameList = str_list.GetRange(3, count - 3); } } } catch (System.Exception ex) { MessageBox.Show(ex.Message); } }
private ResultSet ListFiles(ManagerEngine man, string cmd, Hashtable input) { ResultSet rs = new ResultSet(new string[] {"name","path","size","type","created","modified","attribs","custom"}); Hashtable customInfo; ArrayList files = new ArrayList(); BasicFileFilter filter; IFile listDir; ManagerConfig config = man.Config; bool onlyDirs, onlyFiles, remember, hasParent = false; string type, attribs, path, rootPath, configPrefixes, name, tmpPath; int pages, pageSize; HttpRequest req = HttpContext.Current.Request; HttpResponse resp = HttpContext.Current.Response; // Handle remember_last_path state if (input["remember_last_path"] != null) { // URL specified if (((string) input["path"]) == "{default}") { if (input["url"] != null && (string) input["url"] != "") input["path"] = man.ConvertURIToPath((string) input["url"]); } path = (string) input["path"]; if (input["remember_last_path"] is bool) remember = (bool) input["remember_last_path"]; else if (((string) input["remember_last_path"]) != "auto") remember = StringUtils.CheckBool((string) input["remember_last_path"]); else remember = config.GetBool("general.remember_last_path", false); // Get/set cookie if (remember) { if (path == "{default}" && req.Cookies["MCManager_" + man.Prefix + "_lastPath"] != null) { tmpPath = req.Cookies["MCManager_" + man.Prefix + "_lastPath"].Value; if (tmpPath != null && man.GetFSFromPath(tmpPath) == "file") input["path"] = tmpPath; } else { HttpCookie cookie = new HttpCookie("MCManager_" + man.Prefix + "_lastPath"); cookie.Expires = DateTime.Now.AddDays(30); cookie.Value = path; resp.Cookies.Remove("MCManager_" + man.Prefix + "_lastPath"); if (man.GetFSFromPath(path) == "file") resp.Cookies.Add(cookie); } } } path = man.DecryptPath((string) input["path"]); rootPath = man.DecryptPath((string) input["root_path"]); onlyDirs = input["only_dirs"] != null && (bool) input["only_dirs"]; onlyFiles = input["only_files"] != null && (bool) input["only_files"]; configPrefixes = (string) input["config"]; if (man.GetFSFromPath(path) == "file" && !man.VerifyPath(path)) path = man.Config.Get("filesystem.path"); // Move path into rootpath if (rootPath != null && !PathUtils.IsChildPath(rootPath, path) && man.GetFSFromPath(path) == "file") path = rootPath; listDir = man.GetFile(path); // Use default path instead if (!listDir.Exists) { path = config["filesystem.path"]; listDir = man.GetFile(path); } rs.Header["path"] = man.EncryptPath(path); rs.Header["visual_path"] = man.ToVisualPath(path, rootPath); rs.Header["attribs"] = (listDir.CanRead ? "R" : "-") + (listDir.CanWrite ? "W" : "-"); // List files if (listDir.IsDirectory) { config = listDir.Config; // Return part of the config if (configPrefixes != null) rs.Config = man.GetJSConfig(config, configPrefixes); // Verify filesystem config filter = new BasicFileFilter(); filter.IncludeDirectoryPattern = config["filesystem.include_directory_pattern"]; filter.ExcludeDirectoryPattern = config["filesystem.exclude_directory_pattern"]; filter.IncludeFilePattern = config["filesystem.include_file_pattern"]; filter.ExcludeFilePattern = config["filesystem.exclude_file_pattern"]; filter.IncludeExtensions = config["filesystem.extensions"]; filter.OnlyDirs = onlyDirs; // Directory is hidden use parent dir if (!filter.Accept(listDir)) { listDir = listDir.ParentFile; rs.Header["path"] = man.EncryptPath(listDir.AbsolutePath); rs.Header["visual_path"] = man.ToVisualPath(listDir.AbsolutePath, rootPath); } if (input["filter"] != null) filter.IncludeWildcardPattern = (string) input["filter"]; if (input["only_files"] != null) filter.OnlyFiles = onlyFiles; else if (!onlyDirs) filter.OnlyFiles = !config.GetBool("filesystem.list_directories", false); // Add parent if (path != rootPath && input["only_files"] == null && (input["only_dirs"] != null || man.Config.GetBool("filesystem.list_directories", true))) { if (man.VerifyPath(listDir.Parent)) { hasParent = true; rs.Add("..", man.EncryptPath(listDir.Parent), -1, "parent", "", "", "", new NameValueCollection()); } } // Setup input filter BasicFileFilter inputFilter = new BasicFileFilter(); if (input["include_directory_pattern"] != null) filter.IncludeDirectoryPattern = (string) input["include_directory_pattern"]; if (input["exclude_directory_pattern"] != null) filter.ExcludeDirectoryPattern = (string) input["exclude_directory_pattern"]; if (input["include_file_pattern"] != null) filter.IncludeFilePattern = (string) input["include_file_pattern"]; if (input["exclude_file_pattern"] != null) filter.ExcludeFilePattern = (string) input["exclude_file_pattern"]; if (input["extensions"] != null) filter.IncludeExtensions = (string) input["extensions"]; // Combine the filters CombinedFileFilter combinedFilter = new CombinedFileFilter(); combinedFilter.AddFilter(inputFilter); combinedFilter.AddFilter(filter); files.AddRange(listDir.ListFilesFiltered(combinedFilter)); if (input["page_size"] != null) { if (hasParent) pageSize = Convert.ToInt32(input["page_size"]) - 1; else pageSize = Convert.ToInt32(input["page_size"]); pages = (int) Math.Ceiling(files.Count / (double) pageSize); // Setup response rs.Header["pages"] = (pages > 1 ? pages : 1); rs.Header["count"] = files.Count; // Remove non visible files int start = Convert.ToInt32(input["page"]) * pageSize; int len = pageSize; len = start + len > files.Count ? len - ((start + len) - files.Count) : len; files = files.GetRange(start, len); } // Sort Files files.Sort(new FileComparer()); // Output folders foreach (IFile file in files) { if (file.IsDirectory) { // Setup attribs attribs = "RW"; type = "folder"; // Fill custom info customInfo = new Hashtable(); man.DispatchEvent(EventType.CustomInfo, file, "list", customInfo); // Special treatment of roots name = file.Name; if (path == "root:///") { if (man.RootNames[file.AbsolutePath] != null) name = man.RootNames[file.AbsolutePath]; } // Add to resultset rs.Add( name, man.EncryptPath(file.AbsolutePath), file.IsDirectory ? -1 : file.Length, type, StringUtils.GetDate(file.CreationDate, listDir.Config.Get("filesystem.datefmt", "yyyy-MM-dd HH:mm")), StringUtils.GetDate(file.LastModified, listDir.Config.Get("filesystem.datefmt", "yyyy-MM-dd HH:mm")), attribs, customInfo ); } } // Output files foreach (IFile file in files) { if (file.IsFile) { // Setup attribs attribs = "RW"; type = PathUtils.GetExtension(file.AbsolutePath).ToLower(); // Fill custom info customInfo = new Hashtable(); man.DispatchEvent(EventType.CustomInfo, file, "list", customInfo); // Add to resultset rs.Add( file.Name, man.EncryptPath(file.AbsolutePath), file.Length, type, StringUtils.GetDate(file.CreationDate, listDir.Config.Get("filesystem.datefmt", "yyyy-MM-dd HH:mm")), StringUtils.GetDate(file.LastModified, listDir.Config.Get("filesystem.datefmt", "yyyy-MM-dd HH:mm")), attribs, customInfo ); } } } else throw new ManagerException("{#error.file_not_exists}"); return rs; }
private int FinalizeUpdate(String filename, String passphrase) { try { core.InitializeKeys(passphrase); } catch { Console.Error.WriteLine("Invalid passphrase"); return 1; } StreamReader sr = new StreamReader(Path.Combine(core.ApplicationDataFolder, "identity")); String username = sr.ReadLine(); String email = sr.ReadLine(); sr.Close(); username.Trim(); email.Trim(); Connect(); ArrayList key = new ArrayList(File.ReadAllBytes(Path.Combine(core.ApplicationDataFolder, "answers.key"))); AESInfo info = new AESInfo(); info.key = (byte[]) key.GetRange(0, Crypto.AESKeySize/8).ToArray(Type.GetType("System.Byte")); info.IV = (byte[]) key.GetRange(Crypto.AESKeySize/8, Crypto.AESIVSize/8).ToArray(Type.GetType("System.Byte")); Rijndael aes = Rijndael.Create(); String e_macpass = File.ReadAllText(filename); e_macpass = Crypto.StripMessage(e_macpass); byte[] macpass = Crypto.AESDecrypt(Convert.FromBase64String(e_macpass), aes.CreateDecryptor(info.key, info.IV)); HMAC hmac = HMACSHA1.Create(); hmac.Key = macpass; byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(core.PublicKey)); if (server.USKeyUpdate_SendPublicKey(username, email, core.PublicKey, Convert.ToBase64String(hash))) { Console.WriteLine("Public key successfully sent."); } else { Console.WriteLine("Public key could not be sent, please try again."); } File.Delete(Path.Combine(core.ApplicationDataFolder, "answers.key")); return 0; }