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(); }
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); }
//-------------------------------------------------------------------// /// <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; }
// Copy the contents of an array. public static Array CopyArray(Array arySrc, Array aryDest) { if(arySrc != null) { // Check that the arrays have the same rank and dimensions. int rank = arySrc.Rank; if(rank != aryDest.Rank) { ThrowExceptionInternal (new InvalidCastException (S._("VB_MismatchedRanks"))); } for(int dim = 0; dim < rank; ++dim) { if(arySrc.GetUpperBound(dim) != aryDest.GetUpperBound(dim)) { ThrowExceptionInternal (new ArrayTypeMismatchException (S._("VB_MismatchedDimensions"))); } } Array.Copy(arySrc, aryDest, arySrc.Length); } return aryDest; }
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(); }
/// <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); } }
static bool IsEnd(Array array, Int32[] indexer) { for (var i = 0; i < array.Rank; ++i) { if (indexer[i] > array.GetUpperBound(i)) return true; } return false; }
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> /// Инициализирующий конструктор. /// </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(); }
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++); } }
public static object GetArraySlice( Array inputarray, int sliceindex ) { int numoutputdimensions = inputarray.Rank - 1; int[] newdimensions = new int[ numoutputdimensions ]; for( int i = 1; i < numoutputdimensions + 1; i++ ) { newdimensions[ i - 1 ] = inputarray.GetUpperBound( i ) + 1; } Array newarray = Array.CreateInstance( inputarray.GetType().GetElementType(), newdimensions ); int[]traverseinputindex = new int[ numoutputdimensions + 1 ]; int[]traverseoutputindex = new int[ numoutputdimensions ]; traverseinputindex[0] = sliceindex; bool bDone = false; while( !bDone ) { newarray.SetValue( inputarray.GetValue( traverseinputindex ), traverseoutputindex ); bool bUpdatedtraverseindex = false; for( int i = numoutputdimensions - 1; i >= 0 && !bUpdatedtraverseindex; i-- ) { traverseinputindex[i + 1]++; traverseoutputindex[i]++; if( traverseoutputindex[i] >= newdimensions[i] ) { if( i == 0 ) { bDone = true; } else { traverseinputindex[i + 1] = 0; traverseoutputindex[i ] = 0; } } else { bUpdatedtraverseindex = true; } } } return newarray; }
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; }
private void ImportPipeComponentSheet(Array sheetValues, Worksheet worksheet, List<CellValue> cellValues) { try { RaiseMessage(MessageType.Added, "----------------------------------"); RaiseMessage(MessageType.Added, string.Format("Importing Sheet '{0}'.", worksheet.Name)); RaiseMessage(MessageType.Added, "----------------------------------"); int tagNameIndex = cellValues.Where(x => x.ExpectedValue == mTagNumberCellName).FirstOrDefault().Y; int lineNumberIndex = cellValues.Where(x => x.ExpectedValue == mLineNumberCellName).FirstOrDefault().Y; int pandIdIndex = cellValues.Where(x => x.ExpectedValue == mPandIDCellName).FirstOrDefault().Y; int emptyPipesCount = 0; int rowCount = sheetValues.GetUpperBound(0); int columnCount = sheetValues.GetUpperBound(1); int firstRowIndex = cellValues.Where(x => x.ExpectedValue == mPandIDCellName).FirstOrDefault().X + 1; //Get Property Names and their column indexes Dictionary<string, int> propertyPositions = new Dictionary<string, int>(); for (int colIndex = pandIdIndex + 1; colIndex <= columnCount; colIndex++) { string propertyName = sheetValues.GetValue(firstRowIndex, colIndex) == null ? string.Empty : sheetValues.GetValue(firstRowIndex, colIndex).ToString(); if (!string.IsNullOrEmpty(propertyName)) { var property = (from x in mExistingPipeComponentProperties where x.Name.ToLower() == propertyName.Trim().ToLower() select x).FirstOrDefault(); if (property != null) { if (!propertyPositions.ContainsKey(property.Name)) { propertyPositions.Add(property.Name, colIndex); } else { RaiseMessage(MessageType.Warning, string.Format("WorkSheet '{0}': Found duplicate property names '{1}'. Skipping Worksheet.", worksheet.Name, propertyName)); } } else { RaiseMessage(MessageType.Error, string.Format("WorkSheet '{0}': Property name '{1}' will be skipped as it does not exist in the Database.", worksheet.Name, propertyName)); } } } for (int rowIndex = firstRowIndex; rowIndex <= rowCount; rowIndex++) { PipeComponent newPipeComponent = new PipeComponent(); string lineNumber = sheetValues.GetValue(rowIndex, lineNumberIndex) == null ? string.Empty : sheetValues.GetValue(rowIndex, lineNumberIndex).ToString(); string tagNumber = sheetValues.GetValue(rowIndex, lineNumberIndex) == null ? string.Empty : sheetValues.GetValue(rowIndex, tagNameIndex).ToString(); string drawing = sheetValues.GetValue(rowIndex, pandIdIndex) == null ? string.Empty : sheetValues.GetValue(rowIndex, pandIdIndex).ToString(); LineNumberParser lineNumberParser = new LineNumberParser(lineNumber); if (!lineNumberParser.IsValid()) { string msg = string.Format("Worksheet {0}, Row {1} : Pipe Number Format '{2}'. Reason: {3}", worksheet.Name, rowIndex, tagNumber, lineNumberParser.ErrorMessage); RaiseMessage(MessageType.Error, msg); continue; } TagNumberParser tagNumberParser = new TagNumberParser(tagNumber); if (!tagNumberParser.IsValid()) { string msg = string.Format("Worksheet {0}, Row {1} : Invalid Tag Number Format '{2}'. Reason: {3}", worksheet.Name, rowIndex, tagNumber, tagNumberParser.ErrorMessage); RaiseMessage(MessageType.Error, msg); continue; } if (GetPipe(worksheet, lineNumberParser, newPipeComponent, rowIndex)) { emptyPipesCount++; if (emptyPipesCount == 3) { RaiseMessage(MessageType.Warning, string.Format("WorkSheet '{0}' Line '{1}': Found 3 empty Pipes. Continuing on to next Sheet.", worksheet.Name, rowIndex)); break; } continue; } GetDrawing(worksheet, drawing, newPipeComponent, rowIndex); AttachComponentProperties(worksheet, propertyPositions, sheetValues, newPipeComponent, rowIndex); //SAVE SavePipeComponent(worksheet, tagNumberParser, newPipeComponent, rowIndex); } RaiseMessage(MessageType.Added, string.Format("Finished importing Sheet '{0}'.", worksheet.Name)); } catch (Exception ex) { RaiseMessage(MessageType.Error, string.Format("Error occured: {0}", ex.Message)); RaiseMessage(MessageType.Error, string.Format("Error Stack trace: {0}", ex.StackTrace)); } RaiseMessage(MessageType.Added, "Finished Job"); }
private static void Iterate(Array array, int[] indices, int dimension, Action<int[]> action) { if (dimension >= indices.Length) { action(indices); } else { var lowerBound = array.GetLowerBound(dimension); var upperBound = array.GetUpperBound(dimension); for (var index = lowerBound; index <= upperBound; index++) { indices[dimension] = index; Iterate(array, indices, dimension + 1, action); } } }
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 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); }
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 void WriteGenericArray (BinaryWriter writer, long id, Array array) { Type elementType = array.GetType().GetElementType(); // Registers and writes the assembly of the array element type if needed if (!elementType.IsArray) WriteAssembly (writer, elementType.Assembly); // Writes the array writer.Write ((byte) BinaryElement.GenericArray); writer.Write ((int)id); // Write the structure of the array if (elementType.IsArray) writer.Write ((byte) ArrayStructure.Jagged); else if (array.Rank == 1) writer.Write ((byte) ArrayStructure.SingleDimensional); else writer.Write ((byte) ArrayStructure.MultiDimensional); // Write the number of dimensions and the length // of each dimension writer.Write (array.Rank); for (int n=0; n<array.Rank; n++) writer.Write (array.GetUpperBound (n) + 1); // Writes the type WriteTypeCode (writer, elementType); WriteTypeSpec (writer, elementType); // Writes the values. For single-dimension array, a special tag is used // to represent multiple consecutive null values. I don't know why this // optimization is not used for multidimensional arrays. if (array.Rank == 1 && !elementType.IsValueType) { WriteSingleDimensionArrayElements (writer, array, elementType); } else { foreach (object item in array) WriteValue (writer, elementType, item); } }
/// <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; }
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); }
/// <summary> /// Write a rank of an array in Json format /// </summary> /// <param name="writer">JsonWriter in use</param> /// <param name="serializer">JsonSerializer in use</param> /// <param name="array">Array to be written</param> /// <param name="currentRank">Current rank "depth"</param> /// <param name="assignFromIndexList">List of indexes currently being used to read from the array</param> private void WriteRank(JsonWriter writer, JsonSerializer serializer, Array array, int currentRank, int[] assignFromIndexList) { writer.WriteStartArray(); var lb = array.GetLowerBound(currentRank); var ub = array.GetUpperBound(currentRank); // Create a new indices list (one bigger than passed in) and fill with existing values var myAssignFromIndex = assignFromIndexList.GetUpperBound(0) + 1; var myAssignFromIndexList = new int[myAssignFromIndex + 1]; Array.Copy(assignFromIndexList, myAssignFromIndexList, assignFromIndexList.Length); for (var i = lb; i <= ub; i++) { // set current index of this current rank myAssignFromIndexList[myAssignFromIndex] = i; if (currentRank < array.Rank - 1) // There are still more ranks, process them WriteRank(writer, serializer, array, currentRank + 1, myAssignFromIndexList); else // This is the "bottom" rank, write out values serializer.Serialize(writer, array.GetValue(myAssignFromIndexList)); } writer.WriteEndArray(); }
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, int initialDepth, int[] indices) { int dimension = indices.Length; int[] newIndices = new int[dimension + 1]; for (int i = 0; i < dimension; i++) { newIndices[i] = indices[i]; } writer.WriteStartArray(); for (int i = values.GetLowerBound(dimension); i <= values.GetUpperBound(dimension); i++) { newIndices[dimension] = i; bool isTopLevel = (newIndices.Length == values.Rank); if (isTopLevel) { object value = values.GetValue(newIndices); try { JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); if (ShouldWriteReference(value, null, valueContract, contract, member)) { WriteReference(writer, value); } else { if (CheckForCircularReference(writer, value, null, valueContract, contract, member)) { SerializeValue(writer, value, valueContract, null, contract, member); } } } catch (Exception ex) { if (IsErrorHandled(values, contract, i, null, writer.ContainerPath, ex)) { HandleError(writer, initialDepth + 1); } else { throw; } } } else { SerializeMultidimensionalArray(writer, values, contract, member, initialDepth + 1, newIndices); } } writer.WriteEndArray(); }
/// <summary> /// To check whether an index is in the range of the given array. /// </summary> /// <param name="index">Index to check</param> /// <param name="arrayToCheck">Array where to check</param> /// <returns></returns> /// <remarks> /// Contributed by Mohammad Rahman, http://mohammad-rahman.blogspot.com/ /// </remarks> public static bool IsIndexInArray(this int index, Array arrayToCheck) { return index.GetArrayIndex().InRange(arrayToCheck.GetLowerBound(0), arrayToCheck.GetUpperBound(0)); }
void WriteMultiDimensionalArray(WriteJsonValue m, Array md) { var r = md.Rank; var lb = new int[r]; var ub = new int[r]; var mdi = new int[r]; for (int i = 0; i < r; i++) { lb[i] = md.GetLowerBound (i); ub[i] = md.GetUpperBound (i) + 1; } Array.Copy (lb, 0, mdi, 0, r); WriteMultiDimensionalArray (m, md, r, lb, ub, mdi, 0); }
public void CopyTo(Array array, int index) { IWbemQualifierSetFreeThreaded typeQualifierSet; if (array != null) { if (index < array.GetLowerBound(0) || index > array.GetUpperBound(0)) { throw new ArgumentOutOfRangeException("index"); } else { string[] strArrays = null; try { typeQualifierSet = this.GetTypeQualifierSet(); } catch (ManagementException managementException1) { ManagementException managementException = managementException1; if (this.qualifierSetType != QualifierType.PropertyQualifier || managementException.ErrorCode != ManagementStatus.SystemProperty) { throw; } else { return; } } int names_ = typeQualifierSet.GetNames_(0, out strArrays); if (names_ < 0) { if (((long)names_ & (long)-4096) != (long)-2147217408) { Marshal.ThrowExceptionForHR(names_); } else { ManagementException.ThrowWithExtendedInfo((ManagementStatus)names_); } } if (index + (int)strArrays.Length <= array.Length) { string[] strArrays1 = strArrays; for (int i = 0; i < (int)strArrays1.Length; i++) { string str = strArrays1[i]; int num = index; index = num + 1; array.SetValue(new QualifierData(this.parent, this.propertyOrMethodName, str, this.qualifierSetType), num); } } else { throw new ArgumentException(null, "index"); } return; } } else { throw new ArgumentNullException("array"); } }
private static string[,] ConvertToStringArray2Dimensional(Array values) { // create a new string array var theArray = new string[values.GetUpperBound(0), values.GetUpperBound(1) - 1]; // string[,] test = new string[11, 2]; // loop through the 2-D System.Array and populate the 1-D String Array for (var i = 1; i <= values.GetUpperBound(0); i++) { for (var j = 1; j < values.GetUpperBound(1); j++) { if (values.GetValue(i, j) == null) { theArray[i - 1, j - 1] = string.Empty; } else { theArray[i - 1, j - 1] = values.GetValue(i, j).ToString(); } // if (MainForm.StopGracefully) // return null; } } return theArray; }
/// <overload> /// <para>Copies the <see cref='System.Management.QualifierDataCollection'/> into an array.</para> /// </overload> /// <summary> /// <para> Copies the <see cref='System.Management.QualifierDataCollection'/> into an array.</para> /// </summary> /// <param name='array'>The array to which to copy the <see cref='System.Management.QualifierDataCollection'/>. </param> /// <param name='index'>The index from which to start copying. </param> public void CopyTo(Array array, int index) { if (null == array) throw new ArgumentNullException("array"); if ((index < array.GetLowerBound(0)) || (index > array.GetUpperBound(0))) throw new ArgumentOutOfRangeException("index"); // Get the names of the qualifiers string[] qualifierNames = null; IWbemQualifierSetFreeThreaded quals; try { quals = GetTypeQualifierSet(); } catch(ManagementException e) { // There are NO qualifiers on system properties, so we just return if(qualifierSetType == QualifierType.PropertyQualifier && e.ErrorCode == ManagementStatus.SystemProperty) return; else throw; } int status = quals.GetNames_(0, out qualifierNames); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status); } if ((index + qualifierNames.Length) > array.Length) throw new ArgumentException(null, "index"); foreach (string qualifierName in qualifierNames) array.SetValue(new QualifierData(parent, propertyOrMethodName, qualifierName, qualifierSetType), index++); return; }