public override void Reset()
 {
     if (cache != null)
     {
         iterator = cache.GetEnumerator();
     }
 }
        internal RestCollection(IEnumerator enumerator)
        {
            if (enumerator == null)
                this._inner = new object[0];
            else
            {
                ArrayList list = new ArrayList();
                //try
                //{
                //    object o = enumerator.Current;
                //    list.Add(o);
                //}
                //catch (InvalidOperationException)
                //{
                //    // Just means there's no current object
                //}

                while (enumerator.MoveNext())
                {
                    list.Add(enumerator.Current);
                }
                this._inner = list;
                _count = _inner.Count-1;
            }
        }
Example #3
0
 /// <summary>
 /// Initializes a new instance of the EnumeratorProxy class.
 /// </summary>
 /// <param name="wrapperScope">The wrapper scope.</param>
 /// <param name="underlyingImplementation">The underlying implementation of the proxy.</param>
 public EnumeratorProxy(IWrapperScope wrapperScope, System.Collections.IEnumerator underlyingImplementation)
 {
     ExceptionUtilities.CheckArgumentNotNull(wrapperScope, "wrapperScope");
     ExceptionUtilities.CheckArgumentNotNull(underlyingImplementation, "underlyingImplementation");
     
     this.Scope = wrapperScope;
     this.underlyingImplementation = underlyingImplementation;
 }
        public static SyntaxTree GetTree(System.Collections.ArrayList Tokens)
        {
            TokenEnm = Tokens.GetEnumerator();

            GetToken();

            return StatementBlock();
        }
 private System.Collections.IEnumerator CurrentIterator()
 {
     if (_currentIterator == null)
     {
         _currentIterator = _delegate.GetEnumerator();
         _status = Enumerator_Status.RESET;
     }
     return _currentIterator;
 }
        /// <summary>
        /// Create new odb client
        /// </summary>
        public OdbClient()
        {

            this.PriorityEnumerator = Priorities.GetEnumerator();
            this.socket = new OdbSocket(new StreamSocket());

            this.status = new OdbStatus(this.socket);
            this.commands = new OdbCommands(this.socket);
            this.ecu = new OdbEcu(this.socket, this.commands);
        }
Example #7
0
        public void VisitAll(params System.Collections.IEnumerable[] m)
        {
            // initialize
            int n = m.Length;
            int j;
            System.Collections.IEnumerator[] a = new System.Collections.IEnumerator[n + 1];

            for (j = 1; j <= n; j++)
            {
                a[j] = m[j - 1].GetEnumerator();
                a[j].MoveNext();
            }

            a[0] = m[0].GetEnumerator();
            a[0].MoveNext();

            for (; ; )
            {
                switch (this.RunMode)
                {
                    case RunModeEnum.SelectClauses:
                        VisitTableColumns(a);
                        break;

                    case RunModeEnum.CurrentRow:
                        VisitCurrentRow(a);
                        break;

                    case RunModeEnum.Console:
                    default:
                        Visit(a);
                        break;
                }

                // prepare to add one
                j = n;

                // carry if necessary
                while (!a[j].MoveNext())
                {
                    a[j].Reset();
                    a[j].MoveNext();
                    j -= 1;
                }

                // increase unless done
                if (j == 0)
                {
                    break; // Terminate the algorithm
                }

            }
        }
 /// <summary>
 /// Initializes a newly created <code>SequenceInputStream</code>
 /// by remembering the argument, which must
 /// be an <code>Enumeration</code>  that produces
 /// objects whose run-time type is <code>InputStream</code>.
 /// </summary>
 /// <remarks>
 /// Initializes a newly created <code>SequenceInputStream</code>
 /// by remembering the argument, which must
 /// be an <code>Enumeration</code>  that produces
 /// objects whose run-time type is <code>InputStream</code>.
 /// The input streams that are  produced by
 /// the enumeration will be read, in order,
 /// to provide the bytes to be read  from this
 /// <code>SequenceInputStream</code>. After
 /// each input stream from the enumeration
 /// is exhausted, it is closed by calling its
 /// <code>close</code> method.
 /// </remarks>
 /// <param name="e">an enumeration of input streams.</param>
 /// <seealso cref="System.Collections.IEnumerator{E}">System.Collections.IEnumerator&lt;E&gt;
 /// 	</seealso>
 public SequenceInputStream(System.Collections.Generic.IEnumerator<InputStream> e)
 {
     this.e = e;
     try
     {
         nextStream();
     }
     catch (System.IO.IOException)
     {
         // This should never happen
         throw new System.Exception("panic");
     }
 }
Example #9
0
		public override Token Next(Token reusableToken)
		{
			System.Diagnostics.Debug.Assert(reusableToken != null);
			if (iter == null)
				iter = lst.GetEnumerator();
			// Since this TokenStream can be reset we have to maintain the tokens as immutable
			if (iter.MoveNext())
			{
				Token nextToken = (Token) iter.Current;
				return (Token) nextToken.Clone();
			}
			return null;
		}
Example #10
0
        public VertexDeclaration( IGraphicsDevice graphicsDevice, VertexElement [] elements )
        {
            this.elements = elements.GetEnumerator ();
            SharpDX.Direct3D9.Device device = graphicsDevice.Handle as SharpDX.Direct3D9.Device;

            SharpDX.Direct3D9.VertexElement [] convedElements = new SharpDX.Direct3D9.VertexElement [ elements.Length + 1 ];
            for ( int i = 0, offset = 0; i < elements.Length; ++i )
            {
                convedElements [ i ] = new SharpDX.Direct3D9.VertexElement ( 0, ( short ) offset,
                    ConvertType ( elements [ i ].Size ), SharpDX.Direct3D9.DeclarationMethod.Default,
                    ConvertType ( elements [ i ].Type ), ( byte ) elements [ i ].UsageIndex );
                offset += ElementSizeToRealSize ( elements [ i ].Size );
            }
            convedElements [ elements.Length ] = SharpDX.Direct3D9.VertexElement.VertexDeclarationEnd;

            vertexDeclaration = new SharpDX.Direct3D9.VertexDeclaration ( device, convedElements );
        }
		public override Token Next()
		{
			if (cache == null)
			{
				// fill cache lazily
				cache = new System.Collections.ArrayList();
				FillCache();
				iterator = cache.GetEnumerator();
			}
			
			if (!iterator.MoveNext())
			{
				// the cache is exhausted, return null
				return null;
			}
			
			return (Token) iterator.Current;
		}
Example #12
0
		public override bool IncrementToken()
		{
			if (cache == null)
			{
				// fill cache lazily
				cache = new System.Collections.ArrayList();
				FillCache();
				iterator = cache.GetEnumerator();
			}
			
			if (!iterator.MoveNext())
			{
				// the cache is exhausted, return false
				return false;
			}
			// Since the TokenFilter can be reset, the tokens need to be preserved as immutable.
			RestoreState((AttributeSource.State) iterator.Current);
			return true;
		}
        public override Token Next(/* in */ Token reusableToken)
        {
            System.Diagnostics.Debug.Assert(reusableToken != null);
            if (cache == null)
            {
                // fill cache lazily
                cache = new System.Collections.ArrayList();
                FillCache(reusableToken);
                iterator = cache.GetEnumerator();
            }

            if (!iterator.MoveNext())
            {
                // the cache is exhausted, return null
                return null;
            }

            Token nextToken = (Token) iterator.Current;
            return (Token) nextToken.Clone();
        }
Example #14
0
 /// Starts a coroutine on this system.
 public UnityEngine.Coroutine StartCoroutine(System.Collections.IEnumerator routine) =>
 Controller.Instance.StartCoroutine(routine);
