/// <summary> /// /**A Helper converter that will take our "values" and convert them into a string array. /// String parsing IS requires for now until we make it smart. /// A string array is returned by with white spaces. /// flag = 0 means no null/white space, 1 means leave white space and null and we work with doubles /// </summary> /// <param name="values"></param> /// <param name="flag"></param> /// <returns></returns> private string[] ConvertToStringArray(System.Array values, int flag) { string[] newArray = new string[values.Length]; int index = 0; for (int i = values.GetLowerBound(0); i <= values.GetUpperBound(0); i++) { for (int j = values.GetLowerBound(1); j <= values.GetUpperBound(1); j++) { //This takes care of white space if ((values.GetValue(i, j) == null) || (values.GetValue(i, j).ToString().Trim().Length == 0)) { //Add an empty string so we can parse for last time later if (flag == 1) { newArray[index] = ""; index++; } } //this puts in the sting representation of what is in cell i, j // can be 1 of three types: a normal string, an integer, or a double. else { newArray[index] = (string)values.GetValue(i, j).ToString(); //Move to the next position in the new array. index++; } } } //Return an array with no null characters return(newArray = newArray.Where(n => n != null).ToArray()); }
public override void WriteToKernel(CallContext CallContext, int i) { // // Get count and size of individual array elements // long ElementCount = 1; for (int d = 0; d < m_Value.Rank; d++) { ElementCount *= (m_Value.GetUpperBound(d) - m_Value.GetLowerBound(d) + 1); } // // Allocate memory buffer on target hardware using the appropriate type // OpenCLNet.MemFlags MemFlags; if (m_ForRead && !m_ForWrite) { MemFlags = OpenCLNet.MemFlags.READ_ONLY; } else if (!m_ForRead && m_ForWrite) { MemFlags = OpenCLNet.MemFlags.WRITE_ONLY; } else { m_ForRead = m_ForWrite = true; MemFlags = OpenCLNet.MemFlags.READ_WRITE; } EnqueueWrite(CallContext, i, ElementCount, MemFlags); }
public static string CodeRepresentation(Array a) { StringBuilder ret = new StringBuilder(); ret.Append(a.GetType().FullName); ret.Append("("); switch (a.Rank) { case 1: { for (int i = 0; i < a.Length; i++) { if (i > 0) ret.Append(", "); ret.Append(Ops.StringRepr(a.GetValue(i + a.GetLowerBound(0)))); } } break; case 2: { int imax = a.GetLength(0); int jmax = a.GetLength(1); for (int i = 0; i < imax; i++) { ret.Append("\n"); for (int j = 0; j < jmax; j++) { if (j > 0) ret.Append(", "); ret.Append(Ops.StringRepr(a.GetValue(i + a.GetLowerBound(0), j + a.GetLowerBound(1)))); } } } break; default: ret.Append(" Multi-dimensional array "); break; } ret.Append(")"); return ret.ToString(); }
/// <summary> /// Converting the data values retrieved from the rangecells to string values. /// </summary> /// <param name="data"></param> /// <returns></returns> private string[][] ToStringArray(System.Array data) { try { string[][] sArray = new string[data.GetUpperBound(0)][]; for (int i = data.GetLowerBound(0); i <= data.GetUpperBound(0); ++i) { sArray[i - 1] = new string[data.GetUpperBound(1)]; for (int j = data.GetLowerBound(1); j <= data.GetUpperBound(1); ++j) { if (data.GetValue(i, j) == null) { sArray[i - 1][j - 1] = "-----"; } else { sArray[i - 1][j - 1] = data.GetValue(i, j).ToString(); } } } return(sArray); } catch { throw (new Exception("Exception: Conversion to string array")); } }
// The test guarantees that `a` is a 2-D array. Verifies that the intrinsics don't kick in. static void test3(System.Array a) { Console.WriteLine(a.Rank); Console.WriteLine(a.GetLength(0)); Console.WriteLine(a.GetLength(1)); Console.WriteLine(a.GetLowerBound(0)); Console.WriteLine(a.GetUpperBound(0)); Console.WriteLine(a.GetLowerBound(1)); Console.WriteLine(a.GetUpperBound(1)); }
static int test9(System.Array a) { int sum = 0; for (int i = a.GetLowerBound(0); i <= a.GetUpperBound(0); i++) { for (int j = a.GetLowerBound(1); j <= a.GetUpperBound(1); j++) { sum += (int)a.GetValue(i, j); } } return(sum); }
//-------------------------------------------------------------------// /// <summary> /// Converts COM like 2dim array where one dimension is of length 1 to regular array. /// </summary> /// <param name="a">COM array</param> /// <returns>regular array</returns> public static object[] Com2DArray2Array(Array a) { if (a == null) return null; object[] converted = null; switch (a.Rank) { case 1: converted = new object[a.GetLength(0)]; for (var i = a.GetLowerBound(0); i <= a.GetUpperBound(0); i++) { converted[i] = a.GetValue(i); } break; case 2: { var d1 = a.GetLength(0); var d2 = a.GetLength(1); var len = (d1 > d2) ? d1 : d2; converted = new object[len]; var dim = (d1 > d2) ? 0 : 1; for (var i = a.GetLowerBound(dim); i <= a.GetUpperBound(dim); i++) { converted[i - a.GetLowerBound(dim)] = a.GetValue((d1 == 1 ? a.GetLowerBound(0) : i), (d2 == 1 ? a.GetLowerBound(1) : i)); } } break; } return converted; }
public static string ArrayToDescriptor(Array array, TypeRegistry treg, Type type = null, string th = null) { if (type==null) type = array.GetType(); if (array.LongLength>MAX_ELM_COUNT) throw new SlimSerializationException(StringConsts.SLIM_ARRAYS_OVER_MAX_ELM_ERROR.Args(array.LongLength, MAX_ELM_COUNT)); if (type==typeof(object[]))//special case for object[], because this type is very often used in Glue and other places return "$1|"+array.Length.ToString(); if (th==null) th = treg.GetTypeHandle(type); var ar = array.Rank; if (ar>MAX_DIM_COUNT) throw new SlimSerializationException(StringConsts.SLIM_ARRAYS_OVER_MAX_DIMS_ERROR.Args(ar, MAX_DIM_COUNT)); var descr = new StringBuilder(th); descr.Append('|');//separator char for(int i=0; i<ar; i++) { descr.Append(array.GetLowerBound(i)); descr.Append('~'); descr.Append(array.GetUpperBound(i)); if (i<ar-1) descr.Append(','); } return descr.ToString(); }
public void CopyTo(Array array, int index) { if (this.isDisposed) { throw new ObjectDisposedException(name); } if (array == null) { throw new ArgumentNullException("array"); } if ((index < array.GetLowerBound(0)) || (index > array.GetUpperBound(0))) { throw new ArgumentOutOfRangeException("index"); } int num = array.Length - index; int num2 = 0; ArrayList list = new ArrayList(); ManagementObjectEnumerator enumerator = this.GetEnumerator(); while (enumerator.MoveNext()) { ManagementBaseObject current = enumerator.Current; list.Add(current); num2++; if (num2 > num) { throw new ArgumentException(null, "index"); } } list.CopyTo(array, index); }
public static string ArrayToDescriptor(Array array, Type type, VarIntStr typeHandle) { if (array.LongLength>MAX_ELM_COUNT) throw new SlimSerializationException(StringConsts.SLIM_ARRAYS_OVER_MAX_ELM_ERROR.Args(array.LongLength, MAX_ELM_COUNT)); if (type==typeof(object[]))//special case for object[], because this type is very often used in Glue and other places return "$2|"+array.Length.ToString(); var th = typeHandle.StringValue ?? ( typeHandle.IntValue < TypeRegistry.STR_HNDL_POOL.Length ? TypeRegistry.STR_HNDL_POOL[typeHandle.IntValue] : '$'+typeHandle.IntValue.ToString() ); var ar = array.Rank; if (ar>MAX_DIM_COUNT) throw new SlimSerializationException(StringConsts.SLIM_ARRAYS_OVER_MAX_DIMS_ERROR.Args(ar, MAX_DIM_COUNT)); var descr = new StringBuilder(); descr.Append( th ); descr.Append('|');//separator char for(int i=0; i<ar; i++) { descr.Append(array.GetLowerBound(i)); descr.Append('~'); descr.Append(array.GetUpperBound(i)); if (i<ar-1) descr.Append(','); } return descr.ToString(); }
/// <summary> /// Modifies the specified array by applying the specified function to each element. /// </summary> /// <param name="a"></param> /// <param name="func">object delegate(object o){}</param> /// <returns></returns> public static void ForEach(Array a, ForEachFunction func) { long[] ix = new long[a.Rank]; //Init index for (int i = 0; i < ix.Length; i++) ix[i] = a.GetLowerBound(i); //Loop through all items for (long i = 0; i < a.LongLength; i++) { a.SetValue(func(a.GetValue(ix)), ix); //Increment ix, the index for (int j = 0; j < ix.Length; j++) { if (ix[j] < a.GetUpperBound(j)) { ix[j]++; break; //We're done incrementing. } else { //Ok, reset this one and increment the next. ix[j] = a.GetLowerBound(j); //If this is the last dimension, assert //that we are at the last element if (j == ix.Length - 1) { if (i < a.LongLength - 1) throw new Exception(); } continue; } } } return; }
/// <summary> /// Asserts that each element in the first array is equal to its corresponding element in the second array. /// </summary> public static void AssertAllArrayElementsAreEqual(Array first, Array second, IComparer comparer = null) { Assert.True(first.Length == second.Length, "The two arrays are not even the same size."); for (int g = first.GetLowerBound(0); g < first.GetUpperBound(0); g++) { AssertArrayElementsAreEqual(first, second, g, comparer); } }
private static void ArrayRankInfo(String name, Array a) { Console.WriteLine("Number of dimensions in \"{0}\" array (of type {1}): ", name, a.GetType().ToString(), a.Rank); for (int r = 0; r < a.Rank; r++) { Console.WriteLine("Rank: {0}, LowerBound = {1}, UpperBound = {2}", r, a.GetLowerBound(r), a.GetUpperBound(r)); } Console.WriteLine(); }
/// <summary> /// The following implementation is based on /// stackoverflow.com/questions/9914230/iterate-through-an-array-of-arbitrary-dimension/9914326#9914326 /// </summary> /// <param name="array"></param> /// <returns></returns> public int[] determineFirstIndicesArray(Array array) { int spaceDimension = array.Rank; int[] firstIndicesArray = new int[spaceDimension]; for (int dimIdx = 0; dimIdx < spaceDimension; dimIdx++) { firstIndicesArray[dimIdx] = array.GetLowerBound(dimIdx); } return firstIndicesArray; }
public static void ClearInternal(object thisNull, System.Array array, int index, int length) { index += array.GetLowerBound(0); object defaultValue = Activator.CreateInstance(array.GetType().GetElementType()); for (var ind = index; ind < length; ind++) { array.SetValue(defaultValue, ind); } }
// General case: non-constant arguments to GetLength()/GetLowerBound()/GetUpperBound() static void test4(System.Array a) { int rank = a.Rank; Console.WriteLine(rank); for (int i = 0; i < rank; i++) { Console.WriteLine(a.GetLength(i)); Console.WriteLine(a.GetLowerBound(i)); Console.WriteLine(a.GetUpperBound(i)); } }
ConvertToStringArray(System.Array values) { string[] newArray = new string[values.Length]; int index = 0; for (int i = values.GetLowerBound(0); i < values.GetUpperBound(0); i++) { for (int j = values.GetLowerBound(1); j < values.GetUpperBound(1); j++) { if (values.GetValue(i, j) == null) { newArray[index] = ""; } else { newArray[index] = values.GetValue(i, j).ToString(); } index++; } } return(newArray); }
/// <summary> /// Инициализирующий конструктор. /// </summary> /// <param name="arr">Массив, индексы которого перебираются.</param> public ArrayIndexEnumerator(Array arr) { rank = arr.Rank; az = new int[rank, 2]; index = new int[rank]; for(int a = 0; a < rank; a++) { az[a, 0] = arr.GetLowerBound(a); index[a] = az[a, 0]; az[a, 1] = arr.GetUpperBound(a); } index[rank-1]--; }
/// <summary> /// The following implementation is based on /// stackoverflow.com/questions/9914230/iterate-through-an-array-of-arbitrary-dimension/9914326#9914326 /// </summary> /// <param name="array"></param> /// <param name="previousIndicesArray"></param> /// <returns></returns> public int[] determineNextIndicesArray(Array array, int[] previousIndicesArray) { int spaceDimension = array.Rank; int[] nextIndicesArray = new int[spaceDimension]; previousIndicesArray.CopyTo(nextIndicesArray, 0); for (int dimIdx = spaceDimension - 1; dimIdx >= 0; --dimIdx) { nextIndicesArray[dimIdx]++; if (nextIndicesArray[dimIdx] <= array.GetUpperBound(dimIdx)) return nextIndicesArray; nextIndicesArray[dimIdx] = array.GetLowerBound(dimIdx); } return null; }
/// <summary> /// Convert a list into a human-readable string representation. The /// representation used is: (0 to 2) {1, 2, 3} /// </summary> /// <param name="data">The array to process</param> /// <returns>A string containing the array data.</returns> public static string ASCIIfy(Array data) { if ( data == null ) return "()"; StringBuilder sb = new StringBuilder("("); sb.Append( String.Format( ResStrings.GetString( "ArrayLimits" ), data.GetLowerBound( 0 ), data.GetUpperBound( 0 ) ) ); sb.Append( ASCIIfy((IList)data) ); sb.Append( ")" ); return sb.ToString(); }
static public int GetLowerBound(IntPtr l) { try { System.Array self = (System.Array)checkSelf(l); System.Int32 a1; checkType(l, 2, out a1); var ret = self.GetLowerBound(a1); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
static int GetLowerBound(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); System.Array obj = (System.Array)ToLua.CheckObject(L, 1, typeof(System.Array)); int arg0 = (int)LuaDLL.luaL_checknumber(L, 2); int o = obj.GetLowerBound(arg0); LuaDLL.lua_pushinteger(L, o); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
private static void SetupLoopData(Array arr, out int rank, out int[] dimensions, out int[] lowerBounds, out int[] upperBounds) { rank = arr.Rank; dimensions = new int[rank]; lowerBounds = new int[rank]; upperBounds = new int[rank]; for (int dimension = 0; dimension < rank; dimension++) { lowerBounds[dimension] = arr.GetLowerBound(dimension); upperBounds[dimension] = arr.GetUpperBound(dimension); //setup start values dimensions[dimension] = lowerBounds[dimension]; } }
public void CopyTo(Array array, int index) { IWbemQualifierSetFreeThreaded typeQualifierSet; if (array == null) { throw new ArgumentNullException("array"); } if ((index < array.GetLowerBound(0)) || (index > array.GetUpperBound(0))) { throw new ArgumentOutOfRangeException("index"); } string[] pNames = null; try { typeQualifierSet = this.GetTypeQualifierSet(); } catch (ManagementException exception) { if ((this.qualifierSetType != QualifierType.PropertyQualifier) || (exception.ErrorCode != ManagementStatus.SystemProperty)) { throw; } return; } int errorCode = typeQualifierSet.GetNames_(0, out pNames); if (errorCode < 0) { if ((errorCode & 0xfffff000L) == 0x80041000L) { ManagementException.ThrowWithExtendedInfo((ManagementStatus) errorCode); } else { Marshal.ThrowExceptionForHR(errorCode); } } if ((index + pNames.Length) > array.Length) { throw new ArgumentException(null, "index"); } foreach (string str in pNames) { array.SetValue(new QualifierData(this.parent, this.propertyOrMethodName, str, this.qualifierSetType), index++); } }
private static int[] GetMultidimensionalIndices(System.Array a, int idx) { var indices = new int[a.Rank]; for (var i = 0; i < a.Rank; i++) { var div = 1; for (var j = i + 1; j < a.Rank; j++) { div *= a.GetLength(j); } indices[i] = a.GetLowerBound(i) + idx / div % a.GetLength(i); } return(indices); }
/// <summary> /// This method return how many entries we need to copy over /// We start from the bottom of the excel sheet and look for the first null, or when date != the date in cell /// </summary> /// <param name="ExSheet"></param> /// <param name="date"></param> /// <returns></returns> private int numberOfRows(Excel.Worksheet ExSheet, string date) { Excel.Range last = ExSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing); int lastRow = ExSheet.UsedRange.Rows.Count; Excel.Range range = ExSheet.get_Range("B2", "B" + lastRow); int numberOfRows = 0; if (range.Rows.Count != 1) { //Export to array System.Array array = (System.Array)range.Cells.Value2; for (int i = array.GetUpperBound(0); i >= array.GetLowerBound(0); i--) { //This finds all number of columns that happen today. if ((array.GetValue(i, 1) != null) && (array.GetValue(i, 1) is double) && (DateTime.FromOADate(double.Parse((string)array.GetValue(i, 1).ToString().Trim())).ToString("M/dd/yy").Equals(date))) { numberOfRows++; } } } else { //We just have one element in the array so we check if its in the time period. if ((range.Value2 != null) && (range.Value2 is double) && (DateTime.FromOADate(double.Parse((string)range.Value2.ToString().Trim())).ToString("M/dd/yy").Equals(date))) { numberOfRows++; } } last = null; range = null; return(numberOfRows); }
private static bool TryGetRankDiff(Array x, Array y, out RankDiff rankDiff) { if (x.Length != y.Length || x.Rank != y.Rank) { rankDiff = new RankDiff(x, y); return true; } for (var i = 0; i < x.Rank; i++) { if (x.GetLowerBound(i) != y.GetLowerBound(i) || x.GetUpperBound(i) != y.GetUpperBound(i)) { rankDiff = new RankDiff(x, y); return true; } } rankDiff = null; return false; }
internal void CopyTo(Array array, int arrayIndex) { if (array == null) throw new ArgumentNullException("array"); // ICollection expects the destination array to be single-dimensional. if (array.Rank != 1) throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported")); int destLB = array.GetLowerBound(0); int srcLen = Count(); int destLen = array.GetLength(0); if (arrayIndex < destLB) throw new ArgumentOutOfRangeException("arrayIndex"); // Does the dimension in question have sufficient space to copy the expected number of entries? // We perform this check before valid index check to ensure the exception message is in sync with // the following snippet that uses regular framework code: // // ArrayList list = new ArrayList(); // list.Add(1); // Array items = Array.CreateInstance(typeof(object), new int[] { 1 }, new int[] { -1 }); // list.CopyTo(items, 0); if(srcLen > (destLen - (arrayIndex - destLB))) throw new ArgumentException(Environment.GetResourceString("Argument_InsufficientSpaceToCopyCollection")); if(arrayIndex - destLB > destLen) throw new ArgumentException(Environment.GetResourceString("Argument_IndexOutOfArrayBounds")); // We need to verify the index as we; IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this); for (uint i = 0; i < srcLen; i++) { array.SetValue(_this.GetAt(i), i + arrayIndex); } }
public static void Clear(object thisNull, System.Array array, int index, int length) { if (array == null) { throw new ArgumentNullException(nameof(array), "Array cannot be null"); } if (length < 0) { throw new IndexOutOfRangeException(); } int lowerBound = array.GetLowerBound(0); if (index < lowerBound) { throw new IndexOutOfRangeException(); } index -= lowerBound; if (index > array.Length - length) { throw new IndexOutOfRangeException(); } ClearInternal(thisNull, array, index, length); }
// Sorts the elements in a section of two arrays based on the keys in the // first array. Elements in the keys array specify the sort keys for // corresponding elements in the items array. The sort compares the // keys to each other using the given IComparer interface. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented // by all elements of the given section of the keys array. // /// <include file='doc\Array.uex' path='docs/doc[@for="Array.Sort7"]/*' /> public static void Sort(Array keys, Array items, int index, int length, IComparer comparer) { if (keys==null) throw new ArgumentNullException("keys"); if (keys.Rank != 1 || (items != null && items.Rank != 1)) throw new RankException(Environment.GetResourceString("Rank_MultiDimNotSupported")); if (items != null && keys.GetLowerBound(0) != items.GetLowerBound(0)) throw new ArgumentException(Environment.GetResourceString("Arg_LowerBoundsMustMatch")); if (index < keys.GetLowerBound(0) || length < 0) throw new ArgumentOutOfRangeException((length<0 ? "length" : "index"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (keys.Length - (index+keys.GetLowerBound(0)) < length || (items != null && index > items.Length - length)) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); if (length > 1) { if (comparer == Comparer.Default || comparer == null) { int r = TrySZSort(keys, items, index, index + length - 1); if (r != 0) return; } Object[] objKeys = keys as Object[]; Object[] objItems = null; if (objKeys != null) objItems = items as Object[]; if (objKeys != null && (items==null || objItems != null)) { SorterObjectArray sorter = new SorterObjectArray(objKeys, objItems, comparer); sorter.QuickSort(index, index + length - 1); } else { SorterGenericArray sorter = new SorterGenericArray(keys, items, comparer); sorter.QuickSort(index, index + length - 1); } } }
// Sorts the elements of two arrays based on the keys in the first array. // Elements in the keys array specify the sort keys for // corresponding elements in the items array. The sort compares the // keys to each other using the given IComparer interface. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented // by all elements of the keys array. // /// <include file='doc\Array.uex' path='docs/doc[@for="Array.Sort5"]/*' /> public static void Sort(Array keys, Array items, IComparer comparer) { if (keys==null) throw new ArgumentNullException("keys"); Sort(keys, items, keys.GetLowerBound(0), keys.Length, comparer); }
// Sorts the elements of an array. The sort compares the elements to each // other using the given IComparer interface. If comparer is // null, the elements are compared to each other using the // IComparable interface, which in that case must be implemented by // all elements of the array. // /// <include file='doc\Array.uex' path='docs/doc[@for="Array.Sort4"]/*' /> public static void Sort(Array array, IComparer comparer) { if (array==null) throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Array")); Sort(array, null, array.GetLowerBound(0), array.Length, comparer); }
// Reverses the elements in a range of an array. Following a call to this // method, an element in the range given by index and count // which was previously located at index i will now be located at // index index + (index + count - i - 1). // /// <include file='doc\Array.uex' path='docs/doc[@for="Array.Reverse1"]/*' /> public static void Reverse(Array array, int index, int length) { if (array==null) throw new ArgumentNullException("array"); if (index < array.GetLowerBound(0) || length < 0) throw new ArgumentOutOfRangeException((index<0 ? "index" : "length"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (array.Length - (index - array.GetLowerBound(0)) < length) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); if (array.Rank != 1) throw new RankException(Environment.GetResourceString("Rank_MultiDimNotSupported")); bool r = TrySZReverse(array, index, length); if (r) return; int i = index; int j = index + length - 1; Object[] objArray = array as Object[]; if (objArray!=null) { while (i < j) { Object temp = objArray[i]; objArray[i] = objArray[j]; objArray[j] = temp; i++; j--; } } else { while (i < j) { Object temp = array.GetValue(i); array.SetValue(array.GetValue(j), i); array.SetValue(temp, j); i++; j--; } } }
public void OnCmd(ref EdmCmd poCmd, ref System.Array ppoData) { //Handle the hook string name = null; switch (poCmd.meCmdType) { case EdmCmdType.EdmCmd_PreState: name = "PreState"; break; case EdmCmdType.EdmCmd_PostAdd: name = "PostAdd"; break; case EdmCmdType.EdmCmd_PostLock: name = "PostLock"; break; case EdmCmdType.EdmCmd_PreUnlock: name = "PreUnlock"; break; case EdmCmdType.EdmCmd_PostUnlock: name = "PostUnlock"; break; default: name = "?"; break; } string message = null; message = "sasasa"; int index = 0; // index = Information.LBound(ppoData); index = ppoData.GetLowerBound(0); int last = 0; //last = Information.UBound(ppoData); last = ppoData.GetUpperBound(0); //Append the paths of all files to a message string while (index <= last) { message = message + ((EdmCmdData)(ppoData.GetValue(index))).mbsStrData1 + Environment.NewLine;//Constants.vbLf; index = index + 1; } //Display a message to the user message = "The following files were affected by a " + name + " hook:" + Environment.NewLine /*Constants.vbLf */ + message; EdmVault5 vault = default(EdmVault5); vault = (EdmVault5)poCmd.mpoVault; vault.MsgBox(poCmd.mlParentWnd, message); if (poCmd.meCmdType == EdmCmdType.EdmCmd_Menu) { if (poCmd.mlCmdID == 1) { System.Windows.Forms.MessageBox.Show("C# Add-in"); } } }
public static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) { if (sourceArray == null) { throw new ArgumentNullException(nameof(sourceArray)); } if (destinationArray == null) { throw new ArgumentNullException(nameof(destinationArray)); } if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length), "Value has to be >= 0."); } if (sourceArray.Rank != destinationArray.Rank) { throw new RankException(SR.Rank_MultiDimNotSupported); } if (sourceIndex < 0) { throw new ArgumentOutOfRangeException(nameof(sourceIndex), "Value has to be >= 0."); } if (destinationIndex < 0) { throw new ArgumentOutOfRangeException(nameof(destinationIndex), "Value has to be >= 0."); } if (FastCopy(sourceArray, sourceIndex, destinationArray, destinationIndex, length)) { return; } int source_pos = sourceIndex - sourceArray.GetLowerBound(0); int dest_pos = destinationIndex - destinationArray.GetLowerBound(0); if (dest_pos < 0) { throw new ArgumentOutOfRangeException(nameof(destinationIndex), "Index was less than the array's lower bound in the first dimension."); } // re-ordered to avoid possible integer overflow if (source_pos > sourceArray.Length - length) { throw new ArgumentException(SR.Arg_LongerThanSrcArray, nameof(sourceArray)); } if (dest_pos > destinationArray.Length - length) { throw new ArgumentException("Destination array was not long enough. Check destIndex and length, and the array's lower bounds", nameof(destinationArray)); } Type src_type = sourceArray.GetType().GetElementType(); Type dst_type = destinationArray.GetType().GetElementType(); var dst_type_vt = dst_type.IsValueType; // Need to check types even if nothing is copied if (length == 0) { var src_etype = RuntimeTypeHandle.GetCorElementType((RuntimeType)src_type); var dst_etype = RuntimeTypeHandle.GetCorElementType((RuntimeType)dst_type); // FIXME: More checks bool match = true; switch (dst_etype) { case CorElementType.ELEMENT_TYPE_OBJECT: case CorElementType.ELEMENT_TYPE_STRING: case CorElementType.ELEMENT_TYPE_CLASS: case CorElementType.ELEMENT_TYPE_ARRAY: case CorElementType.ELEMENT_TYPE_SZARRAY: if (src_type.IsPointer) { match = false; } break; case CorElementType.ELEMENT_TYPE_PTR: switch (src_etype) { case CorElementType.ELEMENT_TYPE_OBJECT: case CorElementType.ELEMENT_TYPE_STRING: case CorElementType.ELEMENT_TYPE_CLASS: case CorElementType.ELEMENT_TYPE_ARRAY: case CorElementType.ELEMENT_TYPE_SZARRAY: match = false; break; default: break; } break; default: break; } if (!match) { throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType); } } if (!Object.ReferenceEquals(sourceArray, destinationArray) || source_pos > dest_pos) { for (int i = 0; i < length; i++) { Object srcval = sourceArray.GetValueImpl(source_pos + i); if (srcval == null && dst_type_vt) { throw new InvalidCastException(); } try { destinationArray.SetValueImpl(srcval, dest_pos + i); } catch (ArgumentException) { throw CreateArrayTypeMismatchException(); } catch (InvalidCastException) { if (CanAssignArrayElement(src_type, dst_type)) { throw; } throw CreateArrayTypeMismatchException(); } } } else { for (int i = length - 1; i >= 0; i--) { Object srcval = sourceArray.GetValueImpl(source_pos + i); try { destinationArray.SetValueImpl(srcval, dest_pos + i); } catch (ArgumentException) { throw CreateArrayTypeMismatchException(); } catch { if (CanAssignArrayElement(src_type, dst_type)) { throw; } throw CreateArrayTypeMismatchException(); } } } }
private void FormatMultidimensionalArray(Builder result, Array array, bool inline) { Debug.Assert(array.Rank > 1); if (array.Length == 0) { result.AppendCollectionItemSeparator(isFirst: true, inline: true); result.AppendGroupOpening(); result.AppendGroupClosing(inline: true); return; } int[] indices = new int[array.Rank]; for (int i = array.Rank - 1; i >= 0; i--) { indices[i] = array.GetLowerBound(i); } int nesting = 0; int flatIndex = 0; while (true) { // increment indices (lower index overflows to higher): int i = indices.Length - 1; while (indices[i] > array.GetUpperBound(i)) { indices[i] = array.GetLowerBound(i); result.AppendGroupClosing(inline: inline || nesting != 1); nesting--; i--; if (i < 0) { return; } indices[i]++; } result.AppendCollectionItemSeparator(isFirst: flatIndex == 0, inline: inline || nesting != 1); i = indices.Length - 1; while (i >= 0 && indices[i] == array.GetLowerBound(i)) { result.AppendGroupOpening(); nesting++; // array isn't empty, so there is always an element following this separator result.AppendCollectionItemSeparator(isFirst: true, inline: inline || nesting != 1); i--; } string name; FormatObjectRecursive(result, array.GetValue(indices), quoteStrings: true, memberFormat: MemberDisplayFormat.InlineValue, name: out name); indices[indices.Length - 1]++; flatIndex++; } }
private static void WriteArray(MemoryStream stream, Array a, Hashtable ht, ref int hv, Encoding encoding) { if (a.Rank == 1) { int len = a.GetLength(0); byte[] alen = Encoding.ASCII.GetBytes(len.ToString()); int lb = a.GetLowerBound(0); int ub = a.GetUpperBound(0); stream.WriteByte(__a); stream.WriteByte(__Colon); stream.Write(alen, 0, alen.Length); stream.WriteByte(__Colon); stream.WriteByte(__LeftB); for (int i = lb; i <= ub; i++) { WriteInteger(stream, Encoding.ASCII.GetBytes(i.ToString())); Serialize(stream, a.GetValue(i), ht, ref hv, encoding); } stream.WriteByte(__RightB); } else { WriteArray(stream, a, new int[] { 0 }, ht, ref hv, encoding); } }
private bool LoadArray(ref System.Array AnArray, short CanonDT, ref string wrTxt) { int ii; int loc; int Wlen; int start; try { start = 1; Wlen = wrTxt.Length; for (ii = AnArray.GetLowerBound(0); (ii <= AnArray.GetUpperBound(0)); ii++) { loc = (wrTxt.IndexOf(",", (start - 1)) + 1); if ((ii < AnArray.GetUpperBound(0))) { if ((loc == 0)) { MessageBox.Show("Write Value: Incorrect Number of Items for Array Size?", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(false); } } else { loc = (Wlen + 1); } switch ((CanonicalDataTypes)CanonDT) { case CanonicalDataTypes.CanonDtByte: AnArray.SetValue(Convert.ToByte(wrTxt.Substring((start - 1), (loc - start))), ii); // End case break; case CanonicalDataTypes.CanonDtChar: AnArray.SetValue(Convert.ToSByte(wrTxt.Substring((start - 1), (loc - start))), ii); // End case break; case CanonicalDataTypes.CanonDtWord: AnArray.SetValue(Convert.ToUInt16(wrTxt.Substring((start - 1), (loc - start))), ii); // End case break; case CanonicalDataTypes.CanonDtShort: AnArray.SetValue(Convert.ToInt16(wrTxt.Substring((start - 1), (loc - start))), ii); // End case break; case CanonicalDataTypes.CanonDtDWord: AnArray.SetValue(Convert.ToUInt32(wrTxt.Substring((start - 1), (loc - start))), ii); // End case break; case CanonicalDataTypes.CanonDtLong: AnArray.SetValue(Convert.ToInt32(wrTxt.Substring((start - 1), (loc - start))), ii); // End case break; case CanonicalDataTypes.CanonDtFloat: AnArray.SetValue(Convert.ToSingle(wrTxt.Substring((start - 1), (loc - start))), ii); // End case break; case CanonicalDataTypes.CanonDtDouble: AnArray.SetValue(Convert.ToDouble(wrTxt.Substring((start - 1), (loc - start))), ii); // End case break; case CanonicalDataTypes.CanonDtBool: AnArray.SetValue(Convert.ToBoolean(wrTxt.Substring((start - 1), (loc - start))), ii); // End case break; case CanonicalDataTypes.CanonDtString: AnArray.SetValue(Convert.ToString(wrTxt.Substring((start - 1), (loc - start))), ii); // End case break; default: MessageBox.Show("Write Value Unknown data type", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(false); break; } start = (loc + 1); } return(true); } catch (Exception ex) { MessageBox.Show(("Write Value generated Exception: " + ex.Message), "SimpleOPCInterface Exception", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(false); } }
///<summary> /// 检测索引是否在数组的范围之内 ///</summary> ///<param name = "source">源数组</param> ///<param name = "index">检查的索引</param> ///<param name="dimension">检查的维度</param> ///<returns><c>true</c> 表示有效,<c>false</c> 表示索引超过范围</returns> public static bool WithinIndex(this Array source, int index, int dimension) { return(source != null && index >= source.GetLowerBound(dimension) && index <= source.GetUpperBound(dimension)); }
public static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) { if (sourceArray == null) { throw new ArgumentNullException("sourceArray"); } if (destinationArray == null) { throw new ArgumentNullException("destinationArray"); } if (length < 0) { throw new ArgumentOutOfRangeException("length", Locale.GetText( "Value has to be >= 0.")); } ; if (sourceArray.Rank != destinationArray.Rank) { throw new RankException(SR.Rank_MultiDimNotSupported); } if (sourceIndex < 0) { throw new ArgumentOutOfRangeException("sourceIndex", Locale.GetText( "Value has to be >= 0.")); } ; if (destinationIndex < 0) { throw new ArgumentOutOfRangeException("destinationIndex", Locale.GetText( "Value has to be >= 0.")); } ; if (FastCopy(sourceArray, sourceIndex, destinationArray, destinationIndex, length)) { return; } int source_pos = sourceIndex - sourceArray.GetLowerBound(0); int dest_pos = destinationIndex - destinationArray.GetLowerBound(0); if (dest_pos < 0) { throw new ArgumentOutOfRangeException("destinationIndex", "Index was less than the array's lower bound in the first dimension."); } // re-ordered to avoid possible integer overflow if (source_pos > sourceArray.Length - length) { throw new ArgumentException("length"); } if (dest_pos > destinationArray.Length - length) { string msg = "Destination array was not long enough. Check " + "destIndex and length, and the array's lower bounds"; throw new ArgumentException(msg, string.Empty); } Type src_type = sourceArray.GetType().GetElementType(); Type dst_type = destinationArray.GetType().GetElementType(); if (!Object.ReferenceEquals(sourceArray, destinationArray) || source_pos > dest_pos) { for (int i = 0; i < length; i++) { Object srcval = sourceArray.GetValueImpl(source_pos + i); try { destinationArray.SetValueImpl(srcval, dest_pos + i); } catch (ArgumentException) { throw CreateArrayTypeMismatchException(); } catch { if (CanAssignArrayElement(src_type, dst_type)) { throw; } throw CreateArrayTypeMismatchException(); } } } else { for (int i = length - 1; i >= 0; i--) { Object srcval = sourceArray.GetValueImpl(source_pos + i); try { destinationArray.SetValueImpl(srcval, dest_pos + i); } catch (ArgumentException) { throw CreateArrayTypeMismatchException(); } catch { if (CanAssignArrayElement(src_type, dst_type)) { throw; } throw CreateArrayTypeMismatchException(); } } } }
public static bool LoadArray(ref System.Array AnArray, int CanonDT, string wrTxt) { int ii = 0; int loc = 0; int Wlen = 0; int start = 0; try { start = 1; Wlen = wrTxt.Length; for (ii = AnArray.GetLowerBound(0); ii <= AnArray.GetUpperBound(0); ii++) { loc = wrTxt.IndexOf(",", 0); if (ii < AnArray.GetUpperBound(0)) { if (loc == 0) { return(false); } } else { loc = Wlen + 1; } switch (CanonDT) { case (int)CanonicalDataTypes.CanonDtByte: AnArray.SetValue(Convert.ToByte((wrTxt.Substring(start, loc - start))), ii); break; case (int)CanonicalDataTypes.CanonDtChar: AnArray.SetValue(Convert.ToSByte((wrTxt.Substring(start, loc - start))), ii); break; case (int)CanonicalDataTypes.CanonDtWord: AnArray.SetValue(Convert.ToUInt16((wrTxt.Substring(start, loc - start))), ii); break; case (int)CanonicalDataTypes.CanonDtShort: AnArray.SetValue(Convert.ToInt16((wrTxt.Substring(start, loc - start))), ii); break; case (int)CanonicalDataTypes.CanonDtDWord: AnArray.SetValue(Convert.ToInt32((wrTxt.Substring(start, loc - start))), ii); break; case (int)CanonicalDataTypes.CanonDtLong: AnArray.SetValue(Convert.ToInt32((wrTxt.Substring(start, loc - start))), ii); break; case (int)CanonicalDataTypes.CanonDtFloat: AnArray.SetValue(Convert.ToSingle((wrTxt.Substring(start, loc - start))), ii); break; case (int)CanonicalDataTypes.CanonDtDouble: AnArray.SetValue(Convert.ToDouble((wrTxt.Substring(start, loc - start))), ii); break; case (int)CanonicalDataTypes.CanonDtBool: AnArray.SetValue(Convert.ToBoolean((wrTxt.Substring(start, loc - start))), ii); break; case (int)CanonicalDataTypes.CanonDtString: AnArray.SetValue(Convert.ToString((wrTxt.Substring(start, loc - start))), ii); break; default: return(false); } start = loc + 1; } return(true); } catch (Exception ex) { return(false); } }
public static bool LoadArray(ref System.Array AnArray, int CanonDT, string wrTxt) { int ii = 0; int loc = 0; int Wlen = 0; int start = 0; try { start = 1; Wlen = wrTxt.Length; for (ii = AnArray.GetLowerBound(0); ii <= AnArray.GetUpperBound(0); ii++) { loc = wrTxt.IndexOf(",", 0); if (ii < AnArray.GetUpperBound(0)) { if (loc == 0) { //MessageBox.Show("Valor escrito: Numero incorrecto de digitos para el tamaño del arreglo?", "Error de argumento", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(false); } } else { loc = Wlen + 1; } switch (CanonDT) { case (int)CanonicalDataTypes.CanonDtByte: AnArray.SetValue(Convert.ToByte((wrTxt.Substring(start, loc - start))), ii); break; // End case case (int)CanonicalDataTypes.CanonDtChar: AnArray.SetValue(Convert.ToSByte((wrTxt.Substring(start, loc - start))), ii); break; // End case case (int)CanonicalDataTypes.CanonDtWord: AnArray.SetValue(Convert.ToUInt16((wrTxt.Substring(start, loc - start))), ii); break; // End case case (int)CanonicalDataTypes.CanonDtShort: AnArray.SetValue(Convert.ToInt16((wrTxt.Substring(start, loc - start))), ii); break; // End case case (int)CanonicalDataTypes.CanonDtDWord: AnArray.SetValue(Convert.ToInt32((wrTxt.Substring(start, loc - start))), ii); break; // End case case (int)CanonicalDataTypes.CanonDtLong: AnArray.SetValue(Convert.ToInt32((wrTxt.Substring(start, loc - start))), ii); break; // End case case (int)CanonicalDataTypes.CanonDtFloat: AnArray.SetValue(Convert.ToSingle((wrTxt.Substring(start, loc - start))), ii); break; // End case case (int)CanonicalDataTypes.CanonDtDouble: AnArray.SetValue(Convert.ToDouble((wrTxt.Substring(start, loc - start))), ii); break; // End case case (int)CanonicalDataTypes.CanonDtBool: AnArray.SetValue(Convert.ToBoolean((wrTxt.Substring(start, loc - start))), ii); break; // End case case (int)CanonicalDataTypes.CanonDtString: AnArray.SetValue(Convert.ToString((wrTxt.Substring(start, loc - start))), ii); break; // End case default: //MessageBox.Show("El tipo de valor que se intenta escribir es desconocido", "Error de argumento", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(false); } start = loc + 1; } return(true); } catch (Exception ex) { //MessageBox.Show("Al intentar escribir el vaor se genero la siguiente excepción: " + ex.Message, "Excepción de OPC", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(false); } }
// Returns the index of the first occurrence of a given value in a range of // an array. The array is searched forwards, starting at index // startIndex and upto count elements. The // elements of the array are compared to the given value using the // Object.Equals method. // public static int IndexOf(Array array, Object value, int startIndex, int count) { if (array == null) { throw new Exception("array is null in Array::IndexOf"); } if (array.Rank != 1) { throw new Exception("Rank_MultiDimNotSupported"); } int lb = array.GetLowerBound(0); if (startIndex < lb || startIndex > array.Length + lb) { throw new Exception("start index is invaild"); } if (count < 0 || count > array.Length - startIndex + lb) { throw new Exception("count is invaild"); } // Try calling a quick native method to handle primitive types. int retVal; bool r = TrySZIndexOf(array, startIndex, count, value, out retVal); if (r) { return(retVal); } Object[] objArray = array as Object[]; int endIndex = startIndex + count; if (objArray != null) { if (value == null) { for (int i = startIndex; i < endIndex; i++) { if (objArray[i] == null) { return(i); } } } else { for (int i = startIndex; i < endIndex; i++) { Object obj = objArray[i]; if (obj != null && obj.Equals(value)) { return(i); } } } } else { for (int i = startIndex; i < endIndex; i++) { Object obj = array.GetValue(i); if (obj == null) { if (value == null) { return(i); } } else { if (obj.Equals(value)) { return(i); } } } } // Return one less than the lower bound of the array. This way, // for arrays with a lower bound of -1 we will not return -1 when the // item was not found. And for SZArrays (the vast majority), -1 still // works for them. return(lb - 1); }
public override string FormatArrayTypeName(Type arrayType, Array arrayOpt, ObjectFormattingOptions options) { StringBuilder sb = new StringBuilder(); // print the inner-most element type first: Type elementType = arrayType.GetElementType(); while (elementType.IsArray) { elementType = elementType.GetElementType(); } sb.Append(FormatTypeName(elementType, options)); // print all components of a jagged array: Type type = arrayType; do { if (arrayOpt != null) { sb.Append('['); int rank = type.GetArrayRank(); bool anyNonzeroLowerBound = false; for (int i = 0; i < rank; i++) { if (arrayOpt.GetLowerBound(i) > 0) { anyNonzeroLowerBound = true; break; } } for (int i = 0; i < rank; i++) { int lowerBound = arrayOpt.GetLowerBound(i); int length = arrayOpt.GetLength(i); if (i > 0) { sb.Append(", "); } if (anyNonzeroLowerBound) { AppendArrayBound(sb, lowerBound, options.UseHexadecimalNumbers); sb.Append(".."); AppendArrayBound(sb, length + lowerBound, options.UseHexadecimalNumbers); } else { AppendArrayBound(sb, length, options.UseHexadecimalNumbers); } } sb.Append(']'); arrayOpt = null; } else { AppendArrayRank(sb, type); } type = type.GetElementType(); } while (type.IsArray); return sb.ToString(); }
private void WriteArray(Array array, Hashtable objectContainer, ref Int32 objectID) { if (array.Rank > 1) { throw new RankException("Only single dimension arrays are supported here."); } stream.WriteByte(PHPSerializationTag.AssocArray); stream.WriteByte(PHPSerializationTag.Colon); WriteNumber(array.GetLength(0)); stream.WriteByte(PHPSerializationTag.Colon); stream.WriteByte(PHPSerializationTag.LeftB); Int32 lowerBound = array.GetLowerBound(0); Int32 upperBound = array.GetUpperBound(0); for (Int32 i = lowerBound; i <= upperBound; i++) { WriteInteger(i); Serialize(array.GetValue(i), objectContainer, ref objectID); } stream.WriteByte(PHPSerializationTag.RightB); }
static bool IsSingleDimensionalZeroBasedArray(Array a) { return a != null && a.Rank == 1 && a.GetLowerBound(0) == 0; }
/// <summary> /// Formats an array type name (vector or multidimensional). /// </summary> public virtual string FormatArrayTypeName(Type arrayType, Array arrayOpt, CommonTypeNameFormatterOptions options) { if (arrayType == null) { throw new ArgumentNullException(nameof(arrayType)); } StringBuilder sb = new StringBuilder(); // print the inner-most element type first: Type elementType = arrayType.GetElementType(); while (elementType.IsArray) { elementType = elementType.GetElementType(); } sb.Append(FormatTypeName(elementType, options)); // print all components of a jagged array: Type type = arrayType; do { if (arrayOpt != null) { sb.Append(ArrayOpening); int rank = type.GetArrayRank(); bool anyNonzeroLowerBound = false; for (int i = 0; i < rank; i++) { if (arrayOpt.GetLowerBound(i) > 0) { anyNonzeroLowerBound = true; break; } } for (int i = 0; i < rank; i++) { int lowerBound = arrayOpt.GetLowerBound(i); int length = arrayOpt.GetLength(i); if (i > 0) { sb.Append(", "); } if (anyNonzeroLowerBound) { AppendArrayBound(sb, lowerBound, options.ArrayBoundRadix); sb.Append(".."); AppendArrayBound(sb, length + lowerBound, options.ArrayBoundRadix); } else { AppendArrayBound(sb, length, options.ArrayBoundRadix); } } sb.Append(ArrayClosing); arrayOpt = null; } else { AppendArrayRank(sb, type); } type = type.GetElementType(); } while (type.IsArray); return sb.ToString(); }
/// <summary> /// Fills the one-dimension targetArray with either matching cell values from /// sourceArray or with a initial value. /// </summary> /// <param name="sourceArray">The array object containing the values to copy.</param> /// <param name="targetArray">The new array where to copy the values.</param> /// <param name="valueProvider">a <c>InitialValueProvider</c> object used to get /// the default values for the new cells.</param> /// <param name="bFixedLengthString">Optional bolean flag that indicates if the current array type is fixed length string (original vb6 code) - /// its default value is false, because it will be generated in upgraded code when current array type used to be a fixed length string.</param> /// <param name="iFixedLengthStringSize">Optional integer value that indicates what is the fixed length string size, used in conjunction with previous (bFixedLengthString) parameter.</param> private static void FillsOneDimensionArray(Array sourceArray, Array targetArray, InitialValueProvider valueProvider, bool bFixedLengthString = false, int iFixedLengthStringSize = 0) { if (targetArray.Length > sourceArray.Length) { for (int i = sourceArray.Length; i < targetArray.Length; i++) { targetArray.SetValue(valueProvider.GetInitialValue(bFixedLengthString, iFixedLengthStringSize), i + targetArray.GetLowerBound(0)); } } Array.Copy(sourceArray, sourceArray.GetLowerBound(0), targetArray, sourceArray.GetLowerBound(0), Math.Min(targetArray.GetLength(0), sourceArray.GetLength(0))); }
private static void WriteArray(MemoryStream stream, Array a, int[] indices, Hashtable ht, ref int hv, Encoding encoding) { int n = indices.Length; int dimension = n - 1; int[] temp = new int[n + 1]; indices.CopyTo(temp, 0); int len = a.GetLength(dimension); byte[] alen = Encoding.ASCII.GetBytes(len.ToString()); int lb = a.GetLowerBound(dimension); int ub = a.GetUpperBound(dimension); stream.WriteByte(__a); stream.WriteByte(__Colon); stream.Write(alen, 0, alen.Length); stream.WriteByte(__Colon); stream.WriteByte(__LeftB); for (int i = lb; i <= ub; i++) { WriteInteger(stream, Encoding.ASCII.GetBytes(i.ToString())); if (a.Rank == n) { indices[n - 1] = i; Serialize(stream, a.GetValue(indices), ht, ref hv, encoding); } else { temp[n - 1] = i; WriteArray(stream, a, temp, ht, ref hv, encoding); } } stream.WriteByte(__RightB); }
// Returns the index of the last occurrence of a given value in a range of // an array. The array is searched backwards, starting at index // startIndex and counting uptocount elements. The elements of // the array are compared to the given value using the Object.Equals // method. // /// <include file='doc\Array.uex' path='docs/doc[@for="Array.LastIndexOf2"]/*' /> public static int LastIndexOf(Array array, Object value, int startIndex, int count) { if (array==null) throw new ArgumentNullException("array"); if (array.Length == 0) { return -1; } int lb = array.GetLowerBound(0); if (startIndex < lb || startIndex >= array.Length + lb) throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count")); if (count > startIndex - lb + 1) throw new ArgumentOutOfRangeException("endIndex", Environment.GetResourceString("ArgumentOutOfRange_EndIndexStartIndex")); if (array.Rank != 1) throw new RankException(Environment.GetResourceString("Rank_MultiDimNotSupported")); // Try calling a quick native method to handle primitive types. int retVal; int r = TrySZLastIndexOf(array, startIndex, count, value, out retVal); if (r != 0) return retVal; Object[] objArray = array as Object[]; int endIndex = startIndex - count + 1; if (objArray!=null) { if (value == null) { for (int i = startIndex; i >= endIndex; i--) { if (objArray[i] == null) return i; } } else { for (int i = startIndex; i >= endIndex; i--) { Object obj = objArray[i]; if (obj != null && value.Equals(obj)) return i; } } } else { // This is an array of value classes BCLDebug.Assert(array.GetType().GetElementType().IsValueType, "array.GetType().GetUnderlyingType().IsValueType"); if (value==null) return -1; for (int i = startIndex; i >= endIndex; i--) { Object obj = array.GetValue(i); if (obj != null && value.Equals(obj)) return i; } } return lb-1; // Return lb-1 for arrays with negative lower bounds. }
/// <summary> /// Append all array data to the binary stream. /// </summary> private void WriteBinaryArrayData(NpgsqlNativeTypeInfo TypeInfo, Array nativeData, NativeToBackendTypeConverterOptions options, MemoryStream dst, int dimensionOffset, int[] dimensionOffsets) { int dimensionLength = nativeData.GetLength(dimensionOffset); int dimensionLBound = nativeData.GetLowerBound(dimensionOffset); if (dimensionOffset < nativeData.Rank - 1) { // Drill down recursively until we hit a single dimension array. for (int i = dimensionLBound ; i < dimensionLBound + dimensionLength ; i++) { dimensionOffsets[dimensionOffset] = i; WriteBinaryArrayData(TypeInfo, nativeData, options, dst, dimensionOffset + 1, dimensionOffsets); } } else { // Write the individual array elements to the output stream. for (int i = dimensionLBound ; i < dimensionLBound + dimensionLength ; i++) { object elementNative; dimensionOffsets[dimensionOffset] = i; elementNative = nativeData.GetValue(dimensionOffsets); if (elementNative == null || elementNative == DBNull.Value) { // Write length identifier -1 indicating NULL value. dst.WriteInt32(-1); } else { byte[] elementBinary; elementBinary = (byte[])_elementConverter.ConvertToBackend(elementNative, true, options); // Write lenght identifier. dst.WriteInt32(elementBinary.Length); // Write element data. dst.Write(elementBinary, 0, elementBinary.Length); } } } }
// Reverses all elements of the given array. Following a call to this // method, an element previously located at index i will now be // located at index length - i - 1, where length is the // length of the array. // /// <include file='doc\Array.uex' path='docs/doc[@for="Array.Reverse"]/*' /> public static void Reverse(Array array) { if (array==null) throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Array")); Reverse(array, array.GetLowerBound(0), array.Length); }
private static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, bool reliable) { if (sourceArray == null) { throw new ArgumentNullException(nameof(sourceArray)); } if (destinationArray == null) { throw new ArgumentNullException(nameof(destinationArray)); } if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length), "Value has to be >= 0."); } if (sourceArray.Rank != destinationArray.Rank) { throw new RankException(SR.Rank_MultiDimNotSupported); } if (sourceIndex < 0) { throw new ArgumentOutOfRangeException(nameof(sourceIndex), "Value has to be >= 0."); } if (destinationIndex < 0) { throw new ArgumentOutOfRangeException(nameof(destinationIndex), "Value has to be >= 0."); } if (FastCopy(sourceArray, sourceIndex, destinationArray, destinationIndex, length)) { return; } int source_pos = sourceIndex - sourceArray.GetLowerBound(0); int dest_pos = destinationIndex - destinationArray.GetLowerBound(0); if (source_pos < 0) { throw new ArgumentOutOfRangeException(nameof(sourceIndex), "Index was less than the array's lower bound in the first dimension."); } if (dest_pos < 0) { throw new ArgumentOutOfRangeException(nameof(destinationIndex), "Index was less than the array's lower bound in the first dimension."); } // re-ordered to avoid possible integer overflow if (source_pos > sourceArray.Length - length) { throw new ArgumentException(SR.Arg_LongerThanSrcArray, nameof(sourceArray)); } if (dest_pos > destinationArray.Length - length) { throw new ArgumentException("Destination array was not long enough. Check destIndex and length, and the array's lower bounds", nameof(destinationArray)); } Type src_type = sourceArray.GetType().GetElementType() !; Type dst_type = destinationArray.GetType().GetElementType() !; var dst_type_vt = dst_type.IsValueType && Nullable.GetUnderlyingType(dst_type) == null; if (src_type.IsEnum) { src_type = Enum.GetUnderlyingType(src_type); } if (dst_type.IsEnum) { dst_type = Enum.GetUnderlyingType(dst_type); } if (reliable) { if (!dst_type.Equals(src_type)) { throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType); } } else { if (!CanAssignArrayElement(src_type, dst_type)) { throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_CantAssignType); } } if (!Object.ReferenceEquals(sourceArray, destinationArray) || source_pos > dest_pos) { for (int i = 0; i < length; i++) { Object srcval = sourceArray.GetValueImpl(source_pos + i); if (dst_type_vt && (srcval == null || (src_type == typeof(object) && srcval.GetType() != dst_type))) { throw new InvalidCastException(); } try { destinationArray.SetValueImpl(srcval, dest_pos + i); } catch (ArgumentException) { throw CreateArrayTypeMismatchException(); } } } else { for (int i = length - 1; i >= 0; i--) { Object srcval = sourceArray.GetValueImpl(source_pos + i); try { destinationArray.SetValueImpl(srcval, dest_pos + i); } catch (ArgumentException) { throw CreateArrayTypeMismatchException(); } } } }
public static int GetUpperBound(System.Array array, int dimension) { return(array.GetLowerBound(dimension) + array.GetLength(dimension) - 1); }