Example #15
0
        private void ReadExcelFile()
        {
            try
            {
                ISheet sheet = grWorkbook.GetSheet("GR");
                System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

                #region Cells Comparison
                while (rows.MoveNext())
                {
                    IRow row = (XSSFRow)rows.Current;
                    if (row.RowNum == 0)
                    {
                        continue;
                    }
                    if (row.Cells.Any(d => d.CellType == CellType.Error))
                    {
                        continue;
                    }

                    ImportCLassModel obj = new ImportCLassModel();
                    for (int i = 0; i < row.LastCellNum; i++)
                    {
                        ICell cell = row.GetCell(i);

                        switch (i)
                        {
                        case 0:
                            if (cell == null)
                            {
                                obj.DocumentDate = null;
                            }
                            else
                            {
                                obj.DocumentDate = cell.DateCellValue;
                            }
                            break;

                        case 1:
                            if (cell == null)
                            {
                                obj.DocumentDate = null;
                            }
                            else
                            {
                                obj.PostingDate = cell.DateCellValue;
                            }
                            break;

                        case 2:
                            if (cell == null)
                            {
                                continue;
                            }
                            else
                            {
                                obj.PurchaseOrder = SetCellValue(cell);
                            }
                            break;

                        case 3:
                            if (cell == null)
                            {
                                obj.Vendor = null;
                            }
                            else
                            {
                                obj.Vendor = SetCellValue(cell);
                            }
                            break;

                        case 4:
                            if (cell == null)
                            {
                                obj.DeliveryNote = null;
                            }
                            else
                            {
                                obj.DeliveryNote = SetCellValue(cell);
                            }
                            break;

                        case 5:
                            if (cell == null)
                            {
                                obj.BillOfLading = null;
                            }
                            else
                            {
                                obj.BillOfLading = SetCellValue(cell);
                            }
                            break;

                        case 6:
                            if (cell == null)
                            {
                                obj.HeaderText = null;
                            }
                            else
                            {
                                obj.HeaderText = SetCellValue(cell);
                            }
                            break;

                        case 7:
                            if (cell == null)
                            {
                                continue;
                            }
                            else
                            {
                                obj.Material = SetCellValue(cell);
                            }
                            break;

                        case 8:
                            if (cell == null)
                            {
                                continue;
                            }
                            else
                            {
                                obj.MaterialShortText = SetCellValue(cell);
                            }
                            break;

                        case 9:
                            if (cell == null)
                            {
                                obj.Ok = null;
                            }
                            else
                            {
                                obj.Ok = cell.BooleanCellValue.ToString();
                            }
                            break;

                        case 10:
                            if (cell == null)
                            {
                                continue;
                            }
                            else
                            {
                                obj.Quantity = Convert.ToDecimal(cell.NumericCellValue);
                            }
                            break;

                        case 11:
                            if (cell == null)
                            {
                                continue;
                            }
                            else
                            {
                                obj.Eun = SetCellValue(cell);
                            }
                            break;

                        case 12:
                            if (cell == null)
                            {
                                obj.MvmtType = null;
                            }
                            else
                            {
                                obj.MvmtType = SetCellValue(cell);
                            }
                            break;

                        case 13:
                            if (cell == null)
                            {
                                continue;
                            }
                            else
                            {
                                obj.StorageLoc = SetCellValue(cell);
                            }
                            break;

                        case 14:
                            if (cell == null)
                            {
                                continue;
                            }
                            else
                            {
                                obj.Plant = Convert.ToInt32(cell.NumericCellValue);
                            }
                            break;

                        case 15:
                            if (cell == null)
                            {
                                continue;
                            }
                            else
                            {
                                obj.StorageBin = SetCellValue(cell);
                            }
                            break;
                        }
                    }
                    PopulateRecords(obj, tempCollection);
                }
                #endregion Cells Comparison

                if (tempCollection.Count() > 0)
                {
                    ImportBtn           = true;
                    IsEnableAutoRefresh = false;

                    _ImportGRCommand.RaiseCanExecuteChanged();
                    _ExportGRCommand.RaiseCanExecuteChanged();

                    GoodReceives = new ListCollectionView(tempCollection);
                    GoodReceives.SortDescriptions.Add(new SortDescription("CreatedOn", ListSortDirection.Descending));

                    CollectionViewSource.GetDefaultView(GoodReceives).Filter = Filter;
                }
                else
                {
                    throw new Exception("There was no matched data detected.");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to read contents:\n\n" + ex.Message, "Error");
            }
        }
Example #16
0
 /// <summary>
 /// Disposes the wrapped instance if it implements IDisposable.
 /// </summary>
 /// <param name="disposing">Whether or not to dispose managed resources</param>
 protected virtual void Dispose(bool disposing)
 {
     CallOrderUtilities.TryWrapArbitraryMethodCall(
         () => this.Dispose(),
         () =>
             {
                 var d = this.underlyingImplementation as IDisposable;
                 if (d != null)
                 {
                     d.Dispose();
                     this.underlyingImplementation = null;
                 }
             });
 }
 void IDisposable.Dispose()
 {
     v2CollEnum = null;
 }
Example #18
0
        protected static string GetComparisonStatement(StandardProviderParameters std, tgDynamicQuerySerializable query, List <tgComparison> items, string prefix)
        {
            string sql   = String.Empty;
            string comma = String.Empty;

            IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;

            //=======================================
            // WHERE
            //=======================================
            if (items != null)
            {
                sql += prefix;

                string compareTo = String.Empty;
                foreach (tgComparison comparisonItem in items)
                {
                    tgComparison.tgComparisonData comparisonData = (tgComparison.tgComparisonData)comparisonItem;
                    tgDynamicQuerySerializable    subQuery       = null;

                    bool requiresParam        = true;
                    bool needsStringParameter = false;

                    if (comparisonData.IsParenthesis)
                    {
                        if (comparisonData.Parenthesis == tgParenthesis.Open)
                        {
                            sql += "(";
                        }
                        else
                        {
                            sql += ")";
                        }

                        continue;
                    }

                    if (comparisonData.IsConjunction)
                    {
                        switch (comparisonData.Conjunction)
                        {
                        case tgConjunction.And: sql += " AND "; break;

                        case tgConjunction.Or: sql += " OR "; break;

                        case tgConjunction.AndNot: sql += " AND NOT "; break;

                        case tgConjunction.OrNot: sql += " OR NOT "; break;
                        }
                        continue;
                    }

                    Dictionary <string, OleDbParameter> types = null;
                    if (comparisonData.Column.Query != null)
                    {
                        IDynamicQuerySerializableInternal iLocalQuery = comparisonData.Column.Query as IDynamicQuerySerializableInternal;
                        types = Cache.GetParameters(iLocalQuery.DataID, (tgProviderSpecificMetadata)iLocalQuery.ProviderMetadata, (tgColumnMetadataCollection)iLocalQuery.Columns);
                    }

                    if (comparisonData.IsLiteral)
                    {
                        if (comparisonData.Column.Name[0] == '<')
                        {
                            sql += comparisonData.Column.Name.Substring(1, comparisonData.Column.Name.Length - 2);
                        }
                        else
                        {
                            sql += comparisonData.Column.Name;
                        }
                        continue;
                    }

                    if (comparisonData.ComparisonColumn.Name == null)
                    {
                        subQuery = comparisonData.Value as tgDynamicQuerySerializable;

                        if (subQuery == null)
                        {
                            if (comparisonData.Column.Name != null)
                            {
                                IDynamicQuerySerializableInternal iColQuery = comparisonData.Column.Query as IDynamicQuerySerializableInternal;
                                tgColumnMetadataCollection        columns   = (tgColumnMetadataCollection)iColQuery.Columns;
                                compareTo = Delimiters.Param + columns[comparisonData.Column.Name].PropertyName + (++std.pindex).ToString();
                            }
                            else
                            {
                                compareTo = Delimiters.Param + "Expr" + (++std.pindex).ToString();
                            }
                        }
                        else
                        {
                            // It's a sub query
                            compareTo     = GetSubquerySearchCondition(subQuery) + " (" + BuildQuery(std, subQuery) + ") ";
                            requiresParam = false;
                        }
                    }
                    else
                    {
                        compareTo     = GetColumnName(comparisonData.ComparisonColumn);
                        requiresParam = false;
                    }

                    switch (comparisonData.Operand)
                    {
                    case tgComparisonOperand.Exists:
                        sql += " EXISTS" + compareTo;
                        break;

                    case tgComparisonOperand.NotExists:
                        sql += " NOT EXISTS" + compareTo;
                        break;

                    //-----------------------------------------------------------
                    // Comparison operators, left side vs right side
                    //-----------------------------------------------------------
                    case tgComparisonOperand.Equal:
                        if (comparisonData.ItemFirst)
                        {
                            sql += ApplyWhereSubOperations(std, query, comparisonData) + " = " + compareTo;
                        }
                        else
                        {
                            sql += compareTo + " = " + ApplyWhereSubOperations(std, query, comparisonData);
                        }
                        break;

                    case tgComparisonOperand.NotEqual:
                        if (comparisonData.ItemFirst)
                        {
                            sql += ApplyWhereSubOperations(std, query, comparisonData) + " <> " + compareTo;
                        }
                        else
                        {
                            sql += compareTo + " <> " + ApplyWhereSubOperations(std, query, comparisonData);
                        }
                        break;

                    case tgComparisonOperand.GreaterThan:
                        if (comparisonData.ItemFirst)
                        {
                            sql += ApplyWhereSubOperations(std, query, comparisonData) + " > " + compareTo;
                        }
                        else
                        {
                            sql += compareTo + " > " + ApplyWhereSubOperations(std, query, comparisonData);
                        }
                        break;

                    case tgComparisonOperand.LessThan:
                        if (comparisonData.ItemFirst)
                        {
                            sql += ApplyWhereSubOperations(std, query, comparisonData) + " < " + compareTo;
                        }
                        else
                        {
                            sql += compareTo + " < " + ApplyWhereSubOperations(std, query, comparisonData);
                        }
                        break;

                    case tgComparisonOperand.LessThanOrEqual:
                        if (comparisonData.ItemFirst)
                        {
                            sql += ApplyWhereSubOperations(std, query, comparisonData) + " <= " + compareTo;
                        }
                        else
                        {
                            sql += compareTo + " <= " + ApplyWhereSubOperations(std, query, comparisonData);
                        }
                        break;

                    case tgComparisonOperand.GreaterThanOrEqual:
                        if (comparisonData.ItemFirst)
                        {
                            sql += ApplyWhereSubOperations(std, query, comparisonData) + " >= " + compareTo;
                        }
                        else
                        {
                            sql += compareTo + " >= " + ApplyWhereSubOperations(std, query, comparisonData);
                        }
                        break;

                    case tgComparisonOperand.Like:
                        sql += ApplyWhereSubOperations(std, query, comparisonData) + " LIKE " + compareTo;
                        needsStringParameter = true;
                        break;

                    case tgComparisonOperand.NotLike:
                        sql += ApplyWhereSubOperations(std, query, comparisonData) + " NOT LIKE " + compareTo;
                        needsStringParameter = true;
                        break;

                    case tgComparisonOperand.Contains:
                        sql += " CONTAINS(" + GetColumnName(comparisonData.Column) + ", " + compareTo + ")";
                        needsStringParameter = true;
                        break;

                    case tgComparisonOperand.IsNull:
                        sql          += ApplyWhereSubOperations(std, query, comparisonData) + " IS NULL";
                        requiresParam = false;
                        break;

                    case tgComparisonOperand.IsNotNull:
                        sql          += ApplyWhereSubOperations(std, query, comparisonData) + " IS NOT NULL";
                        requiresParam = false;
                        break;

                    case tgComparisonOperand.In:
                    case tgComparisonOperand.NotIn:
                    {
                        if (subQuery != null)
                        {
                            // They used a subquery for In or Not
                            sql += ApplyWhereSubOperations(std, query, comparisonData);
                            sql += (comparisonData.Operand == tgComparisonOperand.In) ? " IN" : " NOT IN";
                            sql += compareTo;
                        }
                        else
                        {
                            comma = String.Empty;
                            if (comparisonData.Operand == tgComparisonOperand.In)
                            {
                                sql += ApplyWhereSubOperations(std, query, comparisonData) + " IN (";
                            }
                            else
                            {
                                sql += ApplyWhereSubOperations(std, query, comparisonData) + " NOT IN (";
                            }

                            foreach (object oin in comparisonData.Values)
                            {
                                string str = oin as string;
                                if (str != null && !(str.StartsWith("#")))
                                {
                                    // STRING
                                    sql  += comma + Delimiters.StringOpen + str + Delimiters.StringClose;
                                    comma = ",";
                                }
                                else if (str != null)
                                {
                                    // DateTime
                                    sql  += comma + Convert.ToString(oin);
                                    comma = ",";
                                }
                                else if (null != oin as System.Collections.IEnumerable)
                                {
                                    // LIST OR COLLECTION OF SOME SORT
                                    System.Collections.IEnumerable enumer = oin as System.Collections.IEnumerable;
                                    if (enumer != null)
                                    {
                                        System.Collections.IEnumerator iter = enumer.GetEnumerator();

                                        while (iter.MoveNext())
                                        {
                                            object o = iter.Current;

                                            string soin = o as string;

                                            if (soin != null && !(soin.StartsWith("#")))
                                            {
                                                sql += comma + Delimiters.StringOpen + soin + Delimiters.StringClose;
                                            }
                                            else
                                            {
                                                sql += comma + Convert.ToString(o);
                                            }

                                            comma = ",";
                                        }
                                    }
                                }
                                else
                                {
                                    // NON STRING OR LIST
                                    sql  += comma + Convert.ToString(oin);
                                    comma = ",";
                                }
                            }
                            sql          += ") ";
                            requiresParam = false;
                        }
                    }
                    break;

                    case tgComparisonOperand.Between:

                        OleDbCommand sqlCommand = std.cmd as OleDbCommand;

                        sql += ApplyWhereSubOperations(std, query, comparisonData) + " BETWEEN ";
                        sql += compareTo;
                        if (comparisonData.ComparisonColumn.Name == null)
                        {
                            sqlCommand.Parameters.AddWithValue(compareTo, comparisonData.BetweenBegin);
                        }

                        if (comparisonData.ComparisonColumn2.Name == null)
                        {
                            IDynamicQuerySerializableInternal iColQuery = comparisonData.Column.Query as IDynamicQuerySerializableInternal;
                            tgColumnMetadataCollection        columns   = (tgColumnMetadataCollection)iColQuery.Columns;
                            compareTo = Delimiters.Param + columns[comparisonData.Column.Name].PropertyName + (++std.pindex).ToString();

                            sql += " AND " + compareTo;
                            sqlCommand.Parameters.AddWithValue(compareTo, comparisonData.BetweenEnd);
                        }
                        else
                        {
                            sql += " AND " + Delimiters.ColumnOpen + comparisonData.ComparisonColumn2 + Delimiters.ColumnClose;
                        }

                        requiresParam = false;
                        break;
                    }

                    if (requiresParam)
                    {
                        OleDbParameter p;

                        if (comparisonData.Column.Name != null)
                        {
                            p = types[comparisonData.Column.Name];

                            p = Cache.CloneParameter(p);
                            p.ParameterName = compareTo;
                            p.Value         = comparisonData.Value;
                            if (needsStringParameter)
                            {
                                p.DbType = DbType.String;
                            }
                        }
                        else
                        {
                            p = new OleDbParameter(compareTo, comparisonData.Value);
                        }

                        std.cmd.Parameters.Add(p);
                    }
                }
            }

            return(sql);
        }
Example #19
0
        /// <summary> Computes a {@link List} of {@link Set}s, where each set contains
        /// vertices which together form a strongly connected component within the
        /// given graph.
        ///
        /// </summary>
        /// <returns> <code>List</code> of <code>Set</code>s containing the strongly
        /// connected components
        /// </returns>
        public virtual System.Collections.IList stronglyConnectedSets()
        {
            if (m_stronglyConnectedSets == null)
            {
                //UPGRADE_TODO: Class 'java.util.LinkedList' was converted to 'System.Collections.ArrayList' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilLinkedList'"
                m_orderedVertices       = new System.Collections.ArrayList();
                m_stronglyConnectedSets = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));

                // create VertexData objects for all vertices, store them
                createVertexData();

                // perform the first round of DFS, result is an ordering
                // of the vertices by decreasing finishing time
                System.Collections.IEnumerator iter = m_vertexToVertexData.Values.GetEnumerator();

                //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'"
                while (iter.MoveNext())
                {
                    //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'"
                    VertexData data = (VertexData)iter.Current;

                    if (!data.m_discovered)
                    {
                        dfsVisit(m_graph, data, null);
                    }
                }

                // calculate inverse graph (i.e. every edge is reversed)
                DirectedGraph inverseGraph = new DefaultDirectedGraph();
                GraphHelper.addGraphReversed(inverseGraph, m_graph);

                // get ready for next dfs round
                resetVertexData();

                // second dfs round: vertices are considered in decreasing
                // finishing time order; every tree found is a strongly
                // connected set
                iter = m_orderedVertices.GetEnumerator();

                //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'"
                while (iter.MoveNext())
                {
                    //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'"
                    VertexData data = (VertexData)iter.Current;

                    if (!data.m_discovered)
                    {
                        // new strongly connected set
                        //UPGRADE_TODO: Class 'java.util.HashSet' was converted to 'SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashSet'"
                        SupportClass.SetSupport set_Renamed = new SupportClass.HashSetSupport();
                        m_stronglyConnectedSets.Add(set_Renamed);
                        dfsVisit(inverseGraph, data, set_Renamed);
                    }
                }

                // clean up for garbage collection
                m_orderedVertices    = null;
                m_vertexToVertexData = null;
            }

            return(m_stronglyConnectedSets);
        }
    public static void Main()
    {
        // Setup collection
        DoubleVector vect = new DoubleVector();

        for (int i = 0; i < collectionSize; i++)
        {
            double num = i * 10.1;
            vect.Add(num);
        }

        // Count property test
        if (vect.Count != collectionSize)
        {
            throw new Exception("Count test failed");
        }

        // IsFixedSize property test
        if (vect.IsFixedSize)
        {
            throw new Exception("IsFixedSize test failed");
        }

        // IsReadOnly property test
        if (vect.IsReadOnly)
        {
            throw new Exception("IsReadOnly test failed");
        }

        // Item indexing
        vect[0] = 200.1;
        if (vect[0] != 200.1)
        {
            throw new Exception("Item property test failed");
        }
        vect[0] = 0 * 10.1;
        try {
            vect[-1] = 777.1;
            throw new Exception("Item out of range (1) test failed");
        } catch (ArgumentOutOfRangeException) {
        }
        try {
            vect[vect.Count] = 777.1;
            throw new Exception("Item out of range (2) test failed");
        } catch (ArgumentOutOfRangeException) {
        }

        // CopyTo() test
        {
            double[] outputarray = new double[collectionSize];
            vect.CopyTo(outputarray);
            int index = 0;
            foreach (double val in outputarray)
            {
                if (vect[index] != val)
                {
                    throw new Exception("CopyTo (1) test failed, index:" + index);
                }
                index++;
            }
        }
        {
            double[] outputarray = new double[midCollection + collectionSize];
            vect.CopyTo(outputarray, midCollection);
            int index = midCollection;
            foreach (double val in vect)
            {
                if (outputarray[index] != val)
                {
                    throw new Exception("CopyTo (2) test failed, index:" + index);
                }
                index++;
            }
        }
        {
            double[] outputarray = new double[3];
            vect.CopyTo(10, outputarray, 1, 2);
            if (outputarray[0] != 0.0 || outputarray[1] != vect[10] || outputarray[2] != vect[11])
            {
                throw new Exception("CopyTo (3) test failed");
            }
        }
        {
            double[] outputarray = new double[collectionSize - 1];
            try {
                vect.CopyTo(outputarray);
                throw new Exception("CopyTo (4) test failed");
            } catch (ArgumentException) {
            }
        }
        {
            StructVector inputvector = new StructVector();
            int          arrayLen    = 10;
            for (int i = 0; i < arrayLen; i++)
            {
                inputvector.Add(new Struct(i / 10.0));
            }
            Struct[] outputarray = new Struct[arrayLen];
            inputvector.CopyTo(outputarray);
            for (int i = 0; i < arrayLen; i++)
            {
                if (outputarray[i].num != inputvector[i].num)
                {
                    throw new Exception("CopyTo (6) test failed, i:" + i);
                }
            }
            foreach (Struct s in inputvector)
            {
                s.num += 20.0;
            }
            for (int i = 0; i < arrayLen; i++)
            {
                if (outputarray[i].num + 20.0 != inputvector[i].num)
                {
                    throw new Exception("CopyTo (7) test failed (only a shallow copy was made), i:" + i);
                }
            }
        }
        {
            try {
                vect.CopyTo(null);
                throw new Exception("CopyTo (8) test failed");
            } catch (ArgumentNullException) {
            }
        }

        // Contains() test
        if (!vect.Contains(0 * 10.1))
        {
            throw new Exception("Contains test 1 failed");
        }
        if (!vect.Contains(10 * 10.1))
        {
            throw new Exception("Contains test 2 failed");
        }
        if (!vect.Contains(19 * 10.1))
        {
            throw new Exception("Contains test 3 failed");
        }
        if (vect.Contains(20 * 10.1))
        {
            throw new Exception("Contains test 4 failed");
        }

        {
            // IEnumerable constructor
            double[]     doubleArray = new double[] { 0.0, 11.1, 22.2, 33.3, 44.4, 55.5, 33.3 };
            DoubleVector dv          = new DoubleVector(doubleArray);
            if (doubleArray.Length != dv.Count)
            {
                throw new Exception("ICollection constructor length check failed: " + doubleArray.Length + "-" + dv.Count);
            }
            for (int i = 0; i < doubleArray.Length; i++)
            {
                if (doubleArray[i] != dv[i])
                {
                    throw new Exception("ICollection constructor failed, index:" + i);
                }
            }
            {
                Struct[]     structArray = new Struct[] { new Struct(0.0), new Struct(11.1), new Struct(22.2), new Struct(33.3) };
                StructVector sv          = new StructVector(structArray);
                for (int i = 0; i < structArray.Length; i++)
                {
                    structArray[i].num += 200.0;
                }
                for (int i = 0; i < structArray.Length; i++)
                {
                    if (structArray[i].num != sv[i].num + 200.0)
                    {
                        throw new Exception("ICollection constructor not a deep copy, index:" + i);
                    }
                }
            }
            try {
                new DoubleVector((System.Collections.ICollection)null);
                throw new Exception("ICollection constructor null test failed");
            } catch (ArgumentNullException) {
            }
            {
                // Collection initializer test, requires C# 3.0
//        myDoubleVector = new DoubleVector() { 123.4, 567.8, 901.2 };
            }

            // IndexOf() test
            for (int i = 0; i < collectionSize; i++)
            {
                if (vect.IndexOf(i * 10.1) != i)
                {
                    throw new Exception("IndexOf test " + i + " failed");
                }
            }
            if (vect.IndexOf(200.1) != -1)
            {
                throw new Exception("IndexOf non-existent test failed");
            }
            if (dv.IndexOf(33.3) != 3)
            {
                throw new Exception("IndexOf position test failed");
            }

            // LastIndexOf() test
            for (int i = 0; i < collectionSize; i++)
            {
                if (vect.LastIndexOf(i * 10.1) != i)
                {
                    throw new Exception("LastIndexOf test " + i + " failed");
                }
            }
            if (vect.LastIndexOf(200.1) != -1)
            {
                throw new Exception("LastIndexOf non-existent test failed");
            }
            if (dv.LastIndexOf(33.3) != 6)
            {
                throw new Exception("LastIndexOf position test failed");
            }

            // Copy constructor test
            DoubleVector dvCopy = new DoubleVector(dv);
            for (int i = 0; i < doubleArray.Length; i++)
            {
                if (doubleArray[i] != dvCopy[i])
                {
                    throw new Exception("Copy constructor failed, index:" + i);
                }
            }
            if (dvCopy.Count != doubleArray.Length)
            {
                throw new Exception("Copy constructor lengths mismatch");
            }

            // ToArray test
            double[] dvArray = dv.ToArray();
            for (int i = 0; i < doubleArray.Length; i++)
            {
                if (doubleArray[i] != dvArray[i])
                {
                    throw new Exception("ToArray failed, index:" + i);
                }
            }
            if (dvArray.Length != doubleArray.Length)
            {
                throw new Exception("ToArray lengths mismatch");
            }
        }
        {
            // Repeat() test
            try {
                myDoubleVector = DoubleVector.Repeat(77.7, -1);
                throw new Exception("Repeat negative count test failed");
            } catch (ArgumentOutOfRangeException) {
            }
            DoubleVector dv = DoubleVector.Repeat(77.7, 5);
            if (dv.Count != 5)
            {
                throw new Exception("Repeat count test failed");
            }

            // Also tests enumerator
            {
                System.Collections.IEnumerator myEnumerator = dv.GetEnumerator();
                while (myEnumerator.MoveNext())
                {
                    if ((double)myEnumerator.Current != 77.7)
                    {
                        throw new Exception("Repeat (1) test failed");
                    }
                }
            }
            {
                System.Collections.Generic.IEnumerator <double> myEnumerator = dv.GetEnumerator();
                while (myEnumerator.MoveNext())
                {
                    if (myEnumerator.Current != 77.7)
                    {
                        throw new Exception("Repeat (2) test failed");
                    }
                }
            }
        }

        {
            // InsertRange() test
            DoubleVector dvect = new DoubleVector();
            for (int i = 0; i < 5; i++)
            {
                dvect.Add(1000.0 * i);
            }
            vect.InsertRange(midCollection, dvect);
            if (vect.Count != collectionSize + dvect.Count)
            {
                throw new Exception("InsertRange test size failed");
            }

            for (int i = 0; i < midCollection; i++)
            {
                if (vect.IndexOf(i * 10.1) != i)
                {
                    throw new Exception("InsertRange (1) test " + i + " failed");
                }
            }
            for (int i = 0; i < dvect.Count; i++)
            {
                if (vect[i + midCollection] != dvect[i])
                {
                    throw new Exception("InsertRange (2) test " + i + " failed");
                }
            }
            for (int i = midCollection; i < collectionSize; i++)
            {
                if (vect.IndexOf(i * 10.1) != i + dvect.Count)
                {
                    throw new Exception("InsertRange (3) test " + i + " failed");
                }
            }
            try {
                vect.InsertRange(0, null);
                throw new Exception("InsertRange (4) test failed");
            } catch (ArgumentNullException) {
            }

            // RemoveRange() test
            vect.RemoveRange(0, 0);
            vect.RemoveRange(midCollection, dvect.Count);
            if (vect.Count != collectionSize)
            {
                throw new Exception("RemoveRange test size failed");
            }
            for (int i = 0; i < collectionSize; i++)
            {
                if (vect.IndexOf(i * 10.1) != i)
                {
                    throw new Exception("RemoveRange test " + i + " failed");
                }
            }
            try {
                vect.RemoveRange(-1, 0);
                throw new Exception("RemoveRange index out of range (1) test failed");
            } catch (ArgumentOutOfRangeException) {
            }
            try {
                vect.RemoveRange(0, -1);
                throw new Exception("RemoveRange count out of range (2) test failed");
            } catch (ArgumentOutOfRangeException) {
            }
            try {
                vect.RemoveRange(collectionSize + 1, 0);
                throw new Exception("RemoveRange index and count out of range (1) test failed");
            } catch (ArgumentException) {
            }
            try {
                vect.RemoveRange(0, collectionSize + 1);
                throw new Exception("RemoveRange index and count out of range (2) test failed");
            } catch (ArgumentException) {
            }

            // AddRange() test
            vect.AddRange(dvect);
            if (vect.Count != collectionSize + dvect.Count)
            {
                throw new Exception("AddRange test size failed");
            }
            for (int i = 0; i < collectionSize; i++)
            {
                if (vect.IndexOf(i * 10.1) != i)
                {
                    throw new Exception("AddRange (1) test " + i + " failed");
                }
            }
            for (int i = 0; i < dvect.Count; i++)
            {
                if (vect[i + collectionSize] != dvect[i])
                {
                    throw new Exception("AddRange (2) test " + i + " failed");
                }
            }
            try {
                vect.AddRange(null);
                throw new Exception("AddRange (3) test failed");
            } catch (ArgumentNullException) {
            }
            vect.RemoveRange(collectionSize, dvect.Count);

            // GetRange() test
            int          rangeSize   = 5;
            DoubleVector returnedVec = vect.GetRange(0, 0);
            returnedVec = vect.GetRange(midCollection, rangeSize);
            if (returnedVec.Count != rangeSize)
            {
                throw new Exception("GetRange test size failed");
            }
            for (int i = 0; i < rangeSize; i++)
            {
                if (returnedVec.IndexOf((i + midCollection) * 10.1) != i)
                {
                    throw new Exception("GetRange test " + i + " failed");
                }
            }
            try {
                vect.GetRange(-1, 0);
                throw new Exception("GetRange index out of range (1) test failed");
            } catch (ArgumentOutOfRangeException) {
            }
            try {
                vect.GetRange(0, -1);
                throw new Exception("GetRange count out of range (2) test failed");
            } catch (ArgumentOutOfRangeException) {
            }
            try {
                vect.GetRange(collectionSize + 1, 0);
                throw new Exception("GetRange index and count out of range (1) test failed");
            } catch (ArgumentException) {
            }
            try {
                vect.GetRange(0, collectionSize + 1);
                throw new Exception("GetRange index and count out of range (2) test failed");
            } catch (ArgumentException) {
            }
            {
                StructVector inputvector = new StructVector();
                int          arrayLen    = 10;
                for (int i = 0; i < arrayLen; i++)
                {
                    inputvector.Add(new Struct(i / 10.0));
                }
                StructVector outputvector = inputvector.GetRange(0, arrayLen);
                for (int i = 0; i < arrayLen; i++)
                {
                    if (outputvector[i].num != inputvector[i].num)
                    {
                        throw new Exception("GetRange (1) test failed, i:" + i);
                    }
                }
                foreach (Struct s in inputvector)
                {
                    s.num += 20.0;
                }
                for (int i = 0; i < arrayLen; i++)
                {
                    if (outputvector[i].num + 20.0 != inputvector[i].num)
                    {
                        throw new Exception("GetRange (2) test failed (only a shallow copy was made), i:" + i);
                    }
                }
            }
        }

        // Insert() test
        int pos   = 0;
        int count = vect.Count;

        vect.Insert(pos, -5.1);
        count++;
        if (vect.Count != count || vect[pos] != -5.1)
        {
            throw new Exception("Insert at beginning test failed");
        }

        pos = midCollection;
        vect.Insert(pos, 85.1);
        count++;
        if (vect.Count != count || vect[pos] != 85.1)
        {
            throw new Exception("Insert at " + pos + " test failed");
        }

        pos = vect.Count;
        vect.Insert(pos, 195.1);
        count++;
        if (vect.Count != count || vect[pos] != 195.1)
        {
            throw new Exception("Insert at end test failed");
        }

        pos = vect.Count + 1;
        try {
            vect.Insert(pos, 222.1); // should throw
            throw new Exception("Insert after end (1) test failed");
        } catch (ArgumentOutOfRangeException) {
        }
        if (vect.Count != count)
        {
            throw new Exception("Insert after end (2) test failed");
        }

        pos = -1;
        try {
            vect.Insert(pos, 333.1); // should throw
            throw new Exception("Insert before start (1) test failed");
        } catch (ArgumentOutOfRangeException) {
        }
        if (vect.Count != count)
        {
            throw new Exception("Insert before start (2) test failed");
        }

        // Remove() test
        vect.Remove(195.1);
        count--;
        vect.Remove(-5.1);
        count--;
        vect.Remove(85.1);
        count--;
        vect.Remove(9999.1); // element does not exist, should quietly do nothing
        if (vect.Count != count)
        {
            throw new Exception("Remove count check test failed");
        }
        for (int i = 0; i < collectionSize; i++)
        {
            if (vect[i] != i * 10.1)
            {
                throw new Exception("Remove test failed, index:" + i);
            }
        }

        // RemoveAt() test
        vect.Insert(0, -4.1);
        vect.Insert(midCollection, 84.1);
        vect.Insert(vect.Count, 194.1);
        vect.RemoveAt(vect.Count - 1);
        vect.RemoveAt(midCollection);
        vect.RemoveAt(0);
        try {
            vect.RemoveAt(-1);
            throw new Exception("RemoveAt test (1) failed");
        } catch (ArgumentOutOfRangeException) {
        }
        try {
            vect.RemoveAt(vect.Count);
            throw new Exception("RemoveAt test (2) failed");
        } catch (ArgumentOutOfRangeException) {
        }
        for (int i = 0; i < collectionSize; i++)
        {
            if (vect[i] != i * 10.1)
            {
                throw new Exception("RemoveAt test (3) failed, index:" + i);
            }
        }

        {
            // Capacity test
            try {
                myDoubleVector = new DoubleVector(-1);
                throw new Exception("constructor setting capacity (1) test failed");
            } catch (ArgumentOutOfRangeException) {
            }

            DoubleVector dv = new DoubleVector(10);
            if (dv.Capacity != 10 || dv.Count != 0)
            {
                throw new Exception("constructor setting capacity (2) test failed");
            }
            dv.Capacity = 20;
            if (dv.Capacity != 20)
            {
                throw new Exception("capacity test (1) failed");
            }
            dv.Add(1.11);
            try {
                dv.Capacity = dv.Count - 1;
                throw new Exception("capacity test (2) failed");
            } catch (ArgumentOutOfRangeException) {
            }

            // SetRange() test
            for (int i = dv.Count; i < collectionSize; i++)
            {
                dv.Add(0.0);
            }
            dv.SetRange(0, vect);
            if (dv.Count != collectionSize)
            {
                throw new Exception("SetRange count check test failed");
            }
            for (int i = 0; i < collectionSize; i++)
            {
                if (vect[i] != dv[i])
                {
                    throw new Exception("SetRange test (1) failed, index:" + i);
                }
            }
            try {
                dv.SetRange(-1, vect);
                throw new Exception("SetRange test (2) failed");
            } catch (ArgumentOutOfRangeException) {
            }
            try {
                dv.SetRange(1, vect);
                throw new Exception("SetRange test (3) failed");
            } catch (ArgumentOutOfRangeException) {
            }
            try {
                vect.SetRange(0, null);
                throw new Exception("SetRange (4) test failed");
            } catch (ArgumentNullException) {
            }

            // Reverse() test
            dv.Reverse();
            for (int i = 0; i < collectionSize; i++)
            {
                if (vect[i] != dv[collectionSize - i - 1])
                {
                    throw new Exception("Reverse test (1) failed, index:" + i);
                }
            }
            dv.Reverse(0, collectionSize);
            for (int i = 0; i < collectionSize; i++)
            {
                if (vect[i] != dv[i])
                {
                    throw new Exception("Reverse test (2) failed, index:" + i);
                }
            }
            dv.Reverse(0, 0); // should do nothing!
            for (int i = 0; i < collectionSize; i++)
            {
                if (vect[i] != dv[i])
                {
                    throw new Exception("Reverse test (3) failed, index:" + i);
                }
            }
            try {
                dv.Reverse(-1, 0);
                throw new Exception("Reverse test (4) failed");
            } catch (ArgumentOutOfRangeException) {
            }
            try {
                dv.Reverse(0, -1);
                throw new Exception("Reverse test (5) failed");
            } catch (ArgumentOutOfRangeException) {
            }
            try {
                dv.Reverse(collectionSize + 1, 0);
                throw new Exception("Reverse test (6) failed");
            } catch (ArgumentException) {
            }
            try {
                dv.Reverse(0, collectionSize + 1);
                throw new Exception("Reverse test (7) failed");
            } catch (ArgumentException) {
            }
        }

        // foreach test
        {
            int index = 0;
            foreach (double s in vect)
            {
                if (s != index * 10.1)
                {
                    throw new Exception("foreach test failed, index:" + index);
                }
                index++;
            }
        }

        // Clear() test
        vect.Clear();
        if (vect.Count != 0)
        {
            throw new Exception("Clear failed");
        }

        // Finally test the methods being wrapped
        {
            IntVector iv = new IntVector();
            for (int i = 0; i < 4; i++)
            {
                iv.Add(i);
            }

            double x = li_std_vector.average(iv);
            x           += li_std_vector.average(new IntVector(new int[] { 1, 2, 3, 4 }));
            myRealVector = li_std_vector.half(new RealVector(new float[] { 10F, 10.5F, 11F, 11.5F }));

            DoubleVector dvec = new DoubleVector();
            for (int i = 0; i < 10; i++)
            {
                dvec.Add(i / 2.0);
            }
            li_std_vector.halve_in_place(dvec);
        }

        // Dispose()
        {
            using (StructVector vs = new StructVector(new Struct[] { new Struct(0.0), new Struct(11.1) }))
                using (DoubleVector vd = new DoubleVector(new double[] { 0.0, 11.1 })) {
                }
        }

        // More wrapped methods
        {
            RealVector v0  = li_std_vector.vecreal(new RealVector());
            float      flo = 123.456f;
            v0.Add(flo);
            flo = v0[0];

            IntVector         v1 = li_std_vector.vecintptr(new IntVector());
            IntPtrVector      v2 = li_std_vector.vecintptr(new IntPtrVector());
            IntConstPtrVector v3 = li_std_vector.vecintconstptr(new IntConstPtrVector());

            v1.Add(123);
            v2.Clear();
            v3.Clear();

            StructVector         v4 = li_std_vector.vecstruct(new StructVector());
            StructPtrVector      v5 = li_std_vector.vecstructptr(new StructPtrVector());
            StructConstPtrVector v6 = li_std_vector.vecstructconstptr(new StructConstPtrVector());

            v4.Add(new Struct(123));
            v5.Add(new Struct(123));
            v6.Add(new Struct(123));
        }

        // Test vectors of pointers
        {
            StructPtrVector inputvector = new StructPtrVector();
            int             arrayLen    = 10;
            for (int i = 0; i < arrayLen; i++)
            {
                inputvector.Add(new Struct(i / 10.0));
            }
            Struct[] outputarray = new Struct[arrayLen];
            inputvector.CopyTo(outputarray);
            for (int i = 0; i < arrayLen; i++)
            {
                if (outputarray[i].num != inputvector[i].num)
                {
                    throw new Exception("StructPtrVector test (1) failed, i:" + i);
                }
            }
            foreach (Struct s in inputvector)
            {
                s.num += 20.0;
            }
            for (int i = 0; i < arrayLen; i++)
            {
                if (outputarray[i].num != 20.0 + i / 10.0)
                {
                    throw new Exception("StructPtrVector test (2) failed (a deep copy was incorrectly made), i:" + i);
                }
            }

            int             rangeSize   = 5;
            int             mid         = arrayLen / 2;
            StructPtrVector returnedVec = inputvector.GetRange(mid, rangeSize);
            for (int i = 0; i < rangeSize; i++)
            {
                if (inputvector[i + mid].num != returnedVec[i].num)
                {
                    throw new Exception("StructPtrVector test (3) failed, i:" + i);
                }
            }
        }

        // Test vectors of const pointers
        {
            StructConstPtrVector inputvector = new StructConstPtrVector();
            int arrayLen = 10;
            for (int i = 0; i < arrayLen; i++)
            {
                inputvector.Add(new Struct(i / 10.0));
            }
            Struct[] outputarray = new Struct[arrayLen];
            inputvector.CopyTo(outputarray);
            for (int i = 0; i < arrayLen; i++)
            {
                if (outputarray[i].num != inputvector[i].num)
                {
                    throw new Exception("StructConstPtrVector test (1) failed, i:" + i);
                }
            }
            foreach (Struct s in inputvector)
            {
                s.num += 20.0;
            }
            for (int i = 0; i < arrayLen; i++)
            {
                if (outputarray[i].num != 20.0 + i / 10.0)
                {
                    throw new Exception("StructConstPtrVector test (2) failed (a deep copy was incorrectly made), i:" + i);
                }
            }

            int rangeSize = 5;
            int mid       = arrayLen / 2;
            StructConstPtrVector returnedVec = inputvector.GetRange(mid, rangeSize);
            for (int i = 0; i < rangeSize; i++)
            {
                if (inputvector[i + mid].num != returnedVec[i].num)
                {
                    throw new Exception("StructConstPtrVector test (3) failed, i:" + i);
                }
            }
        }

        // Test construction
        {
            string[] one_two_three = new string[] { "one", "two", "three" };

            // Test construction from array
            {
                string[] collection = one_two_three;
                check123(new StringVector(collection));
            }

            // Test construction from IEnumerable
            {
                global::System.Collections.IEnumerable collection = one_two_three;
                check123(new StringVector(collection));
            }

            // Test construction from IEnumerable<>
            {
                global::System.Collections.Generic.IEnumerable <string> collection = one_two_three;
                check123(new StringVector(collection));
            }

            // Test construction from IList<>
            {
                global::System.Collections.Generic.IList <string> collection = one_two_three;
                check123(new StringVector(collection));
            }

            // Test construction from ICollection
            {
                global::System.Collections.ICollection collection = one_two_three;
                check123(new StringVector(collection));
            }

            // Test construction from ICollection<>
            {
                global::System.Collections.Generic.ICollection <string> collection = new global::System.Collections.Generic.List <string>(one_two_three);
                check123(new StringVector(collection));
            }
        }
    }
 /// <summary>
 ///
 /// </summary>
 /// <param name="collection"></param>
 public Enumerator(RichTextBoxRowColoringRuleCollection collection)
 {
     this.wrapped = ((System.Collections.CollectionBase)collection).GetEnumerator();
 }
        /// <summary> Rotate the ModuleSpec instance by 90 degrees (this modifies only tile
        /// and tile-component specifications).
        ///
        /// </summary>
        /// <param name="nT">Number of tiles along horizontal and vertical axis after
        /// rotation.
        ///
        /// </param>
        public virtual void  rotate90(Coord anT)
        {
            // Rotate specValType
            byte[][] tmpsvt = new byte[nTiles][];
            int      ax, ay;
            Coord    bnT = new Coord(anT.y, anT.x);

            for (int by = 0; by < bnT.y; by++)
            {
                for (int bx = 0; bx < bnT.x; bx++)
                {
                    ay = bx;
                    ax = bnT.y - by - 1;
                    tmpsvt[ay * anT.x + ax] = specValType[by * bnT.x + bx];
                }
            }
            specValType = tmpsvt;

            // Rotate tileDef
            if (tileDef != null)
            {
                System.Object[] tmptd = new System.Object[nTiles];
                for (int by = 0; by < bnT.y; by++)
                {
                    for (int bx = 0; bx < bnT.x; bx++)
                    {
                        ay = bx;
                        ax = bnT.y - by - 1;
                        tmptd[ay * anT.x + ax] = tileDef[by * bnT.x + bx];
                    }
                }
                tileDef = tmptd;
            }

            // Rotate tileCompVal
            if (tileCompVal != null && tileCompVal.Count > 0)
            {
                System.Collections.Hashtable tmptcv = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable());
                System.String tmpKey;
                System.Object tmpVal;
                int           btIdx, atIdx;
                int           i1, i2;
                int           bx, by;
                //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'"
                for (System.Collections.IEnumerator e = tileCompVal.Keys.GetEnumerator(); e.MoveNext();)
                {
                    //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'"
                    tmpKey = ((System.String)e.Current);
                    tmpVal = tileCompVal[tmpKey];
                    i1     = tmpKey.IndexOf('t');
                    i2     = tmpKey.IndexOf('c');
                    btIdx  = (System.Int32.Parse(tmpKey.Substring(i1 + 1, (i2) - (i1 + 1))));
                    bx     = btIdx % bnT.x;
                    by     = btIdx / bnT.x;
                    ay     = bx;
                    ax     = bnT.y - by - 1;
                    atIdx  = ax + ay * anT.x;
                    tmptcv["t" + atIdx + tmpKey.Substring(i2)] = tmpVal;
                }
                tileCompVal = tmptcv;
            }
        }
Example #23
0
        static void List()
        {
            String policyName = null;

            try
            {
                // creating a dp policy start element
                NaElement input = new NaElement("dp-policy-list-iter-start");
                if (Args.Length > 4)
                {
                    policyName = Args[4];
                    input.AddNewChild("dp-policy-name-or-id", policyName);
                }

                // invoke the api && capturing the records && tag values
                NaElement output = server.InvokeElem(input);


                // Extracting the record && tag values && printing them
                String records = output.GetChildContent("records");

                if (records.Equals("0"))
                {
                    Console.WriteLine("\nNo policies to display");
                }

                String tag = output.GetChildContent("tag");



                // Extracting records one at a time
                input = new NaElement("dp-policy-list-iter-next");
                input.AddNewChild("maximum", records);
                input.AddNewChild("tag", tag);
                NaElement record = server.InvokeElem(input);

                // Navigating to the dp-policy-infos child element
                NaElement stat = record.GetChildByName("dp-policy-infos");

                // Navigating to the dp-policy-info child element
                System.Collections.IList infoList = null;

                if (stat != null)
                {
                    infoList = stat.GetChildren();
                }
                if (infoList == null)
                {
                    return;
                }


                System.Collections.IEnumerator infoIter =
                    infoList.GetEnumerator();

                // Iterating through each record
                while (infoIter.MoveNext())
                {
                    String    value;
                    NaElement info = (NaElement)infoIter.Current;


                    // extracting the policy name and printing it
                    // Navigating to the dp-policy-content child element
                    NaElement policyContent =
                        info.GetChildByName("dp-policy-content");

                    // Removing non modifiable policies
                    if (policyContent.GetChildContent("name").IndexOf("NM") < 0)
                    {
                        Console.WriteLine(
                            "----------------------------------------------------");
                        value = policyContent.GetChildContent("name");
                        Console.WriteLine("Policy Name : " + value);


                        value = info.GetChildContent("id");
                        Console.WriteLine("Id : " + value);

                        value = policyContent.GetChildContent("description");
                        Console.WriteLine("Description : " + value);

                        Console.WriteLine(
                            "----------------------------------------------------");


                        // printing detials if only one policy is selected for listing
                        if (policyName != null)
                        {
                            // printing connection info
                            NaElement dpc = policyContent.
                                            GetChildByName("dp-policy-connections");
                            NaElement dpci =
                                dpc.GetChildByName("dp-policy-connection-info");

                            value = dpci.GetChildContent("backup-schedule-name");
                            Console.Write("\nBackup Schedule Name : ");
                            if (value != null)
                            {
                                Console.Write(value);
                            }

                            value = dpci.GetChildContent("backup-schedule-id");
                            Console.Write("\nBackup Schedule Id   : ");
                            if (value != null)
                            {
                                Console.WriteLine(value);
                            }

                            value = dpci.GetChildContent("id");
                            Console.WriteLine("Connection Id        : " + value);

                            value = dpci.GetChildContent("type");
                            Console.WriteLine("Connection Type      : " + value);

                            value =
                                dpci.GetChildContent("lag-warning-threshold");
                            Console.WriteLine("Lag Warning Threshold: " + value);

                            value = dpci.GetChildContent("lag-error-threshold");
                            Console.WriteLine("Lag Error Threshold  : " + value);

                            value = dpci.GetChildContent("from-node-name");
                            Console.WriteLine("From Node Name       : " + value);

                            value = dpci.GetChildContent("from-node-id");
                            Console.WriteLine("From Node Id         : " + value);

                            value = dpci.GetChildContent("to-node-name");
                            Console.WriteLine("To Node Name         : " + value);

                            value = dpci.GetChildContent("to-node-id");
                            Console.WriteLine("To Node Id           : " + value);
                        }
                    }
                }

                // invoking the iter-end zapi
                input = new NaElement("dp-policy-list-iter-end");
                input.AddNewChild("tag", tag);
                server.InvokeElem(input);
            }
            catch (NaException e) {
                //Print the error message
                Console.Error.WriteLine(e.Message);
                Environment.Exit(1);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message);
                Environment.Exit(1);
            }
        }
Example #24
0
        internal void LoadType(Type type)
        {
            if (type == null || type == typeof(object))
            {
                return;
            }

            List <PropertyInfoItem> typeProps  = null;
            List <PropertyInfo>     props      = null;
            List <Type>             innerTypes = null;

            //double-check lock pattern; optemized thread-safe
            if (!properties.ContainsKey(type.FullName) && GetPropertyTypeCategory(type) == PropertyTypeCategory.Class)
            {
                lock (locker)
                {
                    innerTypes = new List <Type>();

                    if (!properties.ContainsKey(type.FullName) && GetPropertyTypeCategory(type) == PropertyTypeCategory.Class)
                    {
                        typeProps = new List <PropertyInfoItem>();

                        // props = System.ComponentModel.TypeDescriptor.GetProperties(type.GetProperties);
                        props = type.GetProperties().Where(s => s.GetAccessors(false).Any()).ToList();
                        foreach (var prop in props)
                        {
                            var atts = prop.GetCustomAttributes(false).ToArray();
                            if (atts.OfType <NotMappedAttribute>().Any())
                            {
                                continue;
                            }

                            PropertyTypeCategory propTypeCategory = GetPropertyTypeCategory(prop.PropertyType);
                            PropertyInfoItem     propInfoItem     = new PropertyInfoItem()
                            {
                                Type          = type,
                                TypeCategory  = propTypeCategory,
                                Property      = prop,
                                PropertyName  = prop.Name,
                                PropertyType  = prop.PropertyType,
                                IsGenericType = prop.PropertyType == typeof(object),
                                IsReadOnly    = !prop.CanWrite
                            };

                            var primaryKeyAtt = atts.OfType <PrimaryKeyAttribute>().FirstOrDefault();
                            propInfoItem.IsPrimaryKey = null != primaryKeyAtt;

                            var foreignKeyAtts = atts.OfType <ForeignKeyAttribute>();
                            if (foreignKeyAtts.Any())
                            {
                                propInfoItem.ForeignKeys = foreignKeyAtts.Cast <ForeignKeyAttribute>().ToList();
                            }

                            var parentKeyAtts = atts.OfType <ParentKeyAttribute>();
                            if (parentKeyAtts.Any())
                            {
                                propInfoItem.ParentKeys = parentKeyAtts.Cast <ParentKeyAttribute>().ToList();
                            }

                            PropertyAttribute propertyAtt = atts.OfType <PropertyAttribute>().FirstOrDefault();
                            if (null != propertyAtt)
                            {
                                propInfoItem.Cascade      = propertyAtt.Cascade;
                                propInfoItem.IsAutonumber = propertyAtt.AutoNumber;
                                //propInfoItem.ForceAutoNumber = propertyAtt.OverrideAutoNumber;
                                propInfoItem.IsIndexed         = propertyAtt.Indexed;
                                propInfoItem.ValuePosition     = propertyAtt.Position;
                                propInfoItem.IdentityIncrement = propertyAtt.IdentityIncrement;
                                propInfoItem.IdentitySeed      = propertyAtt.IdentitySeed;
                            }

                            RequiredAttribute requiredAtt = atts.OfType <RequiredAttribute>().FirstOrDefault();
                            propInfoItem.IsRequired = null != requiredAtt;

                            UniqueKeyAttribute uniqueKeyAtt = atts.OfType <UniqueKeyAttribute>().FirstOrDefault();
                            propInfoItem.IsUnique = null != uniqueKeyAtt;

                            MarkupAttribute markupAtt = atts.OfType <MarkupAttribute>().FirstOrDefault();
                            propInfoItem.IsMarkup = null != markupAtt;

                            CryptoAttribute cryptoAtt = atts.OfType <CryptoAttribute>().FirstOrDefault();
                            propInfoItem.Encryption = (null != cryptoAtt) ? cryptoAtt.Method : CryptoMethod.None;

                            ChildrenAttribute childrenAtt = atts.OfType <ChildrenAttribute>().FirstOrDefault();
                            //InheritedAttribute inheritedAtt = (InheritedAttribute)atts
                            //    .FirstOrDefault(s => s.GetType() == typeof(InheritedAttribute));
                            if (null != childrenAtt)
                            {
                                propInfoItem.ReferenceType       = PropertyReferenceType.Children;
                                propInfoItem.Cascade             = CascadeOptions.Delete;
                                propInfoItem.ChildParentProperty = childrenAtt.RemoteParentProperty;
                            }

                            GenericTypePropertyAttribute genericTypeAtt = atts.OfType <GenericTypePropertyAttribute>().FirstOrDefault();
                            if (prop.PropertyType == typeof(object) && null != genericTypeAtt)
                            {
                                propInfoItem.GenericTypeProperty = genericTypeAtt.Name;
                            }

                            //setting reference type
                            if (propInfoItem.ReferenceType != PropertyReferenceType.Children)
                            {
                                if (propTypeCategory == PropertyTypeCategory.None)
                                {
                                    propInfoItem.ReferenceType = PropertyReferenceType.None;
                                }
                                else if (foreignKeyAtts.Any())
                                {
                                    if (prop.PropertyType.GetProperties()
                                        .Where(s =>
                                               s.PropertyType == type &&
                                               null != s.GetCustomAttribute <ForeignKeyAttribute>(false)).Any())
                                    {
                                        propInfoItem.ReferenceType = PropertyReferenceType.SelfForeign;
                                    }
                                    else
                                    {
                                        propInfoItem.ReferenceType = PropertyReferenceType.Foreign;
                                    }
                                }
                                else if (parentKeyAtts.Any())
                                {
                                    propInfoItem.ReferenceType = PropertyReferenceType.Parent;
                                }
                                else
                                {
                                    propInfoItem.ReferenceType = PropertyReferenceType.Reference;

                                    // PropertyDescriptorCollection propTypeProps = TypeDescriptor.GetProperties(prop.PropertyType);
                                    var propTypeProps = type.GetProperties().Where(s => s.GetAccessors(false).Any()).ToList();

                                    System.Collections.IEnumerator propTypePropsItems = propTypeProps.GetEnumerator();
                                    foreach (var propTypeProp in propTypeProps)
                                    {
                                        var propTypePropAtts = propTypeProp.GetCustomAttributes(false).ToArray();
                                        if (propTypePropAtts.OfType <PrimaryKeyAttribute>().Any())
                                        {
                                            propInfoItem.ReferenceType = PropertyReferenceType.Complex;
                                            propInfoItem.Cascade       = CascadeOptions.Delete;
                                            break;
                                        }
                                    }
                                }
                            }

                            if (propTypeCategory == PropertyTypeCategory.Array)
                            {
                                propInfoItem.CollectionItemType = prop.PropertyType.GetElementType();
                            }
                            else if (propTypeCategory == PropertyTypeCategory.GenericCollection)
                            {
                                propInfoItem.CollectionItemType = prop.PropertyType.GetGenericArguments().FirstOrDefault();
                            }

                            typeProps.Add(propInfoItem);

                            if (prop.PropertyType != type && (
                                    propTypeCategory == PropertyTypeCategory.Class ||
                                    propTypeCategory == PropertyTypeCategory.Array ||
                                    propTypeCategory == PropertyTypeCategory.GenericCollection))
                            {
                                if (prop.PropertyType.IsArray && prop.PropertyType.GetArrayRank() == 1)
                                {
                                    innerTypes.Add(prop.PropertyType.GetElementType());
                                }
                                else if (null != prop.PropertyType.GetTypeInfo().GetInterface("ICollection"))
                                {
                                    innerTypes.Add(prop.PropertyType.GetGenericArguments().FirstOrDefault());
                                }
                                else if (prop.PropertyType.GetTypeInfo().IsClass)
                                {
                                    innerTypes.Add(prop.PropertyType);
                                }
                            }
                        }

                        properties.Add(type.FullName, typeProps);

                        //if there is no PrimaryKey find a property with name Id and make it PrimaryKey
                        if (!typeProps.Any(s => s.IsPrimaryKey))
                        {
                            var primaryKeyProperty = typeProps.FirstOrDefault(s => s.PropertyName == "Id");
                            if (primaryKeyProperty != null)
                            {
                                primaryKeyProperty.IsPrimaryKey = true;
                                primaryKeyProperty.IsAutonumber = true;
                            }
                        }
                    }
                }

                //after loading all PropertyInfoItems validate them
                CheckReservedKeywords(type);

                //load types of inner reference type properties
                foreach (var innerType in innerTypes)
                {
                    LoadType(innerType);
                }
            }

            //else if (properties.ContainsKey(type.FullName))
            //{
            //    typeProps = Properties(type.FullName).ToList();
            //    props = System.ComponentModel.TypeDescriptor.GetProperties(type);
            //    foreach (PropertyDescriptor prop in props)
            //    {
            //        var propItems = typeProps.Select(s => s.Property).ToArray();
            //        if (propItems.Contains(prop))
            //            continue;

            //        var refType = GetPropertyTypeCategory(prop.PropertyType);
            //        if (refType == PropertyTypeCategory.Class ||
            //            refType == PropertyTypeCategory.Array ||
            //            refType == PropertyTypeCategory.GenericCollection)
            //        {
            //            if (prop.PropertyType.IsArray && prop.PropertyType.GetArrayRank() == 1)
            //                LoadType(prop.PropertyType.GetElementType());
            //            else if (null != prop.PropertyType.GetInterface("ICollection"))
            //                LoadType(prop.PropertyType.GetGenericArguments().FirstOrDefault());
            //            else if (prop.PropertyType.IsClass)
            //                LoadType(prop.PropertyType);
            //        }
            //    }
            //}
        }
Example #25
0
 internal StringEnumerator(StringCollection mappings)
 {
     _temp = (IEnumerable)(mappings);
     _baseEnumerator = _temp.GetEnumerator();
 }
Example #26
0
        //Temporarily commented
        //		public override void start()
        //		{
        //			if( !IsStatic)
        //			{
        //				if( broadcaster == null)
        //				{
        //					broadcaster = new MPingBroadcast(this);
        //				}
        //				if( receiver == null)
        //				{
        //					receiver = new MPingReceiver(this);
        //				}
        //
        //				broadcaster.start();
        //				receiver.start();
        //			}
        //		}
        //		public override void stop()
        //		{
        //			if(broadcaster != null)
        //			{
        //				broadcaster.stop();
        //				broadcaster = null;
        //			}
        //			if( receiver != null)
        //			{
        //				receiver.stop();
        //				receiver = null;
        //			}
        //		}

        public override void down(Event evt)
        {
            Message msg;
            long    time_to_wait, start_time;

            switch (evt.Type)
            {
            case Event.FIND_INITIAL_MBRS:      // sent by GMS layer, pass up a GET_MBRS_OK event

                //We pass this event down to tcp so that it can take some measures.
                passDown(evt);

                initial_members.Clear();
                msg = new Message(null, null, null);

                msg.putHeader(HeaderType.TCPPING, new PingHeader(PingHeader.GET_MBRS_REQ, (System.Object)local_addr, group_addr));


                // if intitial nodes have been specified and static is true, then only those
                // members will form the cluster, otherwise, nodes having the same IP Multicast and port
                // will form the cluster dyanamically.

                mbrDiscoveryInProcess = true;
                lock (members.SyncRoot)
                {
                    if (initial_hosts != null)
                    {
                        for (System.Collections.IEnumerator it = initial_hosts.GetEnumerator(); it.MoveNext();)
                        {
                            Address addr = (Address)it.Current;;
                            msg.Dest = addr;
                            if (Stack.NCacheLog.IsInfoEnabled)
                            {
                                Stack.NCacheLog.Info("[FIND_INITIAL_MBRS] sending PING request to " + msg.Dest);
                            }
                            passDown(new Event(Event.MSG_URGENT, msg.copy(), Priority.High));
                        }
                    }
                }

                if (Stack.NCacheLog.IsInfoEnabled)
                {
                    Stack.NCacheLog.Info("TcpPing.down()", "[FIND_INITIAL_MBRS] waiting for results...............");
                }
                lock (initial_members.SyncRoot)
                {
                    start_time   = (System.DateTime.Now.Ticks - 621355968000000000) / 10000;
                    time_to_wait = timeout;

                    while (initial_members.Count < num_initial_members && time_to_wait > 0)
                    {
                        try
                        {
                            if (Stack.NCacheLog.IsInfoEnabled)
                            {
                                Stack.NCacheLog.Info("TcpPing.down()", "initial_members Count: " + initial_members.Count + "initialHosts Count: " + num_initial_members);
                            }
                            if (Stack.NCacheLog.IsInfoEnabled)
                            {
                                Stack.NCacheLog.Info("TcpPing.down()", "Time to wait for next response: " + time_to_wait);
                            }

                            bool timeExpire = System.Threading.Monitor.Wait(initial_members.SyncRoot, TimeSpan.FromMilliseconds(time_to_wait));
                        }
                        catch (System.Exception e)
                        {
                            Stack.NCacheLog.Error("TCPPing.down(FIND_INITIAL_MBRS)", e.ToString());
                        }
                        time_to_wait = timeout - ((System.DateTime.Now.Ticks - 621355968000000000) / 10000 - start_time);
                    }
                    mbrDiscoveryInProcess = false;
                }
                if (Stack.NCacheLog.IsInfoEnabled)
                {
                    Stack.NCacheLog.Info("TcpPing.down()", "[FIND_INITIAL_MBRS] initial members are " + Global.CollectionToString(initial_members));
                }
                if (Stack.NCacheLog.IsInfoEnabled)
                {
                    Stack.NCacheLog.Info("TcpPing.down()", "[FIND_INITIAL_MBRS] initial members count " + initial_members.Count);
                }

                //remove those which are not functional due to twoPhaseConnect
                for (int i = initial_members.Count - 1; i >= 0; i--)
                {
                    PingRsp rsp = initial_members[i] as PingRsp;
                    if (!rsp.IsStarted)
                    {
                        initial_members.RemoveAt(i);
                    }
                }

                // 3. Send response
                passUp(new Event(Event.FIND_INITIAL_MBRS_OK, initial_members));
                break;


            case Event.TMP_VIEW:
            case Event.VIEW_CHANGE:
                System.Collections.ArrayList tmp;
                if ((tmp = ((View)evt.Arg).Members) != null)
                {
                    lock (members.SyncRoot)
                    {
                        members.Clear();
                        members.AddRange(tmp);
                    }
                }
                passDown(evt);
                break;

            /****************************After removal of NackAck *********************************/
            //TCPPING emulates a GET_DIGEST call, which is required by GMS. This is needed
            //since we have now removed NAKACK from the stack!
            case Event.GET_DIGEST:
                pbcast.Digest digest = new pbcast.Digest(members.Count);
                for (int i = 0; i < members.Count; i++)
                {
                    Address sender = (Address)members[i];
                    digest.add(sender, 0, 0);
                }
                passUp(new Event(Event.GET_DIGEST_OK, digest));
                return;

            case Event.SET_DIGEST:
                // Not needed! Just here to let you know that it is needed by GMS!
                return;

            /********************************************************************************/

            case Event.BECOME_SERVER:      // called after client has joined and is fully working group member
                if (Stack.NCacheLog.IsInfoEnabled)
                {
                    Stack.NCacheLog.Info("TcpPing.down()", "received BECOME_SERVER event");
                }
                passDown(evt);
                is_server = true;
                break;


            case Event.CONNECT:
                object[] addrs = ((object[])evt.Arg);
                group_addr      = (string)addrs[0];
                subGroup_addr   = (string)addrs[1];
                twoPhaseConnect = (bool)addrs[2];

                if (twoPhaseConnect)
                {
                    timeout = 1000;
                }
                passDown(evt);
                break;


            case Event.DISCONNECT:
                passDown(evt);
                break;

            case Event.HAS_STARTED:
                hasStarted = true;
                passDown(evt);
                break;

            default:
                passDown(evt);     // Pass on to the layer below us
                break;
            }
        }
		public QueryDefsEnumerator(System.Collections.IEnumerator _Enmtr) { Enmtr=_Enmtr; }
Example #28
0
 private VariantEnumerator(Variant.EnumType type, System.Collections.IEnumerator enumerator)
 {
     Type         = type;
     m_enumerator = enumerator;
 }
Example #29
0
 public Enumerator(AttributeDeclarationCollection collection)
 {
     this.wrapped = ((System.Collections.CollectionBase)collection).GetEnumerator();
 }
Example #30
0
        /// <summary>Returns a {@link Status} instance detailing
        /// the state of the index.
        ///
        /// </summary>
        /// <param name="onlySegments">list of specific segment names to check
        ///
        /// <p/>As this method checks every byte in the specified
        /// segments, on a large index it can take quite a long
        /// time to run.
        ///
        /// <p/><b>WARNING</b>: make sure
        /// you only call this when the index is not opened by any
        /// writer.
        /// </param>
        public virtual Status CheckIndex_Renamed_Method(System.Collections.IList onlySegments)
        {
            System.Globalization.NumberFormatInfo nf = System.Globalization.CultureInfo.CurrentCulture.NumberFormat;
            SegmentInfos sis    = new SegmentInfos();
            Status       result = new Status();

            result.dir = dir;
            try
            {
                sis.Read(dir);
            }
            catch (System.Exception t)
            {
                Msg("ERROR: could not read any segments file in directory");
                result.missingSegments = true;
                if (infoStream != null)
                {
                    infoStream.WriteLine(t.StackTrace);
                }
                return(result);
            }

            int numSegments = sis.Count;

            System.String segmentsFileName = sis.GetCurrentSegmentFileName();
            IndexInput    input            = null;

            try
            {
                input = dir.OpenInput(segmentsFileName);
            }
            catch (System.Exception t)
            {
                Msg("ERROR: could not open segments file in directory");
                if (infoStream != null)
                {
                    infoStream.WriteLine(t.StackTrace);
                }
                result.cantOpenSegments = true;
                return(result);
            }
            int format = 0;

            try
            {
                format = input.ReadInt();
            }
            catch (System.Exception t)
            {
                Msg("ERROR: could not read segment file version in directory");
                if (infoStream != null)
                {
                    infoStream.WriteLine(t.StackTrace);
                }
                result.missingSegmentVersion = true;
                return(result);
            }
            finally
            {
                if (input != null)
                {
                    input.Close();
                }
            }

            System.String sFormat = "";
            bool          skip    = false;

            if (format == SegmentInfos.FORMAT)
            {
                sFormat = "FORMAT [Lucene Pre-2.1]";
            }
            if (format == SegmentInfos.FORMAT_LOCKLESS)
            {
                sFormat = "FORMAT_LOCKLESS [Lucene 2.1]";
            }
            else if (format == SegmentInfos.FORMAT_SINGLE_NORM_FILE)
            {
                sFormat = "FORMAT_SINGLE_NORM_FILE [Lucene 2.2]";
            }
            else if (format == SegmentInfos.FORMAT_SHARED_DOC_STORE)
            {
                sFormat = "FORMAT_SHARED_DOC_STORE [Lucene 2.3]";
            }
            else
            {
                if (format == SegmentInfos.FORMAT_CHECKSUM)
                {
                    sFormat = "FORMAT_CHECKSUM [Lucene 2.4]";
                }
                else if (format == SegmentInfos.FORMAT_DEL_COUNT)
                {
                    sFormat = "FORMAT_DEL_COUNT [Lucene 2.4]";
                }
                else if (format == SegmentInfos.FORMAT_HAS_PROX)
                {
                    sFormat = "FORMAT_HAS_PROX [Lucene 2.4]";
                }
                else if (format == SegmentInfos.FORMAT_USER_DATA)
                {
                    sFormat = "FORMAT_USER_DATA [Lucene 2.9]";
                }
                else if (format == SegmentInfos.FORMAT_DIAGNOSTICS)
                {
                    sFormat = "FORMAT_DIAGNOSTICS [Lucene 2.9]";
                }
                else if (format < SegmentInfos.CURRENT_FORMAT)
                {
                    sFormat = "int=" + format + " [newer version of Lucene than this tool]";
                    skip    = true;
                }
                else
                {
                    sFormat = format + " [Lucene 1.3 or prior]";
                }
            }

            result.segmentsFileName = segmentsFileName;
            result.numSegments      = numSegments;
            result.segmentFormat    = sFormat;
            result.userData         = sis.GetUserData();
            System.String userDataString;
            if (sis.GetUserData().Count > 0)
            {
                userDataString = " userData=" + SupportClass.CollectionsHelper.CollectionToString(sis.GetUserData());
            }
            else
            {
                userDataString = "";
            }

            Msg("Segments file=" + segmentsFileName + " numSegments=" + numSegments + " version=" + sFormat + userDataString);

            if (onlySegments != null)
            {
                result.partial = true;
                if (infoStream != null)
                {
                    infoStream.Write("\nChecking only these segments:");
                }
                System.Collections.IEnumerator it = onlySegments.GetEnumerator();
                while (it.MoveNext())
                {
                    if (infoStream != null)
                    {
                        infoStream.Write(" " + it.Current);
                    }
                }
                System.Collections.IEnumerator e = onlySegments.GetEnumerator();
                while (e.MoveNext() == true)
                {
                    result.segmentsChecked.Add(e.Current);
                }
                Msg(":");
            }

            if (skip)
            {
                Msg("\nERROR: this index appears to be created by a newer version of Lucene than this tool was compiled on; please re-compile this tool on the matching version of Lucene; exiting");
                result.toolOutOfDate = true;
                return(result);
            }


            result.newSegments = (SegmentInfos)sis.Clone();
            result.newSegments.Clear();

            for (int i = 0; i < numSegments; i++)
            {
                SegmentInfo info = sis.Info(i);
                if (onlySegments != null && !onlySegments.Contains(info.name))
                {
                    continue;
                }
                Status.SegmentInfoStatus segInfoStat = new Status.SegmentInfoStatus();
                result.segmentInfos.Add(segInfoStat);
                Msg("  " + (1 + i) + " of " + numSegments + ": name=" + info.name + " docCount=" + info.docCount);
                segInfoStat.name     = info.name;
                segInfoStat.docCount = info.docCount;

                int toLoseDocCount = info.docCount;

                SegmentReader reader = null;

                try
                {
                    Msg("    compound=" + info.GetUseCompoundFile());
                    segInfoStat.compound = info.GetUseCompoundFile();
                    Msg("    hasProx=" + info.GetHasProx());
                    segInfoStat.hasProx = info.GetHasProx();
                    Msg("    numFiles=" + info.Files().Count);
                    segInfoStat.numFiles = info.Files().Count;
                    Msg(System.String.Format(nf, "    size (MB)={0:f}", new System.Object[] { (info.SizeInBytes() / (1024.0 * 1024.0)) }));
                    segInfoStat.sizeMB = info.SizeInBytes() / (1024.0 * 1024.0);
                    System.Collections.Generic.IDictionary <string, string> diagnostics = info.GetDiagnostics();
                    segInfoStat.diagnostics = diagnostics;
                    if (diagnostics.Count > 0)
                    {
                        Msg("    diagnostics = " + SupportClass.CollectionsHelper.CollectionToString(diagnostics));
                    }

                    int docStoreOffset = info.GetDocStoreOffset();
                    if (docStoreOffset != -1)
                    {
                        Msg("    docStoreOffset=" + docStoreOffset);
                        segInfoStat.docStoreOffset = docStoreOffset;
                        Msg("    docStoreSegment=" + info.GetDocStoreSegment());
                        segInfoStat.docStoreSegment = info.GetDocStoreSegment();
                        Msg("    docStoreIsCompoundFile=" + info.GetDocStoreIsCompoundFile());
                        segInfoStat.docStoreCompoundFile = info.GetDocStoreIsCompoundFile();
                    }
                    System.String delFileName = info.GetDelFileName();
                    if (delFileName == null)
                    {
                        Msg("    no deletions");
                        segInfoStat.hasDeletions = false;
                    }
                    else
                    {
                        Msg("    has deletions [delFileName=" + delFileName + "]");
                        segInfoStat.hasDeletions      = true;
                        segInfoStat.deletionsFileName = delFileName;
                    }
                    if (infoStream != null)
                    {
                        infoStream.Write("    test: open reader.........");
                    }
                    reader = SegmentReader.Get(info);

                    segInfoStat.openReaderPassed = true;

                    int numDocs = reader.NumDocs();
                    toLoseDocCount = numDocs;
                    if (reader.HasDeletions())
                    {
                        if (reader.deletedDocs.Count() != info.GetDelCount())
                        {
                            throw new System.SystemException("delete count mismatch: info=" + info.GetDelCount() + " vs deletedDocs.count()=" + reader.deletedDocs.Count());
                        }
                        if (reader.deletedDocs.Count() > reader.MaxDoc())
                        {
                            throw new System.SystemException("too many deleted docs: maxDoc()=" + reader.MaxDoc() + " vs deletedDocs.count()=" + reader.deletedDocs.Count());
                        }
                        if (info.docCount - numDocs != info.GetDelCount())
                        {
                            throw new System.SystemException("delete count mismatch: info=" + info.GetDelCount() + " vs reader=" + (info.docCount - numDocs));
                        }
                        segInfoStat.numDeleted = info.docCount - numDocs;
                        Msg("OK [" + (segInfoStat.numDeleted) + " deleted docs]");
                    }
                    else
                    {
                        if (info.GetDelCount() != 0)
                        {
                            throw new System.SystemException("delete count mismatch: info=" + info.GetDelCount() + " vs reader=" + (info.docCount - numDocs));
                        }
                        Msg("OK");
                    }
                    if (reader.MaxDoc() != info.docCount)
                    {
                        throw new System.SystemException("SegmentReader.maxDoc() " + reader.MaxDoc() + " != SegmentInfos.docCount " + info.docCount);
                    }

                    // Test getFieldNames()
                    if (infoStream != null)
                    {
                        infoStream.Write("    test: fields..............");
                    }
                    System.Collections.Generic.ICollection <string> fieldNames = reader.GetFieldNames(IndexReader.FieldOption.ALL);
                    Msg("OK [" + fieldNames.Count + " fields]");
                    segInfoStat.numFields = fieldNames.Count;

                    // Test Field Norms
                    segInfoStat.fieldNormStatus = TestFieldNorms(fieldNames, reader);

                    // Test the Term Index
                    segInfoStat.termIndexStatus = TestTermIndex(info, reader);

                    // Test Stored Fields
                    segInfoStat.storedFieldStatus = TestStoredFields(info, reader, nf);

                    // Test Term Vectors
                    segInfoStat.termVectorStatus = TestTermVectors(info, reader, nf);

                    // Rethrow the first exception we encountered
                    //  This will cause stats for failed segments to be incremented properly
                    if (segInfoStat.fieldNormStatus.error != null)
                    {
                        throw new System.SystemException("Field Norm test failed");
                    }
                    else if (segInfoStat.termIndexStatus.error != null)
                    {
                        throw new System.SystemException("Term Index test failed");
                    }
                    else if (segInfoStat.storedFieldStatus.error != null)
                    {
                        throw new System.SystemException("Stored Field test failed");
                    }
                    else if (segInfoStat.termVectorStatus.error != null)
                    {
                        throw new System.SystemException("Term Vector test failed");
                    }

                    Msg("");
                }
                catch (System.Exception t)
                {
                    Msg("FAILED");
                    System.String comment;
                    comment = "fixIndex() would remove reference to this segment";
                    Msg("    WARNING: " + comment + "; full exception:");
                    if (infoStream != null)
                    {
                        infoStream.WriteLine(t.StackTrace);
                    }
                    Msg("");
                    result.totLoseDocCount += toLoseDocCount;
                    result.numBadSegments++;
                    continue;
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }

                // Keeper
                result.newSegments.Add(info.Clone());
            }

            if (0 == result.numBadSegments)
            {
                result.clean = true;
                Msg("No problems were detected with this index.\n");
            }
            else
            {
                Msg("WARNING: " + result.numBadSegments + " broken segments (containing " + result.totLoseDocCount + " documents) detected");
            }

            return(result);
        }
Example #31
0
        public static Task <bool> LoginAsync(string username, string password)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            CancellationToken       cancellationToken = cts.Token;

            LdapConnection conn = null;


            return(Task.Factory.StartNew(() => {
                conn = new LdapConnection();
                conn.Connect(Host, Port);


                if (!string.IsNullOrEmpty(username))
                {
                    try
                    {
                        conn.Bind(dn, pa);
                    }
                    catch (Exception e)
                    {
                        conn.Disconnect();
                        return false;
                    }

                    string searchBase = filter;

                    int searchScope = LdapConnection.ScopeSub;
                    string searchFilter = "uid=" + username.Trim();
                    LdapSearchQueue queue = conn.Search(searchBase,
                                                        searchScope,
                                                        searchFilter,
                                                        null,
                                                        false,
                                                        (LdapSearchQueue)null,
                                                        (LdapSearchConstraints)null);

                    LdapMessage message;
                    while ((message = queue.GetResponse()) != null)
                    {
                        try
                        {
                            string msg = message.ToString();

                            LdapEntry entry = ((LdapSearchResult)message).Entry;

                            LdapAttributeSet attributeSet = entry.GetAttributeSet();
                            System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();

                            LdapAttribute cn = attributeSet.GetAttribute("cn");
                            string idUser = cn.StringValue;

                            try
                            {
                                conn.Bind("cn=" + idUser + "," + filter, password);
                            }
                            catch (Exception e)
                            {
                                conn.Disconnect();
                                return false;
                            }

                            conn.Disconnect();
                            return true;
                        }
                        catch (Exception e)
                        {
                            conn.Disconnect();
                            return false;
                        }
                    }
                }

                return false;
            }, cancellationToken));
        }
Example #32
0
        internal virtual SegmentReader ReopenSegment(SegmentInfo si)
        {
            lock (this)
            {
                bool deletionsUpToDate = (this.si.HasDeletions() == si.HasDeletions()) && (!si.HasDeletions() || this.si.GetDelFileName().Equals(si.GetDelFileName()));
                bool normsUpToDate     = true;


                bool[] fieldNormsChanged = new bool[fieldInfos.Size()];
                if (normsUpToDate)
                {
                    for (int i = 0; i < fieldInfos.Size(); i++)
                    {
                        if (!this.si.GetNormFileName(i).Equals(si.GetNormFileName(i)))
                        {
                            normsUpToDate        = false;
                            fieldNormsChanged[i] = true;
                        }
                    }
                }

                if (normsUpToDate && deletionsUpToDate)
                {
                    return(this);
                }


                // clone reader
                SegmentReader clone   = new SegmentReader();
                bool          success = false;
                try
                {
                    clone.directory      = directory;
                    clone.si             = si;
                    clone.segment        = segment;
                    clone.readBufferSize = readBufferSize;
                    clone.cfsReader      = cfsReader;
                    clone.storeCFSReader = storeCFSReader;

                    clone.fieldInfos            = fieldInfos;
                    clone.tis                   = tis;
                    clone.freqStream            = freqStream;
                    clone.proxStream            = proxStream;
                    clone.termVectorsReaderOrig = termVectorsReaderOrig;


                    // we have to open a new FieldsReader, because it is not thread-safe
                    // and can thus not be shared among multiple SegmentReaders
                    // TODO: Change this in case FieldsReader becomes thread-safe in the future
                    System.String fieldsSegment;

                    Directory storeDir = Directory();

                    if (si.GetDocStoreOffset() != -1)
                    {
                        fieldsSegment = si.GetDocStoreSegment();
                        if (storeCFSReader != null)
                        {
                            storeDir = storeCFSReader;
                        }
                    }
                    else
                    {
                        fieldsSegment = segment;
                        if (cfsReader != null)
                        {
                            storeDir = cfsReader;
                        }
                    }

                    if (fieldsReader != null)
                    {
                        clone.fieldsReader = new FieldsReader(storeDir, fieldsSegment, fieldInfos, readBufferSize, si.GetDocStoreOffset(), si.docCount);
                    }


                    if (!deletionsUpToDate)
                    {
                        // load deleted docs
                        clone.deletedDocs = null;
                        clone.LoadDeletedDocs();
                    }
                    else
                    {
                        clone.deletedDocs = this.deletedDocs;
                    }

                    clone.norms = new System.Collections.Hashtable();
                    if (!normsUpToDate)
                    {
                        // load norms
                        for (int i = 0; i < fieldNormsChanged.Length; i++)
                        {
                            // copy unchanged norms to the cloned reader and incRef those norms
                            if (!fieldNormsChanged[i])
                            {
                                System.String curField = fieldInfos.FieldInfo(i).name;
                                Norm          norm     = (Norm)this.norms[curField];
                                norm.IncRef();
                                clone.norms[curField] = norm;
                            }
                        }

                        clone.OpenNorms(si.GetUseCompoundFile() ? cfsReader : Directory(), readBufferSize);
                    }
                    else
                    {
                        System.Collections.IEnumerator it = norms.Keys.GetEnumerator();
                        while (it.MoveNext())
                        {
                            System.String field = (System.String)it.Current;
                            Norm          norm  = (Norm)norms[field];
                            norm.IncRef();
                            clone.norms[field] = norm;
                        }
                    }

                    if (clone.singleNormStream == null)
                    {
                        for (int i = 0; i < fieldInfos.Size(); i++)
                        {
                            FieldInfo fi = fieldInfos.FieldInfo(i);
                            if (fi.isIndexed && !fi.omitNorms)
                            {
                                Directory     d        = si.GetUseCompoundFile() ? cfsReader : Directory();
                                System.String fileName = si.GetNormFileName(fi.number);
                                if (si.HasSeparateNorms(fi.number))
                                {
                                    continue;
                                }

                                if (fileName.EndsWith("." + IndexFileNames.NORMS_EXTENSION))
                                {
                                    clone.singleNormStream = d.OpenInput(fileName, readBufferSize);
                                    break;
                                }
                            }
                        }
                    }

                    success = true;
                }
                finally
                {
                    if (this.referencedSegmentReader != null)
                    {
                        // this reader shares resources with another SegmentReader,
                        // so we increment the other readers refCount. We don't
                        // increment the refCount of the norms because we did
                        // that already for the shared norms
                        clone.referencedSegmentReader = this.referencedSegmentReader;
                        referencedSegmentReader.IncRefReaderNotNorms();
                    }
                    else
                    {
                        // this reader wasn't reopened, so we increment this
                        // readers refCount
                        clone.referencedSegmentReader = this;
                        IncRefReaderNotNorms();
                    }

                    if (!success)
                    {
                        // An exception occured during reopen, we have to decRef the norms
                        // that we incRef'ed already and close singleNormsStream and FieldsReader
                        clone.DecRef();
                    }
                }

                return(clone);
            }
        }
 internal INVCEnumerator(V2Interop.ITaskNamedValueCollection v2Coll)
 {
     this.v2CollEnum = v2Coll.GetEnumerator();
 }
Example #34
0
 internal StringEnumerator(StringCollection mappings)
 {
     _temp           = (IEnumerable)(mappings);
     _baseEnumerator = _temp.GetEnumerator();
 }
Example #35
0
 /// Stops a given coroutine.
 public void StopCoroutine(System.Collections.IEnumerator routine) =>
 Controller.Instance.StopCoroutine(routine);
		public NuGenFilterIterator(System.Collections.IEnumerator iter, NuGenFilterIterator.Predicate predicate)
		{
			this.iter = iter;
			this.predicate = predicate;
		}
        internal override ObservableCollection <object> QuerySubCollectionViewGroupList(GroupDescription childGroupBy, int nextLevel, bool nextLevelIsBottom)
        {
            string childGroupByPropertyName = DataGridCollectionViewBase.GetPropertyNameFromGroupDescription(childGroupBy);

            if (String.IsNullOrEmpty(childGroupByPropertyName))
            {
                throw new NotSupportedException("Custom groups are not supported when using a DataGridVirtualizingQueryableCollectionView.");
            }

            DataGridVirtualizingCollectionViewBase collectionView = this.GetCollectionView();

            bool sortGroupBy = false;
            ListSortDirection groupByDirection = ListSortDirection.Ascending;

            foreach (SortDescription sortDescription in collectionView.SortDescriptions)
            {
                if (sortDescription.PropertyName == childGroupByPropertyName)
                {
                    sortGroupBy      = true;
                    groupByDirection = sortDescription.Direction;
                    break;
                }
            }

            IQueryable groupsAndCountsQueryable = this.Queryable.GetSubGroupsAndCountsQueryable(childGroupByPropertyName, sortGroupBy, groupByDirection);

            List <QueryableExtensions.IQueryableGroupNameCountPair> distinctValuesAndCounts = new List <QueryableExtensions.IQueryableGroupNameCountPair>();

            try
            {
                System.Collections.IEnumerator enumerator = groupsAndCountsQueryable.GetEnumerator();

                while (enumerator.MoveNext())
                {
                    QueryableExtensions.IQueryableGroupNameCountPair current = enumerator.Current as QueryableExtensions.IQueryableGroupNameCountPair;

                    if (current != null)
                    {
                        distinctValuesAndCounts.Add(current);
                    }
                }
            }
            catch
            {
                // TimeOut exception on the connection or other.
                distinctValuesAndCounts.Clear();
            }


            // If we are not the bottom level, we should have subgroups.
            // However, if the connection timed out and the catch statement set the coundAndDistinctValues to an empty array,
            // then we shouldn't add anything.  We cannot reset on the spot since we might already be resetting.


            // Create the collection of sub CollectionViewGroups
            ObservableCollection <object> subCollectionViewGroupList = new ObservableCollection <object>();

            int runningCount        = this.StartGlobalIndex;
            int distinctValuesCount = distinctValuesAndCounts.Count;

            for (int i = 0; i < distinctValuesCount; i++)
            {
                QueryableExtensions.IQueryableGroupNameCountPair queryableGroupNameCountPair = distinctValuesAndCounts[i];

                subCollectionViewGroupList.Add(
                    new DataGridVirtualizingQueryableCollectionViewGroup(queryableGroupNameCountPair.GroupName, queryableGroupNameCountPair.Count, runningCount, this, nextLevel, nextLevelIsBottom));

                runningCount += queryableGroupNameCountPair.Count;
            }

            return(subCollectionViewGroupList);
        }
 /// <summary> Reset the internal data structures to the start at the front of the list of tokens.  Should be called
 /// if tokens were added to the list after an invocation of {@link #Next(Token)}
 /// </summary>
 /// <throws>  IOException </throws>
 public override void Reset()
 {
     iter = lst.GetEnumerator();
 }
 /// <summary>
 /// Builds enumerator
 /// </summary>
 /// <param name="collection"></param>
 public Enumerator(GraphvizLayerCollection collection)
 {
     this.wrapped = ((System.Collections.CollectionBase)collection).GetEnumerator();
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="collection"></param>
 public Enumerator(RichTextBoxRowColoringRuleCollection collection)
 {
     this.wrapped = ((System.Collections.CollectionBase)collection).GetEnumerator();
 }
		public PropertiesEnumerator(System.Collections.IEnumerator _Enmtr) { Enmtr=_Enmtr; }
		/// <summary>
		///     Enumerator constructor
		/// </summary>
		public AffixEntryEnumerator(AffixEntryCollection mappings) 
		{
			this.Local = ((System.Collections.IEnumerable)(mappings));
			this.Base = Local.GetEnumerator();
		}
			public Enumerator(RunPipeListenerCollection collection)
			{
				this.wrapped = ((System.Collections.CollectionBase)collection).GetEnumerator();
			}
Example #44
0
			public override bool Next()
			{
				if (termEnum == null)
					return false;
				
				// another term in this field?
				if (termEnum.Next() && (System.Object) termEnum.Term().Field() == (System.Object) field)
					return true; // yes, keep going
				
				termEnum.Close(); // close old termEnum
				
				// find the next field with terms, if any
				if (fieldIterator == null)
				{
                    System.Collections.Comparer comparer = System.Collections.Comparer.Default;
                    System.Collections.SortedList newList = new System.Collections.SortedList();
                    if (Enclosing_Instance.fieldToReader != null)
                    {
                        if (Enclosing_Instance.fieldToReader.Count > 0)
                        {
                            int index = 0;
                            while (comparer.Compare(Enclosing_Instance.fieldToReader.GetKey(index), field) < 0)
                                index++;
                            for (; index < Enclosing_Instance.fieldToReader.Count; index++)
                            {
                                newList.Add(Enclosing_Instance.fieldToReader.GetKey(index), Enclosing_Instance.fieldToReader[Enclosing_Instance.fieldToReader.GetKey(index)]);
                            }
                        }
                    }

                    fieldIterator = newList.Keys.GetEnumerator();
                    fieldIterator.MoveNext();
					System.Object generatedAux = fieldIterator.Current; // Skip field to get next one
				}
				while (fieldIterator.MoveNext())
				{
					field = ((System.String) fieldIterator.Current);
					termEnum = ((IndexReader) Enclosing_Instance.fieldToReader[field]).Terms(new Term(field));
					Term term = termEnum.Term();
					if (term != null && (System.Object) term.Field() == (System.Object) field)
						return true;
					else
						termEnum.Close();
				}
				
				return false; // no more fields
			}
 public Enumerator(TestTreePopulatorCollection collection)
 {
     this.wrapped = ((System.Collections.CollectionBase)collection).GetEnumerator();
 }
Example #46
0
 public static void StartCoroutine(System.Collections.IEnumerator enumerator)
 {
     GameManager.instance.StartCoroutine(enumerator);
 }
 /// <summary> Returns the next token out of the list of cached tokens</summary>
 /// <returns> The next {@link Lucene.Net.Analysis.Token} in the Sink.
 /// </returns>
 /// <throws>  IOException </throws>
 public override Token Next(/* in */ Token reusableToken)
 {
     System.Diagnostics.Debug.Assert(reusableToken != null);
     if (iter == null)
         iter = lst.GetEnumerator();
     if (iter.MoveNext())
     {
         Token nextToken = (Token) iter.Current;
         return (Token) nextToken.Clone();
     }
     return null;
 }
Example #48
0
        /// <summary>
        /// Add教学计划
        /// </summary>
        /// <param name="jiHuaBiao">计划表</param>
        /// <param name="JiaoXueJieDuan">阶段ID</param>
        /// <param name="filePath">文件</param>
        /// <returns></returns>
        public ActionResult AddAction(JiaoXueJiHuaBiao jiHuaBiao, int JiaoXueJieDuan, string filePath)
        {
            if (!string.IsNullOrEmpty(filePath))
            {
                try
                {
                    string path = AppDomain.CurrentDomain.BaseDirectory + @"/upload";
                    //保存文件的真实文件名,和全路径;
                    string savepath = Server.MapPath("~/upload/" + filePath);//上传后的文件名
                    //判断是否存在此路径
                    if (!Directory.Exists(path))
                    {
                        //创建文件夹
                        Directory.CreateDirectory(path);
                    }
                    //创建一个WorkBook对象;
                    HSSFWorkbook hSSFWorkbook;
                    using (FileStream filel = new FileStream(savepath, FileMode.Open, FileAccess.Read))
                    {
                        hSSFWorkbook = new HSSFWorkbook(filel);
                    }
                    //获取工作簿的第一个工作表
                    var sheep = hSSFWorkbook.GetSheetAt(0);
                    //获取所有的行
                    System.Collections.IEnumerator rows = sheep.GetRowEnumerator();
                    //获取标题行
                    var headerRow = sheep.GetRow(0);
                    int cellCount = headerRow.LastCellNum;

                    List <Excele> exceles = new List <Excele>();

                    for (int i = (sheep.FirstRowNum + 2); i < sheep.LastRowNum; i++)
                    {
                        var    row     = sheep.GetRow(i);
                        Excele excele2 = new Excele
                        {
                            //第一行下标为1
                            KCM = (row.GetCell(0).ToString()),
                            //第二列下标为1
                            KCID = row.GetCell(1).ToString(),

                            ZJID = row.GetCell(2).ToString(),

                            ZJM = row.GetCell(3).ToString(),

                            Count = Convert.ToInt32(row.GetCell(4).ToString()),

                            KCXH = i - 1
                        };
                        //把对象加入到集合
                        exceles.Add(excele2);
                    }
                    jiHuaBiao.JiHuaBianHaoJiBanBen = jiHuaBiao.JiHuaBianHaoJiBanBen + "_" + JiaoXueJieDuan;
                    jiHuaBiao.ShenHeRen            = jiHuaBiao.ShenHeRen + "_" + filePath;
                    BLL.JiaoXueJiHuaBiaoBLL jiaoXueJi = new BLL.JiaoXueJiHuaBiaoBLL();
                    bool error = jiaoXueJi.AddJiaoXueJihua(exceles, jiHuaBiao, JiaoXueJieDuan);
                    if (error)
                    {
                        return(Json(new { errorNo = "0", errorInfo = "导入教学计划成功" }));
                    }
                    else
                    {
                        return(Json(new { errorNo = "1", errorInfo = "导入教学计划失败" }));
                    }
                }
                catch (Exception ex)
                {
                    return(Json(new { errorNo = "1", errorInfo = ex.Message }));

                    throw ex;
                }
            }
            else
            {
                return(Json(new { errorNo = "1", errorInfo = "无上传文件,操作错误" }, JsonRequestBehavior.AllowGet));
            }
        }
Example #49
0
		public EnumeratorBase(System.Collections.IEnumerator inner)
		{
			this.inner = inner;
		}
Example #50
0
    // Sets up a web thread to download and process the contrasts
    System.Collections.IEnumerator requestContrasts()
    {
        string url = "http://3d-cardiomics.erc.monash.edu/contrast/serve.php?m=" + pieceString;

        Debug.Log(pieceString);

        WWW result = new WWW(url);

        System.Collections.IEnumerator sp = spin();
        StartCoroutine(sp);

        yield return(result);

        contrasts = result.text;

        int count = 0;

        while (contrasts.Length < 20 && count < 20)
        {
            yield return(new WaitForSeconds(2.0f));

            result = new WWW(url);
            yield return(result);

            contrasts = result.text;
            count    += 1;
        }

        // Now let's process the contrasts data
#if UNITY_EDITOR
        Debug.Log(contrasts.Length);
#endif

        if (contrasts.Length != 33)
        {
            string[] wArray = contrasts.Split("\n"[0]);

            double current;
            string line;

            for (int counter = 0; counter < wArray.Length; counter++)
            {
                line = wArray[counter];
                char     delim = ',';
                string[] cols;
                cols = line.Split(delim);

                if (cols[0] != "")
                {
                    double[] _expression = new double[5];

                    // Populate the array with values

                    for (int j = 1; j < cols.Length; j++)
                    {
                        current            = double.Parse(cols[j], CultureInfo.InvariantCulture.NumberFormat);
                        _expression[j - 1] = current; // Create a temporary array with expression values
                    }

                    values.Add(new NamedDoubleArray(cols[0].ToLower(), _expression));
                }
            }
            // Add the gene expression values to values array
            values.Sort((s1, s2) => Math.Abs(s1.Values[4]).CompareTo(Math.Abs(s2.Values[4])));

            Debug.Log(values.Count);


            csvUrl = "http://3d-cardiomics.erc.monash.edu/contrast/serve.php?m=" + pieceString + "&head=1";

            dlButton.SetActive(true);
            sortButton.SetActive(true);

            generateTable();
        }
        else
        {
            // Perform the no results function
            Debug.Log("No Results");
            cText.text = "No Results";
        }

        BC.interactable = true;

        img.SetActive(false);

        StopCoroutine(sp);
    }
 public Enumerator(LoggerConfigCollection collection)
 {
     this.wrapped = ((System.Collections.CollectionBase)collection).GetEnumerator();
 }
Example #52
0
    // Processes the clicking for contrasts
    public void click()
    {
        if (first == 2)
        {
            if (pieces2.Count > 0)
            {
                // Hide complement button
                btnComplement.SetActive(false);

                panelBig.SetActive(true);

                btnWarning.SetActive(false);
                cText.text = "Compare";
                first      = 0;

                // Delete existing pieces
                values.Clear();
                destroy();
                SH.GetComponent <Colour>().resetColour();
                getPieces();

                BC.interactable = false;
                img.SetActive(true);

                cr = requestContrasts();
                StartCoroutine(cr);
            }
            else
            {
                btnWarning.SetActive(true);
                Debug.Log("Please select some pieces for Group 2");
            }
        }
        else
        {
            if (first == 0)
            {
                dlButton.SetActive(false);
                sortButton.SetActive(false);

                cText.text = "Select Group 1 Piece(s)";
                first      = 1;
            }
            else
            {
                if (first == 1)
                {
                    if (pieces1.Count > 0)
                    {
                        btnWarning.SetActive(false);
                        cText.text = "Select Group 2 Piece(s)";

                        // Show complement button
                        btnComplement.SetActive(true);

                        first = 2;
                    }
                    else
                    {
                        btnWarning.SetActive(true);
                        Debug.Log("Please select some pieces for Group 1");
                    }
                }
            }
        }
    }
 public Enumerator(FieldDeclarationCollection collection)
 {
     this.wrapped = ((System.Collections.CollectionBase)collection).GetEnumerator();
 }
Example #54
0
 public abstract void StopCoroutine(System.Collections.IEnumerator coroutine);
Example #55
0
 public Enumerator(AllIterator list, MemberInfo info)
 {
     this.iterator = list.GetEnumerator();
     this.info = info;
 }
Example #56
0
        public bool LoadDocument(string filename, string typename, ListView parent)
        {
            this.Clear();

            if (!File.Exists(filename))
            {
                return(false);
            }

            // all windows media play formats
            if (typename == "WMP")
            {
                this.pdfViewer.Visible  = false;
                this.fileView.Visible   = false;
                this.zipView.Visible    = false;
                this.imgView.Visible    = false;
                this.docView.Visible    = false;
                this.webBrowser.Visible = false;
                if (this.b_cfw)
                {
                    this.axWMP.Visible           = false;
                    this.videoPlayerCtl.URL      = filename;
                    this.videoPlayerCtl.Location = new System.Drawing.Point(this.ClientRectangle.X, this.ClientRectangle.Y);
                    this.videoPlayerCtl.Size     = this.Size;
                    this.videoPlayerCtl.Visible  = true;
                    return(true);
                }
                if (this.b_wmp)
                {
                    this.videoPlayerCtl.Visible = false;
                    this.axWMP.URL     = filename;
                    this.axWMP.Visible = true;
                    this.axWMP.Dock    = DockStyle.Fill;
                    return(true);
                }
            }

            // in case something goes wrong, we allow to fallback to b_asis and show the binary content
            bool asisTmp = this.b_asis;

            // ext drives most of the things
            string ext = System.IO.Path.GetExtension(filename).ToLower();

            // all music
            if ((".mp3.wav.flac".IndexOf(ext) != -1) && this.b_mp3)
            {
                try {
                    this.pdfViewer.Visible      = false;
                    this.fileView.Visible       = false;
                    this.zipView.Visible        = false;
                    this.imgView.Visible        = false;
                    this.webBrowser.Visible     = false;
                    this.videoPlayerCtl.Visible = false;
                    this.docView.Visible        = false;
                    this.axWMP.Visible          = true;
                    this.axWMP.Dock             = DockStyle.Fill;
                    this.axWMP.URL = filename;
                    asisTmp        = false;
                } catch (System.Exception) {
                    asisTmp = true;
                }
            }

            // initially I only found a way to convert Word to html (which is done here), other MSO Files conversations were found later and appear in the HTML section
            if ((".rtf.doc.docx".IndexOf(ext) != -1) && this.b_doc)
            {
                try {
                    this.pdfViewer.Visible      = false;
                    this.fileView.Visible       = false;
                    this.zipView.Visible        = false;
                    this.imgView.Visible        = false;
                    this.webBrowser.Visible     = false;
                    this.videoPlayerCtl.Visible = false;
                    this.axWMP.Visible          = false;
                    this.docView.LoadDocument(filename);
                    this.docView.Visible = true;
                    asisTmp = false;
                } catch (System.Exception) {
                    asisTmp = true;
                }
            }
            else
            {
                // images
                if ((".ico.bmp.tif.jpg.jpeg.wmf.gif.png.exif.emf.tiff".IndexOf(ext) != -1) && this.b_img)
                {
                    try {
                        this.pdfViewer.Visible      = false;
                        this.fileView.Visible       = false;
                        this.zipView.Visible        = false;
                        this.webBrowser.Visible     = false;
                        this.docView.Visible        = false;
                        this.videoPlayerCtl.Visible = false;
                        this.axWMP.Visible          = false;
                        this.imgView.Visible        = true;
                        this.imgView.LoadDocument(filename, parent);
                        asisTmp = false;
                    } catch (System.Exception) {
                        asisTmp = true;
                    }
                }
                else
                {
                    // PDF and PowerPoint
                    if ((".pdf.ppt.pptx.pptm.odp".IndexOf(ext) != -1) && (this.b_pdf || this.b_doc))
                    {
                        // powerpoint formats via powerpoint interop converted to pdf
                        if ((".ppt.pptx.pptm.odp".IndexOf(ext) != -1) && this.b_doc)
                        {
                            string outpath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "temp.pdf");
                            if (System.IO.File.Exists(outpath))
                            {
                                System.IO.File.Delete(outpath);
                            }
                            try {
                                Microsoft.Office.Interop.PowerPoint.Application   app  = new Microsoft.Office.Interop.PowerPoint.Application();
                                Microsoft.Office.Interop.PowerPoint.Presentations pres = app.Presentations;
                                Microsoft.Office.Interop.PowerPoint.Presentation  file = pres.Open(filename, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse);
                                file.SaveCopyAs(outpath, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF, Microsoft.Office.Core.MsoTriState.msoTrue);
                                app.Quit();
                                filename = outpath;
                                asisTmp  = false;
                            } catch (Exception) {
                                asisTmp = true;
                            }
                        }

                        // show pdf
                        try {
                            this.pdfViewer.ZoomMode = PdfViewerZoomMode.FitWidth;
                            PdfDocument pdoc = PdfDocument.Load(filename);
                            this.pdfViewer.Document     = pdoc;
                            this.fileView.Visible       = false;
                            this.zipView.Visible        = false;
                            this.imgView.Visible        = false;
                            this.webBrowser.Visible     = false;
                            this.docView.Visible        = false;
                            this.videoPlayerCtl.Visible = false;
                            this.axWMP.Visible          = false;
                            this.pdfViewer.Visible      = true;
                            asisTmp = false;
                        } catch (Exception) {
                            asisTmp = true;
                        }
                    }
                    else
                    {
                        // ZIP-Viewer simply shows the content of zip file
                        if ((".zip".IndexOf(ext) != -1) && this.b_zip)
                        {
                            try {
                                this.zipView.LoadZip(filename);
                                this.pdfViewer.Visible      = false;
                                this.fileView.Visible       = false;
                                this.imgView.Visible        = false;
                                this.webBrowser.Visible     = false;
                                this.docView.Visible        = false;
                                this.videoPlayerCtl.Visible = false;
                                this.axWMP.Visible          = false;
                                this.zipView.Visible        = true;
                                asisTmp = false;
                            } catch (Exception) {
                                asisTmp = true;
                            }
                        }
                        else
                        {
                            // collector for everything, which could be converted into HTML
                            if ((".htm.html.msg.eml.mht.xls.xlsx.xlsb.xlsm.vsd.vsdx.vsdm" /*.mpp.mpx"*/.IndexOf(ext) != -1) && (this.b_htm || this.b_doc))
                            {
                                // visio via visio interop to html
                                if ((".vsd.vsdx.vsdm".IndexOf(ext) != -1) && this.b_doc)
                                {
                                    string outpath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "temp.html");
                                    if (System.IO.File.Exists(outpath))
                                    {
                                        System.IO.File.Delete(outpath);
                                    }

                                    asisTmp = true;
                                    try {
                                        Microsoft.Office.Interop.Visio.IVInvisibleApp visio = null;
                                        visio = new Microsoft.Office.Interop.Visio.InvisibleApp();
                                        Microsoft.Office.Interop.Visio.SaveAsWeb.VisSaveAsWeb saveAsWeb = (Microsoft.Office.Interop.Visio.SaveAsWeb.VisSaveAsWeb)visio.Application.SaveAsWebObject;
                                        saveAsWeb.AttachToVisioDoc(visio.Documents.OpenEx(filename, (short)Microsoft.Office.Interop.Visio.VisOpenSaveArgs.visOpenRO));
                                        Microsoft.Office.Interop.Visio.SaveAsWeb.VisWebPageSettings webPageSettings = (Microsoft.Office.Interop.Visio.SaveAsWeb.VisWebPageSettings)saveAsWeb.WebPageSettings;

                                        webPageSettings.TargetPath    = outpath;
                                        webPageSettings.PageTitle     = outpath;
                                        webPageSettings.DispScreenRes = Microsoft.Office.Interop.Visio.SaveAsWeb.VISWEB_DISP_RES.res768x1024;
                                        webPageSettings.QuietMode     = 1;
                                        webPageSettings.SilentMode    = 1;
                                        webPageSettings.NavBar        = 1;
                                        webPageSettings.PanAndZoom    = 1;
                                        webPageSettings.Search        = 1;
                                        webPageSettings.OpenBrowser   = 0;
                                        webPageSettings.PropControl   = 0;

                                        saveAsWeb.CreatePages();

                                        this.webBrowser.Navigate(outpath);
                                        asisTmp = false;
                                    } catch (Exception) {
                                        asisTmp = true;
                                    }
                                }

                                // MS Project formats via project interop to xls:
                                // - not working with 2003 Interops on a system running MS-Project 2003 (--> 2003 converter is shown)
                                // - not working with 2007 Interops on a system running MS-Project 2003 (--> no html support in 2003)
                                //if ((".mpp.mpx".IndexOf(ext) != -1) && b_doc) {
                                //    string outpath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "temp.xls");
                                //    if (System.IO.File.Exists(outpath)) {
                                //        System.IO.File.Delete(outpath);
                                //    }

                                //    asisTmp = true;
                                //    try {
                                //        var app = new Microsoft.Office.Interop.MSProject.Application();
                                //        app.Visible = false;
                                //        var proj = app.ActiveProject;
                                //        app.FileOpenx(filename, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.MSProject.PjPoolOpen.pjPoolReadOnly, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                                //        //app.FileOpenEx(filename, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.MSProject.PjPoolOpen.pjPoolReadOnly, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                                //        // save MS-Project as Excel file (MS-Project interopt has no HTML exporter) and let Excel viewer do the job
                                //        proj.SaveAs(outpath, PjFileFormat.pjXLS, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                                //        app.Quit(Microsoft.Office.Interop.MSProject.PjSaveType.pjDoNotSave);
                                //        // set temporary Excel filename as "real" filename --> let Excel viewer do the work
                                //        filename = outpath;
                                //        // adjust extension --> let Excel viewer do the work
                                //        ext = System.IO.Path.GetExtension(filename).ToLower();
                                //        asisTmp = false;
                                //    } catch (System.Reflection.TargetInvocationException x) {
                                //        asisTmp = true;
                                //    }
                                //}

                                // excel formats via excel interop to html
                                if ((".xls.xlsx.xlsb.xlsm".IndexOf(ext) != -1) && this.b_doc)
                                {
                                    string outpath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "temp.html");
                                    if (System.IO.File.Exists(outpath))
                                    {
                                        System.IO.File.Delete(outpath);
                                    }
                                    this.Cursor = Cursors.WaitCursor;
                                    try {
                                        // http://www.codeproject.com/Articles/507068/Microsoft-Interop-API-to-convert-the-doc-docx-dot
                                        Microsoft.Office.Interop.Excel.Application excel = null;
                                        Microsoft.Office.Interop.Excel.Workbook    xls   = null;
                                        excel = new Microsoft.Office.Interop.Excel.Application();
                                        object missing    = Type.Missing;
                                        object trueObject = true;
                                        excel.Visible       = false;
                                        excel.DisplayAlerts = false;
                                        xls = excel.Workbooks.Open(filename, missing, trueObject, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                                        object format = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;
                                        System.Collections.IEnumerator wsEnumerator = excel.ActiveWorkbook.Worksheets.GetEnumerator();
                                        while (wsEnumerator.MoveNext())
                                        {
                                            this.Cursor = Cursors.WaitCursor;
                                            Microsoft.Office.Interop.Excel.Workbook wsCurrent = xls;
                                            wsCurrent.SaveAs(outpath, format, missing, missing, missing, missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
                                        }
                                        excel.Quit();
                                        this.webBrowser.Navigate(outpath);
                                        asisTmp = false;
                                    } catch (Exception cex) {
                                        GrzTools.AutoMessageBox.Show(cex.Message, "Exception", 2000);
                                        asisTmp = true;
                                    }
                                    Cursor.Current = Cursors.Default;
                                }

                                // msg files are converted via MsgReader to html
                                if (".msg".IndexOf(ext) != -1)
                                {
                                    try {
                                        string body      = "";
                                        Reader msgReader = new Reader();
                                        using (StreamReader streamReader = new StreamReader(filename)) {
                                            body = msgReader.ExtractMsgEmailBody(streamReader.BaseStream, true, "text/html; charset=utf-8");
                                        }
                                        this.webBrowser.DocumentText = body;
                                        asisTmp = false;
                                    } catch (Exception) {
                                        asisTmp = true;
                                    }
                                }

                                // html-style formatted files
                                if ((".htm.html.eml.mht".IndexOf(ext) != -1) && this.b_htm)
                                {
                                    this.webBrowser.Url = new Uri(filename);
                                    asisTmp             = false;
                                }
                                if (!asisTmp)
                                {
                                    this.pdfViewer.Visible      = false;
                                    this.fileView.Visible       = false;
                                    this.zipView.Visible        = false;
                                    this.imgView.Visible        = false;
                                    this.docView.Visible        = false;
                                    this.axWMP.Visible          = false;
                                    this.videoPlayerCtl.Visible = false;
                                    this.webBrowser.Visible     = true;
                                }
                            }
                        }
                    }
                }
            }

            // standard file view
            if (asisTmp)
            {
                this.fileView.LoadDocument(null, filename, parent);
                this.pdfViewer.Visible      = false;
                this.zipView.Visible        = false;
                this.imgView.Visible        = false;
                this.webBrowser.Visible     = false;
                this.docView.Visible        = false;
                this.videoPlayerCtl.Visible = false;
                this.axWMP.Visible          = false;
                this.fileView.Visible       = true;
            }

            return(true);
        }
Example #57
0
			/// <summary>
			/// 
			/// </summary>
			/// <param name="collection"></param>
			public Enumerator(CellCollection collection)
			{
				this.wrapped = ((System.Collections.CollectionBase)collection).GetEnumerator();
			}
 /// <summary> Reset the internal data structures to the start at the front of the list of tokens.  Should be called
 /// if tokens were added to the list after an invocation of {@link #Next(Token)}
 /// </summary>
 /// <throws>  IOException </throws>
 public override void  Reset()
 {
     iter = lst.GetEnumerator();
 }
Example #59
0
 public Enumerator(PropertyDeclarationCollection collection)
 {
     this.wrapped = ((System.Collections.CollectionBase)collection).GetEnumerator();
 }
Example #60
0
        public static Task <bool> ModifyAsync(string oldUsername, string username, string password, string nombre, string apellido, string email)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            CancellationToken       cancellationToken = cts.Token;

            LdapConnection conn = null;


            return(Task.Factory.StartNew(() => {
                conn = new LdapConnection();
                conn.Connect(Host, Port);

                if (!string.IsNullOrEmpty(username))
                {
                    try
                    {
                        conn.Bind(dn, pa);
                    }
                    catch (Exception e)
                    {
                        conn.Disconnect();
                        return false;
                    }

                    string searchBase = filter;

                    int searchScope = LdapConnection.ScopeSub;
                    string searchFilter = "uid=" + username.Trim();
                    LdapSearchQueue queue = conn.Search(searchBase,
                                                        searchScope,
                                                        searchFilter,
                                                        null,
                                                        false,
                                                        (LdapSearchQueue)null,
                                                        (LdapSearchConstraints)null);

                    LdapMessage message;
                    while ((message = queue.GetResponse()) != null)
                    {
                        try
                        {
                            string msg = message.ToString();

                            LdapEntry entry = ((LdapSearchResult)message).Entry;

                            LdapAttributeSet attributeSet = entry.GetAttributeSet();
                            System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();

                            LdapAttribute cn = attributeSet.GetAttribute("cn");
                            string idUser = cn.StringValue;

                            try
                            {
                                conn.Delete("cn=" + idUser + "," + filter);


                                LdapAttributeSet ldapAttributeSet = new LdapAttributeSet();
                                ldapAttributeSet.Add(new LdapAttribute("cn", nombre + " " + apellido));
                                ldapAttributeSet.Add(new LdapAttribute("sn", nombre));
                                ldapAttributeSet.Add(new LdapAttribute("homeDirectory", "/home/users/" + username));
                                ldapAttributeSet.Add(new LdapAttribute("objectClass", new string[] { "inetOrgPerson", "posixAccount", "top" }));
                                ldapAttributeSet.Add(new LdapAttribute("uid", username));
                                ldapAttributeSet.Add(new LdapAttribute("givenName", nombre));
                                ldapAttributeSet.Add(new LdapAttribute("uidNumber", "1000"));
                                ldapAttributeSet.Add(new LdapAttribute("gidNumber", "500"));
                                ldapAttributeSet.Add(new LdapAttribute("mail", email));
                                ldapAttributeSet.Add(new LdapAttribute("userPassword", password));

                                LdapEntry ldapEntry = new LdapEntry("cn=" + nombre + " " + apellido + "," + filter, ldapAttributeSet);

                                conn.Add(ldapEntry);
                            }
                            catch (Exception e)
                            {
                                conn.Disconnect();
                                return false;
                            }

                            conn.Disconnect();
                            return true;
                        }
                        catch (Exception e)
                        {
                            conn.Disconnect();
                            return false;
                        }
                    }
                }

                return false;
            }, cancellationToken));
        }