Exemple #1
0
 private void uiCommandManager1_CommandMouseHover(object sender, Janus.Windows.UI.CommandBars.CommandEventArgs e)
 {
     try
     {
         if (e.Command.Key == "cmdBack")
         {
             if (e.Command.Enabled == Janus.Windows.UI.InheritableBoolean.True)
             {
                 int CurrentSeriesId  = (int)SeriesStack.Pop();
                 int PreviousSeriesId = (int)SeriesStack.Peek();
                 lmDatasets.ActivityConfig.SeriesRow[] sra = (lmDatasets.ActivityConfig.SeriesRow[])atmng.acMng.DB.Series.Select("SeriesId=" + PreviousSeriesId);
                 //lmDatasets.ActivityConfig.SeriesRow sr = atmng.acMng.GetSeries().Load(PreviousSeriesId);
                 atriumBE.FileManager FMforTranslation = atmng.GetFile();
                 e.Command.ToolTipText = sra[0][UIHelper.Translate(FMforTranslation, "SeriesDescEng")].ToString();
                 SeriesStack.Push(CurrentSeriesId);
             }
             else
             {
                 e.Command.ToolTipText = "";
             }
         }
     }
     catch (Exception x)
     {
         UIHelper.HandleUIException(x);
     }
 }
Exemple #2
0
 public T CurrentContextIfNone <T>(Func <T> IfNone) where T : FAMIX.Entity
 {
     if (stack.Count == 0 || !(stack.Peek() is T))
     {
         return(IfNone());
     }
     return(stack.Peek() as T);
 }
        /// <summary> Here's where the good stuff happens...
        ///
        /// 1. If we get an open parenthesis or open bracket, then we push it.
        /// 2. If we get a close parenthesis or close bracket, the we pop the stack
        /// growing our tree, until we find an open parenthesis or open bracket.
        /// The type must match, e.g. if we are processing a close parenthesis
        /// but encounter an open bracket, that indicates a syntax error in the
        /// expression, and we throw an exception.
        /// 3. If our op has lower precedence then the current TOS op
        /// we grow the tree and repeat (3).
        ///
        /// Note we are using a trick, whereby the opType constants
        /// are number in order of precedence (that is lower precedence
        /// = lower numeric value).  The exception to this rule is
        /// the open parenthesis which is highest precedence but is
        /// lowest numerically.  This is to allow (3) to work correctly,
        /// since we want to make sure that a open parenthesis only gets
        /// popped by a close parenthesis.
        /// </summary>
        private void  addOp(Operator opType)
        {
            if (opType == Operator.OPEN_PAREN)
            {
                m_opStack.Push(opType);
            }
            else if (opType == Operator.OPEN_BRACKET)
            {
                // This is tricky: for an array index, e.g. "a[k]", we treat it
                // like "a SUBSCRIPT k".  So first we push SUBSCRIPT, and
                // then we push the open-bracket op.
                addOp(Operator.SUBSCRIPT);                 // recursive call
                m_opStack.Push(opType);
            }
            else if (opType == Operator.CLOSE_PAREN || opType == Operator.CLOSE_BRACKET)
            {
                Operator openingOpType;

                if (opType == Operator.CLOSE_PAREN)
                {
                    openingOpType = Operator.OPEN_PAREN;
                }
                else
                {
                    openingOpType = Operator.OPEN_BRACKET;
                }

                while (m_opStack.Peek() != Operator.OPEN_PAREN && m_opStack.Peek() != Operator.OPEN_BRACKET)
                {
                    popOperation();
                }

                // If we saw "(x]" or "[x)", then indicate a syntax error
                if (m_opStack.Peek() != openingOpType)
                {
                    throw new ParseException(LocalizationManager.getLocalizedTextString("key1"), m_parsePos); //$NON-NLS-1$
                }
                popOperation();                                                                               // pop the "(" or "["
            }
            else
            {
                while (m_opStack.Count != 0 && ((Operator)m_opStack.Peek()).precedence >= opType.precedence)
                {
                    popOperation();
                }

                m_opStack.Push(opType);
            }
        }
Exemple #4
0
        //brute force 100% correct
        public int solution(int[] A, int[] B)
        {
            System.Collections.Stack st = new System.Collections.Stack();
            int count = 0;

            for (int i = 0; i < A.Length; i++)
            {
                if (B[i] == 1)
                {
                    st.Push(i);
                }
                else
                {
                    while (st.Count > 0)
                    {
                        if (A[(int)st.Peek()] < A[i])
                        {
                            st.Pop();
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (st.Count == 0)
                    {
                        count++;
                    }
                }
            }


            return(count + st.Count);
        }
        /// <summary>
        /// Adds LT(1) to the current parse subtree.
        /// </summary>
        /// <remarks>
        /// <para>
        /// Note that the match() routines add the node before checking for
        /// correct match.  This means that, upon mismatched token, there
        /// will a token node in the tree corresponding to where that token
        /// was expected.  For no viable alternative errors, no node will
        /// be in the tree as nothing was matched() (the lookahead failed
        /// to predict an alternative).
        /// </para>
        /// </remarks>
        protected void addCurrentTokenToParseTree()                     // throws TokenStreamException
        {
            if (inputState.guessing > 0)
            {
                return;
            }
            ParseTreeRule  root      = (ParseTreeRule)currentParseTreeRoot.Peek();
            ParseTreeToken tokenNode = null;

            if (LA(1) == Token.EOF_TYPE)
            {
                tokenNode = new ParseTreeToken(new antlr.CommonToken("EOF"));
            }
            else
            {
                tokenNode = new ParseTreeToken(LT(1));
            }
            root.addChild(tokenNode);
        }
Exemple #6
0
        public System.Data.SqlClient.SqlCommand CreateSqlCommand(String sqlStatement)
        {
            System.Data.SqlClient.SqlTransaction peekTransaction;

            if (sqlTransactions.Count > 0)
            {
                // use the open transaction to wrap the command

                peekTransaction = (System.Data.SqlClient.SqlTransaction)(sqlTransactions.Peek());

                return(new System.Data.SqlClient.SqlCommand(sqlStatement, sqlConnection, peekTransaction));
            } // end if (sqlTransactions.Count > 0)

            else
            {
                // no open transactions, just return command object

                return(new System.Data.SqlClient.SqlCommand(sqlStatement, sqlConnection));
            } // end if else
        }     // CreateSqlCommand
Exemple #7
0
 private Cargo getLastCargoItem() //returns last item from storage without removing it.
 {
     if (Storage.Count > 0)
     {
         Cargo item = (Cargo)Storage.Peek();
         return(item);
     }
     else
     {
         return(null);
     }
 }
Exemple #8
0
        static void Main(string[] args)
        {
            System.Collections.Stack stack = new System.Collections.Stack();
            stack.Push(1);
            stack.Push(2);
            stack.Push(3);

            Console.WriteLine("1 in stack:{0}", stack.Contains(1));
            Console.WriteLine("Remove 1:{0}", stack.Pop());
            Console.WriteLine("Peek1:{0}", stack.Peek());

            object[] numArray = stack.ToArray();
            Console.WriteLine(string.Join(", ", numArray));
        }
        public override Tag CreateTag(TagData tagData, CompositeTagData compositeTagData)
        {
            string formUrl = ExtractFormLocn(compositeTagData.StartTag, tagData.UrlBeingParsed);

            if (formUrl != null && formUrl.Length > 0)
            {
                compositeTagData.StartTag["ACTION"] = formUrl;
            }
            if (!(stack.Count == 0) && (this == stack.Peek()))
            {
                stack.Pop();
            }
            return(new FormTag(tagData, compositeTagData));
        }
Exemple #10
0
        static void Main(string[] args)
        {
            System.Collections.Stack stack = new System.Collections.Stack();
            stack.Push("Fine");
            stack.Push("Does");
            stack.Push("Boy");
            stack.Push("Good");
            stack.Push("Every");

            Console.WriteLine("Peek returns {0}", stack.Peek());
            while (stack.Count > 0)
            {
                Console.WriteLine(stack.Pop());
            }
        }
Exemple #11
0
        /// <summary> This is the logic that decides when a bullet tag can be allowed
        /// </summary>
        public override bool ShouldCreateEndTagAndExit()
        {
            if (ulli.Count == 0)
            {
                return(false);
            }
            CompositeTagScanner parentScanner = (CompositeTagScanner)ulli.Peek();

            if (parentScanner == this)
            {
                ulli.Pop();
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemple #12
0
 private void button22_Click(object sender, EventArgs e)
 {
     if (st.Count > 1)
     {
         st.Pop();
         textBox1.Text = Convert.ToString(st.Peek());
         var i = richTextBox1.Text.LastIndexOf("\n");
         if (i > -1)
         {
             richTextBox1.SelectionStart  = i;
             richTextBox1.SelectionLength = richTextBox1.Text.Length - i + 1;
             richTextBox1.SelectedText    = "";
         }
     }
     else
     {
         textBox1.Text = Convert.ToString(0);
     }
 }
Exemple #13
0
        private List <Category> GetCategoryTree(List <Category> list, int pid)
        {
            List <Category> tree = new List <Category>();

            System.Collections.Stack task = new System.Collections.Stack();
            task.Push(pid);
            int level = 0;

            while (task.Count > 0)
            {
                bool flag = false;
                for (int i = 0; i < list.Count; i++)
                {
                    var l = list[i];
                    if (l.PId == pid)
                    {
                        task.Push(l.CId);
                        pid      = l.CId;
                        l.CLevel = level.ToString();
                        tree.Add(l);
                        list.Remove(l);
                        i--;
                        level++;
                        flag = true;
                    }
                }
                if (!flag)
                {
                    task.Pop();
                    level--;
                    if (task.Count > 0)
                    {
                        pid = Convert.ToInt32(task.Peek());
                    }
                }
            }
            return(tree);
        }
Exemple #14
0
        public static bool verifyPopFromPush(double[] push, double[] pop)
        {
            int index_push = 0;
            int index_pop = 0;
            System.Collections.Stack s = new System.Collections.Stack();

            while (true)
            {
                while (s.Count == 0 || pop[index_pop] != (double)s.Peek())
                {
                    if (index_push > push.Length - 1)
                    {
                        break;
                    }
                    s.Push(push[index_push]);
                    index_push++;

                }

                if ((double)s.Pop() != pop[index_pop])
                {
                    break;
                }
                index_pop++;
                if (index_pop > pop.Length - 1)
                {
                    break;
                }

            }

            if (index_push == push.Length && index_pop == pop.Length && s.Count == 0)
            {
                return true;
            }

            return false;
        }
Exemple #15
0
        public static bool verifyPopFromPush(double[] push, double[] pop)
        {
            int index_push = 0;
            int index_pop  = 0;

            System.Collections.Stack s = new System.Collections.Stack();

            while (true)
            {
                while (s.Count == 0 || pop[index_pop] != (double)s.Peek())
                {
                    if (index_push > push.Length - 1)
                    {
                        break;
                    }
                    s.Push(push[index_push]);
                    index_push++;
                }

                if ((double)s.Pop() != pop[index_pop])
                {
                    break;
                }
                index_pop++;
                if (index_pop > pop.Length - 1)
                {
                    break;
                }
            }

            if (index_push == push.Length && index_pop == pop.Length && s.Count == 0)
            {
                return(true);
            }

            return(false);
        }
Exemple #16
0
        /// <summary>
        /// Создает  массив, в котором располагаются операторы и символы представленные в обратной польской записи (безскобочной)
        /// На этом же этапе отлавливаются почти все остальные ошибки (см код). По сути - это компиляция.
        /// </summary>
        /// <returns>массив обратной польской записи</returns>
        public static System.Collections.ArrayList CreateStack()
        {
            //Собственно результирующий массив
            System.Collections.ArrayList strarr = new System.Collections.ArrayList(30);
            //Стек с операторами где они временно храняться
            System.Collections.Stack operators = new System.Collections.Stack(15);
            string expr = expression;

            //пооператорная обработка выражения
            while (expr != "")
            {
                string op = expr.Substring(0, expr.IndexOf(" "));
                expr = expr.Substring(expr.IndexOf(" ") + 1);
                switch (op)
                {
                case "(":     //1
                {
                    //Кладем в стэк
                    operators.Push(op);
                    break;
                }

                case "m":     //4
                {
                    //вытаскиваем из стека все операторы чей приоритет больше либо равен унарному минусу

                    /*while (operators.Count != 0 && (operators.Peek().ToString() == "m" || operators.Peek().ToString() == "p"))
                     * {
                     *  if (strarr.Capacity > strarr.Count)
                     *  {
                     *      strarr.Add(operators.Pop());
                     *  }
                     *  else
                     *  {
                     *      // переполнгение стека - возвращем null
                     *      return null;
                     *  }
                     * }*/
                    operators.Push(op);
                    break;
                }

                case "p":     //4
                {
                    /*while (operators.Count != 0 && (operators.Peek().ToString() == "m" || operators.Peek().ToString() == "p"))
                     * {
                     *  if (strarr.Capacity > strarr.Count)
                     *  {
                     *      strarr.Add(operators.Pop());
                     *  }
                     *  else
                     *  {
                     *      return null;
                     *  }
                     * }*/
                    operators.Push(op);
                    break;
                }

                case "*":     //3
                {
                    while (operators.Count != 0 && (operators.Peek().ToString() == "*" || operators.Peek().ToString() == "/" || operators.Peek().ToString() == "mod" || operators.Peek().ToString() == "m" || operators.Peek().ToString() == "p"))
                    {
                        if (strarr.Capacity > strarr.Count)
                        {
                            strarr.Add(operators.Pop());
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    operators.Push(op);
                    break;
                }

                case "/":     //3
                {
                    while (operators.Count != 0 && (operators.Peek().ToString() == "*" || operators.Peek().ToString() == "/" || operators.Peek().ToString() == "mod" || operators.Peek().ToString() == "m" || operators.Peek().ToString() == "p"))
                    {
                        if (strarr.Capacity > strarr.Count)
                        {
                            strarr.Add(operators.Pop());
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    operators.Push(op);
                    break;
                }

                case "mod":     //3
                {
                    while (operators.Count != 0 && (operators.Peek().ToString() == "*" || operators.Peek().ToString() == "/" || operators.Peek().ToString() == "mod" || operators.Peek().ToString() == "m" || operators.Peek().ToString() == "p"))
                    {
                        if (strarr.Capacity > strarr.Count)
                        {
                            strarr.Add(operators.Pop());
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    operators.Push(op);
                    break;
                }

                case "+":     //2
                {
                    while (operators.Count != 0 && (operators.Peek().ToString() == "*" || operators.Peek().ToString() == "/" || operators.Peek().ToString() == "mod" || operators.Peek().ToString() == "+" || operators.Peek().ToString() == "-" || operators.Peek().ToString() == "m" || operators.Peek().ToString() == "p"))
                    {
                        if (strarr.Capacity > strarr.Count)
                        {
                            strarr.Add(operators.Pop());
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    operators.Push(op);
                    break;
                }

                case "-":     //2
                {
                    while (operators.Count != 0 && (operators.Peek().ToString() == "*" || operators.Peek().ToString() == "/" || operators.Peek().ToString() == "mod" || operators.Peek().ToString() == "+" || operators.Peek().ToString() == "-" || operators.Peek().ToString() == "m" || operators.Peek().ToString() == "p"))
                    {
                        if (strarr.Capacity > strarr.Count)
                        {
                            strarr.Add(operators.Pop());
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    operators.Push(op);
                    break;
                }

                case ")":
                {
                    while (operators.Peek().ToString() != "(")
                    {
                        if (strarr.Capacity > strarr.Count)
                        {
                            strarr.Add(operators.Pop());
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    operators.Pop();
                    while (operators.Count != 0 && (operators.Peek().ToString() == "m" || operators.Peek().ToString() == "p"))
                    {
                        if (strarr.Capacity > strarr.Count)
                        {
                            strarr.Add(operators.Pop());
                        }
                        else
                        {
                            // переполнение стека - возвращем null
                            return(null);
                        }
                    }
                    break;
                }

                default:
                {
                    //на входе - число - помещаем в выходной массив
                    if (strarr.Capacity > strarr.Count)
                    {
                        strarr.Add(op);
                        while (operators.Count != 0 && (operators.Peek().ToString() == "m" || operators.Peek().ToString() == "p"))
                        {
                            if (strarr.Capacity > strarr.Count)
                            {
                                strarr.Add(operators.Pop());
                            }
                            else
                            {
                                // переполнение стека - возвращем null
                                return(null);
                            }
                        }
                    }
                    else
                    {
                        return(null);
                    }
                    break;
                }
                }
            }
            //записываем все что осталовь в стеке в выходной массив
            while (operators.Count != 0)
            {
                strarr.Add(operators.Pop());
            }
            return(strarr);
        }
 protected INode Peek()
 {
     return((INode)_nodeStack.Peek());
 }
Exemple #18
0
        private static void MostrarColeccionesNoGenerics()
        {
            Console.Clear();
            Console.WriteLine("******************************");
            Console.WriteLine("*****Pilas No Genéricas*******");
            Console.WriteLine("******************************");
            Console.ReadLine();

            //DECLARO E INSTANCIO UNA COLECCION DE TIPO LIFO
            System.Collections.Stack pila = new System.Collections.Stack();

            pila.Push(1);
            pila.Push(2);
            pila.Push(3);
            pila.Push(4);

            Console.WriteLine("Agrego elementos a la pila...");
            Console.WriteLine("Utilizo pila.Push()");
            Console.WriteLine("Orden de los elementos: 1 - 2 - 3 - 4");
            Console.ReadLine();

            Console.WriteLine("Muestro el primer elemento de la pila...");
            Console.WriteLine("Utilizo pila.Peek()");
            Console.ReadLine();

            Console.WriteLine(pila.Peek());
            Console.ReadLine();

            Console.WriteLine("Muestro todos los elementos de la pila...");
            Console.WriteLine("Recorro con un foreach. No saco los elementos de la pila.");
            Console.ReadLine();

            foreach (int elemento in pila)
            {
                Console.WriteLine(elemento);
            }

            Console.ReadLine();

            Console.WriteLine("Desapilo todos los elementos de la pila...");
            Console.WriteLine("Utilizo pila.Pop(). Recorro con un for");
            Console.ReadLine();

            int cantidad = pila.Count;

            for (int i = 0; i < cantidad; i++)
            {
                Console.WriteLine("Elemento {0} = {1}", i, pila.Pop());
            }

            Console.ReadLine();

            Console.WriteLine("Cantidad de elementos en la pila = {0}", pila.Count);
            Console.ReadLine();


            Console.Clear();
            Console.WriteLine("******************************");
            Console.WriteLine("****Colas No Genéricas********");
            Console.WriteLine("******************************");
            Console.ReadLine();

            System.Collections.Queue cola = new System.Collections.Queue();

            cola.Enqueue(1);
            cola.Enqueue(2);
            cola.Enqueue(3);
            cola.Enqueue(4);

            Console.WriteLine("Agrego elementos a la cola...");
            Console.WriteLine("Utilizo pila.Enqueue()");
            Console.WriteLine("Orden de los elementos: 1 - 2 - 3 - 4");
            Console.ReadLine();

            Console.WriteLine("Muestro el primer elemento de la cola...");
            Console.WriteLine("Utilizo cola.Peek()");
            Console.ReadLine();

            Console.WriteLine(cola.Peek());
            Console.ReadLine();

            Console.WriteLine("Muestro todos los elementos de la cola...");
            Console.WriteLine("Recorro con un foreach");
            Console.ReadLine();

            foreach (int elemento in cola)
            {
                Console.WriteLine(elemento);
            }

            Console.ReadLine();

            Console.WriteLine("Saco todos los elementos de la cola...");
            Console.WriteLine("Utilizo cola.Dequeue(). Recorro con un for");
            Console.ReadLine();

            cantidad = cola.Count;

            for (int i = 0; i < cantidad; i++)
            {
                Console.WriteLine("Elemento {0} = {1}", i, cola.Dequeue());
            }

            Console.ReadLine();

            Console.WriteLine("Cantidad de elementos en la cola = {0}", cola.Count);
            Console.ReadLine();



            Console.Clear();
            Console.WriteLine("******************************");
            Console.WriteLine("******Listas Dinamicas********");
            Console.WriteLine("******************************");
            Console.ReadLine();

            System.Collections.ArrayList vec = new System.Collections.ArrayList();

            vec.Add(1);
            vec.Add(4);
            vec.Add(3);
            vec.Add(2);

            Console.WriteLine("Agrego elementos al ArrayList...");
            Console.WriteLine("Utilizo vec.Add()");
            Console.WriteLine("Orden de los elementos: 1 - 4 - 3 - 2");
            Console.ReadLine();

            Console.WriteLine("Muestro todos los elementos del ArrayList...");
            Console.WriteLine("Recorro con un foreach");
            Console.ReadLine();

            foreach (int elemento in vec)
            {
                Console.WriteLine(elemento);
            }

            Console.ReadLine();

            Console.WriteLine("Ordeno los elementos del ArrayList...");
            Console.WriteLine("Utilizo vec.Sort(). Recorro con un for");
            Console.ReadLine();

            vec.Sort();

            cantidad = vec.Count;

            for (int i = 0; i < cantidad; i++)
            {
                Console.WriteLine("Elemento {0} = {1}", i, vec[i]);
            }

            Console.ReadLine();

            Console.WriteLine("Ordeno los elementos del ArrayList...");
            Console.WriteLine("Utilizo vec.Reverse(). Recorro con un for");
            Console.ReadLine();

            vec.Reverse();

            cantidad = vec.Count;

            for (int i = 0; i < cantidad; i++)
            {
                Console.WriteLine("Elemento {0} = {1}", i, vec[i]);
            }

            Console.ReadLine();

            Console.Clear();
            Console.WriteLine("******************************");
            Console.WriteLine("*********HashTable************");
            Console.WriteLine("******************************");
            Console.ReadLine();

            System.Collections.Hashtable ht = new System.Collections.Hashtable();

            ht.Add(1, "valor 1");
            ht.Add(4, "valor 4");
            ht.Add(3, "valor 3");
            ht.Add(2, "valor 2");

            Console.WriteLine("Agrego elementos al HashTable...");
            Console.WriteLine("Utilizo vec.Add()");
            Console.WriteLine("Orden de los elementos: 1 - 4 - 3 - 2");
            Console.ReadLine();

            Console.WriteLine("Muestro todos los elementos del HashTable...");
            Console.WriteLine("Recorro con un for");
            Console.ReadLine();

            cantidad = ht.Count;

            for (int i = 1; i <= cantidad; i++)
            {
                Console.WriteLine("Elemento {0} = {1}", i, ht[i]);
            }

            Console.ReadLine();
        }
        private bool ToPostfix()
        {
            System.Object prevTok = null;
            System.Object currTok;
            bool          end = false;

            postfixStack.Clear();
            operatorStack.Clear();

            for (int i = 0; i < tokenList.Count; i++)
            {
                currTok = tokenList[i];

                if (currTok.GetType() == typeof(Operator))
                {
                    switch (((Operator)currTok).type)
                    {
                    case OperatorType.LPAREN:
                        if (prevTok != null)
                        {
                            if ((prevTok.GetType() == typeof(Operator) && (
                                     (Operator)prevTok).type == OperatorType.RPAREN) ||
                                prevTok.GetType() == typeof(Operand))
                            {
                                lastError = "Parse error, unexpected left parenthesis";
                                return(false);
                            }
                            else if (prevTok.GetType() != typeof(FunctionCall))
                            {
                                operatorStack.Push(currTok);
                            }
                        }
                        else
                        {
                            operatorStack.Push(currTok);
                        }
                        end = false;
                        break;

                    case OperatorType.ARGSEP:
                    case OperatorType.RPAREN:
                        if (prevTok != null && (
                                prevTok.GetType() == typeof(Operand) || (
                                    prevTok.GetType() == typeof(Operator) &&
                                    ((Operator)prevTok).type == OperatorType.RPAREN)))
                        {
                            while (operatorStack.Count != 0 &&
                                   operatorStack.Peek().GetType() != typeof(FunctionCall) &&
                                   operatorStack.Peek().GetType() == typeof(Operator) &&
                                   ((Operator)operatorStack.Peek()).type != OperatorType.LPAREN)
                            {
                                postfixStack.Push(operatorStack.Pop());
                            }

                            if (((Operator)currTok).type == OperatorType.RPAREN)
                            {
                                if (operatorStack.Count != 0 &&
                                    operatorStack.Peek().GetType() == typeof(Operator) &&
                                    ((Operator)operatorStack.Peek()).type == OperatorType.LPAREN)
                                {
                                    operatorStack.Pop();
                                }
                                else if (operatorStack.Count != 0 && operatorStack.Peek().GetType() == typeof(FunctionCall))
                                {
                                    postfixStack.Push(operatorStack.Pop());
                                }
                                else
                                {
                                    lastError = "Parse error, unbalanced parenthesis";
                                    return(false);
                                }

                                while (operatorStack.Count != 0 &&
                                       operatorStack.Peek().GetType() == typeof(Operator) &&
                                       ((Operator)operatorStack.Peek()).type == OperatorType.UNARY)
                                {
                                    postfixStack.Push(operatorStack.Pop());
                                }
                            }
                            else if (operatorStack.Count == 0 || operatorStack.Peek().GetType() != typeof(FunctionCall))
                            {
                                lastError = "Parse error, no matching function to argument separator";
                                return(false);
                            }
                        }
                        else
                        {
                            lastError = ((Operator)currTok).type == OperatorType.RPAREN ?
                                        "Parse error, unexpected right parenthesis" :
                                        "Parse error, unexpected argument separator";

                            return(false);
                        }
                        end = true;
                        break;

                    case OperatorType.BINARY:
                        if (((Operator)currTok).semantic == OperatorSemantics.Subtract && (prevTok == null || (
                                                                                               prevTok.GetType() == typeof(Operator) &&
                                                                                               ((Operator)prevTok).type != OperatorType.RPAREN)))
                        {
                            currTok = new Operator(OperatorType.UNARY, FunctionDefinitions.Neg, 0);
                            goto UnaryContext;
                        }

                        if (prevTok == null || (prevTok.GetType() == typeof(FunctionCall) || (
                                                    prevTok.GetType() == typeof(Operator) &&
                                                    ((Operator)prevTok).type != OperatorType.RPAREN)))
                        {
                            lastError = "Parse error, unexpected binary operator";
                            return(false);
                        }

                        while (operatorStack.Count != 0 &&
                               operatorStack.Peek().GetType() == typeof(Operator) &&
                               ((Operator)operatorStack.Peek()).type != OperatorType.LPAREN &&
                               ((Operator)operatorStack.Peek()).precedence <= ((Operator)currTok).precedence)
                        {
                            postfixStack.Push(operatorStack.Pop());
                        }

                        operatorStack.Push(currTok);
                        end = false;
                        break;

                    case OperatorType.UNARY:
UnaryContext:

                        if (prevTok != null && (prevTok.GetType() == typeof(Operand) || (
                                                    prevTok.GetType() == typeof(Operator) &&
                                                    ((Operator)prevTok).type == OperatorType.RPAREN)))
                        {
                            lastError = "Parse error, unexpected unary operator";
                            return(false);
                        }

                        operatorStack.Push(currTok);
                        end = false;
                        break;
                    }
                }
                else if (currTok.GetType() == typeof(Operand))
                {
                    if (prevTok != null && (
                            prevTok.GetType() == typeof(Operand) || (
                                prevTok.GetType() == typeof(Operator) && ((Operator)prevTok).type == OperatorType.RPAREN)))
                    {
                        lastError = "Parse error, unexpected operand";
                        return(false);
                    }

                    postfixStack.Push(currTok);

                    while (operatorStack.Count != 0 &&
                           operatorStack.Peek().GetType() == typeof(Operator) &&
                           ((Operator)operatorStack.Peek()).type == OperatorType.UNARY)
                    {
                        postfixStack.Push(operatorStack.Pop());
                    }

                    end = true;
                }
                else if (currTok.GetType() == typeof(FunctionCall))
                {
                    if (prevTok != null && (
                            prevTok.GetType() == typeof(Operand) || (
                                prevTok.GetType() == typeof(Operator) && ((Operator)prevTok).type == OperatorType.RPAREN)))
                    {
                        lastError = "Parse error, unexpected function";
                        return(false);
                    }

                    operatorStack.Push(currTok);
                    end = false;
                }

                prevTok = currTok;
            }

            if (!end)
            {
                lastError = "Parse error, Unexpected end of expression";
                return(false);
            }

            while (operatorStack.Count != 0)
            {
                if ((operatorStack.Peek().GetType() == typeof(Operator) && (
                         (Operator)operatorStack.Peek()).type == OperatorType.LPAREN) ||
                    operatorStack.Peek().GetType() == typeof(FunctionCall))
                {
                    lastError = "Parse error, unbalanced parenthesis at end of expression";
                    return(false);
                }
                else
                {
                    postfixStack.Push(operatorStack.Pop());
                }
            }

            return(true);
        }
Exemple #20
0
        private static Bamboo.Xml.XmlElement Read(System.Xml.XmlTextReader xmlTextReader)
        {
            System.Collections.Stack elementsStack = new System.Collections.Stack();

            while (xmlTextReader.Read())
            {
                switch (xmlTextReader.NodeType)
                {
                case System.Xml.XmlNodeType.Element:
                {
                    Bamboo.Xml.XmlElement element = new Bamboo.Xml.XmlElement();
                    element.Name = xmlTextReader.LocalName;

                    if (xmlTextReader.IsEmptyElement)
                    {
                        if (elementsStack.Count == 0)
                        {
                            elementsStack.Push(element);
                        }
                        else
                        {
                            Bamboo.Xml.XmlElement parent = (XmlElement)elementsStack.Peek();
                            parent.Elements.Add(element);
                        }
                    }
                    else
                    {
                        if (elementsStack.Count > 0)
                        {
                            Bamboo.Xml.XmlElement parent = (XmlElement)elementsStack.Peek();
                            parent.Elements.Add(element);
                        }
                        elementsStack.Push(element);
                    }

                    for (int i = 0; i < xmlTextReader.AttributeCount; i++)
                    {
                        xmlTextReader.MoveToAttribute(i);

                        Bamboo.Xml.XmlAttribute xmlAttribute = new Bamboo.Xml.XmlAttribute();
                        xmlAttribute.Name  = xmlTextReader.LocalName;
                        xmlAttribute.Value = xmlTextReader.Value;

                        element.Attributes.Add(xmlAttribute);
                    }

                    break;
                }

                case System.Xml.XmlNodeType.EndElement:
                {
                    if (elementsStack.Count > 1)
                    {
                        elementsStack.Pop();
                    }
                    break;
                }

                case System.Xml.XmlNodeType.CDATA:
                case System.Xml.XmlNodeType.Text:
                {
                    ((XmlElement)elementsStack.Peek()).Value = xmlTextReader.Value;
                    break;
                }
                }
            }

            if (elementsStack.Count == 0)
            {
                throw new System.Exception("Document does not contain any elements.");
            }
            else if (elementsStack.Count > 1)
            {
                throw new System.Exception("Document contains more than one root element.");
            }

            return((XmlElement)elementsStack.Pop());
        }
Exemple #21
0
 /* Returns the node currently on the top of the stack. */
 internal virtual INode peekNode()
 {
     return((INode)nodes.Peek());
 }
        /// <summary>
        /// load rtf
        /// </summary>
        /// <param name="reader">RTF text reader</param>
        public void Load( RTFReader reader )
        {
            myNodes.Clear();
            System.Collections.Stack groups = new System.Collections.Stack();
            RTFNodeGroup NewGroup = null ;
            RTFNode NewNode = null;
            while( reader.ReadToken() != null )
            {
                if( reader.TokenType == RTFTokenType.GroupStart )
                {
                    // begin group
                    if( NewGroup == null)
                    {
                        NewGroup = this ;
                    }
                    else
                    {
                        NewGroup = new RTFNodeGroup();
                        NewGroup.OwnerDocument = this ;
                    }
                    if( NewGroup != this )
                    {
                        RTFNodeGroup g = ( RTFNodeGroup ) groups.Peek();
                        g.AppendChild( NewGroup );
                    }
                    groups.Push( NewGroup );
                }
                else if( reader.TokenType == RTFTokenType.GroupEnd )
                {
                    // end group
                    NewGroup = ( RTFNodeGroup ) groups.Pop();
                    NewGroup.MergeText();
                    if (NewGroup.FirstNode is RTFNode)
                    {
                        switch (NewGroup.Keyword)
                        {
                            case RTFConsts._fonttbl:
                                // read font table
                                ReadFontTable(NewGroup);
                                break;
                            case RTFConsts._colortbl:
                                // read color table
                                ReadColorTable(NewGroup);
                                break;
                            case RTFConsts._info :
                                // read document information
                                ReadDocumentInfo(NewGroup);
                                break;
                        }
                    }
                    if (groups.Count > 0)
                    {
                        NewGroup = (RTFNodeGroup)groups.Peek();
                    }
                    else
                    {
                        break;
                    }
                    //NewGroup.MergeText();
                }
                else
                {
                    // read content

                    NewNode = new RTFNode( reader.CurrentToken );
                    NewNode.OwnerDocument = this ;
                    NewGroup.AppendChild( NewNode );
                    if (NewNode.Keyword == RTFConsts._f )
                    {
                        RTFFont font = this.FontTable[NewNode.Parameter];
                        if (font != null)
                        {
                            myFontChartset = font.Encoding;
                        }
                        else
                        {
                            myFontChartset = null;
                        }
                        //myFontChartset = RTFFont.GetRTFEncoding( NewNode.Parameter );
                    }
                    else if (NewNode.Keyword == RTFConsts._af)
                    {
                        RTFFont font = this.FontTable[NewNode.Parameter];
                        if (font != null)
                        {
                            myAssociateFontChartset = font.Encoding;
                        }
                        else
                        {
                            myAssociateFontChartset = null;
                        }
                    }
                }
            }// while( reader.ReadToken() != null )
            while( groups.Count > 0 )
            {
                NewGroup = ( RTFNodeGroup ) groups.Pop();
                NewGroup.MergeText();
            }
            //this.UpdateInformation();
        }
Exemple #23
0
        /// <summary>
        /// load rtf
        /// </summary>
        /// <param name="reader">RTF text reader</param>
        public void Load(RTFReader reader)
        {
            myNodes.Clear();
            System.Collections.Stack groups   = new System.Collections.Stack();
            RTFNodeGroup             NewGroup = null;
            RTFNode NewNode = null;

            while (reader.ReadToken() != null)
            {
                if (reader.TokenType == RTFTokenType.GroupStart)
                {
                    // begin group
                    if (NewGroup == null)
                    {
                        NewGroup = this;
                    }
                    else
                    {
                        NewGroup = new RTFNodeGroup();
                        NewGroup.OwnerDocument = this;
                    }
                    if (NewGroup != this)
                    {
                        RTFNodeGroup g = ( RTFNodeGroup )groups.Peek();
                        g.AppendChild(NewGroup);
                    }
                    groups.Push(NewGroup);
                }
                else if (reader.TokenType == RTFTokenType.GroupEnd)
                {
                    // end group
                    NewGroup = ( RTFNodeGroup )groups.Pop();
                    NewGroup.MergeText();
                    if (NewGroup.FirstNode is RTFNode)
                    {
                        switch (NewGroup.Keyword)
                        {
                        case RTFConsts._fonttbl:
                            // read font table
                            ReadFontTable(NewGroup);
                            break;

                        case RTFConsts._colortbl:
                            // read color table
                            ReadColorTable(NewGroup);
                            break;

                        case RTFConsts._info:
                            // read document information
                            ReadDocumentInfo(NewGroup);
                            break;
                        }
                    }
                    if (groups.Count > 0)
                    {
                        NewGroup = (RTFNodeGroup)groups.Peek();
                    }
                    else
                    {
                        break;
                    }
                    //NewGroup.MergeText();
                }
                else
                {
                    // read content

                    NewNode = new RTFNode(reader.CurrentToken);
                    NewNode.OwnerDocument = this;
                    NewGroup.AppendChild(NewNode);
                    if (NewNode.Keyword == RTFConsts._f)
                    {
                        RTFFont font = this.FontTable[NewNode.Parameter];
                        if (font != null)
                        {
                            myFontChartset = font.Encoding;
                        }
                        else
                        {
                            myFontChartset = null;
                        }
                        //myFontChartset = RTFFont.GetRTFEncoding( NewNode.Parameter );
                    }
                    else if (NewNode.Keyword == RTFConsts._af)
                    {
                        RTFFont font = this.FontTable[NewNode.Parameter];
                        if (font != null)
                        {
                            myAssociateFontChartset = font.Encoding;
                        }
                        else
                        {
                            myAssociateFontChartset = null;
                        }
                    }
                }
            }            // while( reader.ReadToken() != null )
            while (groups.Count > 0)
            {
                NewGroup = ( RTFNodeGroup )groups.Pop();
                NewGroup.MergeText();
            }
            //this.UpdateInformation();
        }
 public override int?Peek()
 {
     return((int?)stack.Peek());
 }
Exemple #25
0
        /// <summary> Walk the actions filling in the names of functions as we go.
        /// This is done by looking for DefineFunction's actions and then
        /// examining the content of the stack for a name.
        ///
        /// </summary>
        /// <param name="c">list of actions to be traversed
        /// </param>
        /// <param name="swfVersion">version of swf file that housed the ActionList (just use 7 if you don't know)
        /// </param>
        /// <param name="pool">optional; constant pool for the list of actions
        /// </param>
        /// <param name="className">optional; used to locate a constructor function (i.e if funcName == className)
        /// </param>
        /// <param name="profileOffsets">optional; is filled with offsets if a call to a
        /// function named 'profile' is encountered.  Can be null if caller is not
        /// interested in obtaining this information.
        /// </param>
        public static void walkActions(ActionList c, int swfVersion, String[] pool, String className, System.Collections.IList profileOffsets)
        {
            // assumption: ActionContext c is always not null! try-catch-finally may be busted.
            if (c == null)
            {
                return;
            }

            System.Collections.Stack     evalStack = new System.Collections.Stack();
            System.Collections.Hashtable variables = new System.Collections.Hashtable();

            // loop again, this time, we register all the actions...
            int    offset;
            Action a;

            for (int i = 0; i < c.size(); i++)
            {
                offset = c.getOffset(i);
                a      = c.getAction(i);

                switch (a.code)
                {
                // Flash 1 and 2 actions
                case ActionConstants.sactionHasLength:
                case ActionConstants.sactionNone:
                case ActionConstants.sactionGotoFrame:
                case ActionConstants.sactionGetURL:
                case ActionConstants.sactionNextFrame:
                case ActionConstants.sactionPrevFrame:
                case ActionConstants.sactionPlay:
                case ActionConstants.sactionStop:
                case ActionConstants.sactionToggleQuality:
                case ActionConstants.sactionStopSounds:
                case ActionConstants.sactionWaitForFrame:
                // Flash 3 Actions
                case ActionConstants.sactionSetTarget:
                case ActionConstants.sactionGotoLabel:
                    // no action
                    break;

                // Flash 4 Actions

                case ActionConstants.sactionAdd:
                case ActionConstants.sactionSubtract:
                case ActionConstants.sactionMultiply:
                case ActionConstants.sactionDivide:
                case ActionConstants.sactionEquals:
                case ActionConstants.sactionLess:
                case ActionConstants.sactionAnd:
                case ActionConstants.sactionOr:
                case ActionConstants.sactionStringEquals:
                case ActionConstants.sactionStringAdd:
                case ActionConstants.sactionStringLess:
                case ActionConstants.sactionMBStringLength:
                case ActionConstants.sactionGetProperty:
                    // pop, pop, push
                    pop(evalStack);
                    break;

                case ActionConstants.sactionNot:
                case ActionConstants.sactionStringLength:
                case ActionConstants.sactionToInteger:
                case ActionConstants.sactionCharToAscii:
                case ActionConstants.sactionAsciiToChar:
                case ActionConstants.sactionMBCharToAscii:
                case ActionConstants.sactionMBAsciiToChar:
                case ActionConstants.sactionRandomNumber:
                    // pop, push
                    break;

                case ActionConstants.sactionGetVariable:
                    Object key = pop(evalStack);
                    if (variables[key] == null)
                    {
                        evalStack.Push(key);
                    }
                    else
                    {
                        evalStack.Push(variables[key]);
                    }
                    break;

                case ActionConstants.sactionStringExtract:
                case ActionConstants.sactionMBStringExtract:
                    // pop, pop, pop, push
                    pop(evalStack);
                    pop(evalStack);
                    break;

                case ActionConstants.sactionPush:
                    Push          p    = (Push)a;
                    System.Object o    = p.value;
                    int           type = Push.getTypeCode(o);
                    switch (type)
                    {
                    case ActionConstants.kPushStringType:
                        evalStack.Push(o);
                        break;

                    case ActionConstants.kPushNullType:
                        evalStack.Push("null");
                        break;

                    case ActionConstants.kPushUndefinedType:
                        evalStack.Push("undefined");
                        break;

                    case ActionConstants.kPushRegisterType:
                        evalStack.Push(registers[(int)((SByte)o) & 0xFF]);
                        break;

                    case ActionConstants.kPushConstant8Type:
                    case ActionConstants.kPushConstant16Type:
                        evalStack.Push(pool[Convert.ToInt32(((ValueType)o)) & 0xFFFF]);
                        break;

                    case ActionConstants.kPushFloatType:
                        evalStack.Push(o + "F");
                        break;

                    case ActionConstants.kPushBooleanType:
                    case ActionConstants.kPushDoubleType:
                    case ActionConstants.kPushIntegerType:
                        evalStack.Push(o);
                        break;

                    default:
                        evalStack.Push("type" + type);
                        break;
                    }
                    break;

                case ActionConstants.sactionIf:
                    pop(evalStack);
                    break;

                case ActionConstants.sactionPop:
                case ActionConstants.sactionCall:
                case ActionConstants.sactionGotoFrame2:
                case ActionConstants.sactionSetTarget2:
                case ActionConstants.sactionRemoveSprite:
                case ActionConstants.sactionWaitForFrame2:
                case ActionConstants.sactionTrace:
                    // pop
                    pop(evalStack);
                    break;

                case ActionConstants.sactionJump:
                case ActionConstants.sactionEndDrag:
                    // no action
                    break;

                case ActionConstants.sactionSetVariable:
                    key = pop(evalStack);
                    Object val = pop(evalStack);
                    variables[key] = val;
                    break;

                case ActionConstants.sactionGetURL2:
                    // pop, pop
                    pop(evalStack);
                    pop(evalStack);
                    break;

                case ActionConstants.sactionSetProperty:
                case ActionConstants.sactionCloneSprite:
                    // pop, pop, pop
                    pop(evalStack);
                    pop(evalStack);
                    pop(evalStack);
                    break;

                case ActionConstants.sactionStartDrag:
                    // pop, pop, pop, if the 3rd pop is non-zero, pop, pop, pop, pop
                    pop(evalStack);
                    pop(evalStack);
                    Object obj = pop(evalStack);
                    if (Int32.Parse(obj.ToString()) != 0)
                    {
                        pop(evalStack);
                        pop(evalStack);
                        pop(evalStack);
                        pop(evalStack);
                    }
                    break;

                case ActionConstants.sactionGetTime:
                    // push
                    evalStack.Push(dummy);
                    break;

                // Flash 5 actions

                case ActionConstants.sactionDelete:
                    pop(evalStack);
                    break;

                case ActionConstants.sactionDefineLocal:
                    // pop, pop
                    val            = pop(evalStack);
                    key            = pop(evalStack);
                    variables[key] = val;
                    break;

                case ActionConstants.sactionDefineFunction:
                case ActionConstants.sactionDefineFunction2:
                    DefineFunction f = (DefineFunction)a;

                    if (swfVersion > 6 && className != null)
                    {
                        if (f.name == null || f.name.Length == 0)
                        {
                            int depth = evalStack.Count;
                            if (depth != 0)
                            {
                                o = evalStack.Peek();
                                if (o == dummy)
                                {
                                    f.name = "";
                                }
                                else if (o != null)
                                {
                                    f.name = o.ToString();
                                }
                            }
                            evalStack.Push(dummy);
                        }

                        if (f.name == "null")
                        {
                            f.name = "";
                        }

                        if (f.name == null || f.name.Length == 0)
                        {
                            // do nothing... it's an anonymous function!
                        }
                        else if (!className.EndsWith(f.name))
                        {
                            f.name = className + "." + f.name;
                        }
                        else
                        {
                            f.name = className + ".[constructor]";
                        }
                    }
                    else
                    {
                        if (f.name == null || f.name.Length == 0)
                        {
                            System.Text.StringBuilder buffer = new System.Text.StringBuilder();

                            Boolean bFirst = true;

                            foreach (Object ob in evalStack)
                            {
                                if (ob == dummy)
                                {
                                    break;
                                }
                                else if (bFirst)
                                {
                                    buffer.Append(ob);
                                    bFirst = false;
                                }
                                else
                                {
                                    buffer.Insert(0, '.');
                                    buffer.Insert(0, ob);
                                }
                            }
                            f.name = buffer.ToString();

                            if (f.name != null && f.name.IndexOf(".prototype.") == -1)
                            {
                                f.name = "";
                            }
                            evalStack.Push(dummy);
                        }
                    }
                    // evalActions(f.actions);
                    break;

                case ActionConstants.sactionCallFunction:
                    Object function = pop(evalStack);
                    if (profileOffsets != null && "profile".Equals(function))
                    {
                        profileOffsets.Add((Int32)(offset - 13));                           // Push 1
                        profileOffsets.Add((Int32)(offset - 5));                            // Push 'profile'
                        profileOffsets.Add((Int32)offset);                                  // CallFunction
                        profileOffsets.Add((Int32)(offset + 1));                            // Pop
                    }
                    int n = Convert.ToInt32(((System.ValueType)pop(evalStack)));
                    for (int k = 0; k < n; k++)
                    {
                        pop(evalStack);
                    }
                    evalStack.Push(dummy);
                    break;

                case ActionConstants.sactionReturn:
                    // return function() { ... } doesn't push...
                    pop(evalStack);
                    break;

                case ActionConstants.sactionModulo:
                    // pop, push
                    break;

                case ActionConstants.sactionNewObject:
                    pop(evalStack);
                    int num = Convert.ToInt32(((ValueType)pop(evalStack)));
                    for (int k = 0; k < num; k++)
                    {
                        pop(evalStack);
                    }
                    evalStack.Push(dummy);
                    break;

                case ActionConstants.sactionDefineLocal2:
                case ActionConstants.sactionDelete2:
                case ActionConstants.sactionAdd2:
                case ActionConstants.sactionLess2:
                    // pop
                    pop(evalStack);
                    break;

                case ActionConstants.sactionInitArray:
                    // pop, if the first pop is non-zero, keep popping
                    num = Convert.ToInt32(((ValueType)pop(evalStack)));
                    for (int k = 0; k < num; k++)
                    {
                        pop(evalStack);
                    }
                    evalStack.Push(dummy);
                    break;

                case ActionConstants.sactionInitObject:
                    num = Convert.ToInt32(((ValueType)pop(evalStack))) * 2;
                    for (int k = 0; k < num; k++)
                    {
                        pop(evalStack);
                    }
                    evalStack.Push(dummy);
                    break;

                case ActionConstants.sactionTargetPath:
                case ActionConstants.sactionEnumerate:
                case ActionConstants.sactionToNumber:
                case ActionConstants.sactionToString:
                case ActionConstants.sactionTypeOf:
                    // no action
                    break;

                case ActionConstants.sactionStoreRegister:
                    StoreRegister r = (StoreRegister)a;
                    registers[r.register] = evalStack.Peek();
                    break;

                case ActionConstants.sactionEquals2:
                    // pop, pop, push
                    // if (evalStack.size() >= 2)
                {
                    pop(evalStack);
                }
                break;

                case ActionConstants.sactionPushDuplicate:
                    evalStack.Push(dummy);
                    break;

                case ActionConstants.sactionStackSwap:
                    // pop, pop, push, push
                    break;

                case ActionConstants.sactionGetMember:
                    // pop, pop, concat, push
                    Object o1 = pop(evalStack);
                    Object o2 = pop(evalStack);
                    if (pool != null)
                    {
                        try
                        {
                            evalStack.Push(pool[Int32.Parse(o2.ToString())] + "." + pool[Int32.Parse(o1.ToString())]);
                        }
                        catch (Exception)
                        {
                            if (o1 == dummy || o2 == dummy)
                            {
                                evalStack.Push(dummy);
                            }
                            else
                            {
                                evalStack.Push(o2 + "." + o1);
                            }
                        }
                    }
                    else
                    {
                        evalStack.Push(o2 + "." + o1);
                    }
                    break;

                case ActionConstants.sactionSetMember:
                    // pop, pop, pop
                    pop(evalStack);
                    pop(evalStack);
                    pop(evalStack);
                    break;

                case ActionConstants.sactionIncrement:
                case ActionConstants.sactionDecrement:
                    break;

                case ActionConstants.sactionCallMethod:
                    pop(evalStack);
                    pop(evalStack);
                    Object obj2 = pop(evalStack);
                    if (obj2 is String)
                    {
                        try
                        {
                            n = Int32.Parse((String)obj2);
                        }
                        catch (FormatException)
                        {
                            n = 1;
                        }
                    }
                    else
                    {
                        n = Convert.ToInt32(((ValueType)obj2));
                    }
                    for (int k = 0; k < n; k++)
                    {
                        pop(evalStack);
                    }
                    evalStack.Push(dummy);
                    break;

                case ActionConstants.sactionNewMethod:
                    /*Object meth =*/ pop(evalStack);
                    /*Object cls =*/ pop(evalStack);
                    num = Convert.ToInt32(((ValueType)pop(evalStack)));
                    for (int k = 0; k < num; k++)
                    {
                        pop(evalStack);
                    }
                    evalStack.Push(dummy);
                    break;

                case ActionConstants.sactionWith:
                    // pop
                    pop(evalStack);
                    break;

                case ActionConstants.sactionConstantPool:
                    pool = ((ConstantPool)a).pool;
                    // no action
                    break;

                case ActionConstants.sactionStrictMode:
                    break;


                case ActionConstants.sactionBitAnd:
                case ActionConstants.sactionBitOr:
                case ActionConstants.sactionBitLShift:
                    // pop, push
                    break;

                case ActionConstants.sactionBitXor:
                case ActionConstants.sactionBitRShift:
                case ActionConstants.sactionBitURShift:
                    pop(evalStack);
                    break;

                // Flash 6 actions

                case ActionConstants.sactionInstanceOf:
                    pop(evalStack);
                    break;

                case ActionConstants.sactionEnumerate2:
                    // pop, push, more pushes?
                    break;

                case ActionConstants.sactionStrictEquals:
                case ActionConstants.sactionGreater:
                case ActionConstants.sactionStringGreater:
                    pop(evalStack);
                    break;

                // FEATURE_EXCEPTIONS

                case ActionConstants.sactionTry:
                    // do nothing
                    break;

                case ActionConstants.sactionThrow:
                    pop(evalStack);
                    break;

                // FEATURE_AS2_INTERFACES

                case ActionConstants.sactionCastOp:
                    break;

                case ActionConstants.sactionImplementsOp:
                    break;

                // Reserved for Quicktime

                case ActionConstants.sactionQuickTime:
                    break;

                default:
                    break;
                }
            }
        }
		/// <summary> Walk the actions filling in the names of functions as we go.
		/// This is done by looking for DefineFunction's actions and then
		/// examining the content of the stack for a name.
		/// 
		/// </summary>
		/// <param name="c">list of actions to be traversed
		/// </param>
		/// <param name="swfVersion">version of swf file that housed the ActionList (just use 7 if you don't know)
		/// </param>
		/// <param name="pool">optional; constant pool for the list of actions
		/// </param>
		/// <param name="className">optional; used to locate a constructor function (i.e if funcName == className)
		/// </param>
		/// <param name="profileOffsets">optional; is filled with offsets if a call to a 
		/// function named 'profile' is encountered.  Can be null if caller is not
		/// interested in obtaining this information.
		/// </param>
		public static void walkActions(ActionList c, int swfVersion, String[] pool, String className, System.Collections.IList profileOffsets)
		{
			// assumption: ActionContext c is always not null! try-catch-finally may be busted.
			if (c == null)
				return ;
			
			System.Collections.Stack evalStack = new System.Collections.Stack();
			System.Collections.Hashtable variables = new System.Collections.Hashtable();
			
			// loop again, this time, we register all the actions...
			int offset;
			Action a;
			
			for (int i = 0; i < c.size(); i++)
			{
				offset = c.getOffset(i);
				a = c.getAction(i);
				
				switch (a.code)
				{
					
					// Flash 1 and 2 actions
					case ActionConstants.sactionHasLength: 
					case ActionConstants.sactionNone: 
					case ActionConstants.sactionGotoFrame: 
					case ActionConstants.sactionGetURL: 
					case ActionConstants.sactionNextFrame: 
					case ActionConstants.sactionPrevFrame: 
					case ActionConstants.sactionPlay: 
					case ActionConstants.sactionStop: 
					case ActionConstants.sactionToggleQuality: 
					case ActionConstants.sactionStopSounds: 
					case ActionConstants.sactionWaitForFrame: 
					// Flash 3 Actions
					case ActionConstants.sactionSetTarget: 
					case ActionConstants.sactionGotoLabel: 
						// no action
						break;
						
						// Flash 4 Actions
					
					case ActionConstants.sactionAdd: 
					case ActionConstants.sactionSubtract: 
					case ActionConstants.sactionMultiply: 
					case ActionConstants.sactionDivide: 
					case ActionConstants.sactionEquals: 
					case ActionConstants.sactionLess: 
					case ActionConstants.sactionAnd: 
					case ActionConstants.sactionOr: 
					case ActionConstants.sactionStringEquals: 
					case ActionConstants.sactionStringAdd: 
					case ActionConstants.sactionStringLess: 
					case ActionConstants.sactionMBStringLength: 
					case ActionConstants.sactionGetProperty: 
						// pop, pop, push
						pop(evalStack);
						break;
					
					case ActionConstants.sactionNot: 
					case ActionConstants.sactionStringLength: 
					case ActionConstants.sactionToInteger: 
					case ActionConstants.sactionCharToAscii: 
					case ActionConstants.sactionAsciiToChar: 
					case ActionConstants.sactionMBCharToAscii: 
					case ActionConstants.sactionMBAsciiToChar: 
					case ActionConstants.sactionRandomNumber: 
						// pop, push
						break;
					
					case ActionConstants.sactionGetVariable: 
						Object key = pop(evalStack);
						if (variables[key] == null)
						{
							evalStack.Push(key);
						}
						else
						{
							evalStack.Push(variables[key]);
						}
						break;
					
					case ActionConstants.sactionStringExtract: 
					case ActionConstants.sactionMBStringExtract: 
						// pop, pop, pop, push
						pop(evalStack);
						pop(evalStack);
						break;
					
					case ActionConstants.sactionPush: 
						Push p = (Push) a;
						System.Object o = p.value;
						int type = Push.getTypeCode(o);
						switch (type)
						{
							
							case ActionConstants.kPushStringType: 
								evalStack.Push(o);
								break;
							
							case ActionConstants.kPushNullType: 
								evalStack.Push("null");
								break;
							
							case ActionConstants.kPushUndefinedType: 
								evalStack.Push("undefined");
								break;
							
							case ActionConstants.kPushRegisterType: 
								evalStack.Push(registers[(int) ((SByte) o) & 0xFF]);
								break;
							
							case ActionConstants.kPushConstant8Type: 
							case ActionConstants.kPushConstant16Type: 
								evalStack.Push(pool[Convert.ToInt32(((ValueType) o)) & 0xFFFF]);
								break;
							
							case ActionConstants.kPushFloatType: 
								evalStack.Push(o + "F");
								break;
							
							case ActionConstants.kPushBooleanType: 
							case ActionConstants.kPushDoubleType: 
							case ActionConstants.kPushIntegerType: 
								evalStack.Push(o);
								break;
							
							default: 
								evalStack.Push("type" + type);
								break;
							
						}
						break;
					
					case ActionConstants.sactionIf: 
						pop(evalStack);
						break;
					
					case ActionConstants.sactionPop: 
					case ActionConstants.sactionCall: 
					case ActionConstants.sactionGotoFrame2: 
					case ActionConstants.sactionSetTarget2: 
					case ActionConstants.sactionRemoveSprite: 
					case ActionConstants.sactionWaitForFrame2: 
					case ActionConstants.sactionTrace: 
						// pop
						pop(evalStack);
						break;
					
					case ActionConstants.sactionJump: 
					case ActionConstants.sactionEndDrag: 
						// no action
						break;
					
					case ActionConstants.sactionSetVariable: 
						key = pop(evalStack);
						Object val = pop(evalStack);
						variables[key] = val;
						break;
					
					case ActionConstants.sactionGetURL2: 
						// pop, pop
						pop(evalStack);
						pop(evalStack);
						break;
					
					case ActionConstants.sactionSetProperty: 
					case ActionConstants.sactionCloneSprite: 
						// pop, pop, pop
						pop(evalStack);
						pop(evalStack);
						pop(evalStack);
						break;
					
					case ActionConstants.sactionStartDrag: 
						// pop, pop, pop, if the 3rd pop is non-zero, pop, pop, pop, pop
						pop(evalStack);
						pop(evalStack);
						Object obj = pop(evalStack);
						if (Int32.Parse(obj.ToString()) != 0)
						{
							pop(evalStack);
							pop(evalStack);
							pop(evalStack);
							pop(evalStack);
						}
						break;
					
					case ActionConstants.sactionGetTime: 
						// push
						evalStack.Push(dummy);
						break;
						
						// Flash 5 actions
					
					case ActionConstants.sactionDelete: 
						pop(evalStack);
						break;
					
					case ActionConstants.sactionDefineLocal: 
						// pop, pop
						val = pop(evalStack);
						key = pop(evalStack);
						variables[key] = val;
						break;
					
					case ActionConstants.sactionDefineFunction: 
					case ActionConstants.sactionDefineFunction2: 
						DefineFunction f = (DefineFunction) a;
						
						if (swfVersion > 6 && className != null)
						{
							if (f.name == null || f.name.Length == 0)
							{
								int depth = evalStack.Count;
								if (depth != 0)
								{
									o = evalStack.Peek();
									if (o == dummy)
									{
										f.name = "";
									}
									else if (o != null)
									{
										f.name = o.ToString();
									}
								}
								evalStack.Push(dummy);
							}
							
							if (f.name == "null")
							{
								f.name = "";
							}
							
							if (f.name == null || f.name.Length == 0)
							{
								// do nothing... it's an anonymous function!
							}
							else if (!className.EndsWith(f.name))
							{
								f.name = className + "." + f.name;
							}
							else
							{
								f.name = className + ".[constructor]";
							}
						}
						else
						{
							if (f.name == null || f.name.Length == 0)
							{
                                System.Text.StringBuilder buffer = new System.Text.StringBuilder();

                                Boolean bFirst = true;

								foreach (Object ob in evalStack)
								{
									if (ob == dummy)
									{
										break;
									}
									else if (bFirst)
									{
										buffer.Append(ob);
                                        bFirst = false;
									}
									else
									{
										buffer.Insert(0, '.');
										buffer.Insert(0, ob);
									}
								}
								f.name = buffer.ToString();
								
								if (f.name != null && f.name.IndexOf(".prototype.") == - 1)
								{
									f.name = "";
								}
								evalStack.Push(dummy);
							}
						}
						// evalActions(f.actions);
						break;
					
					case ActionConstants.sactionCallFunction: 
						Object function = pop(evalStack);
						if (profileOffsets != null && "profile".Equals(function))
						{
							profileOffsets.Add((Int32) (offset - 13)); // Push 1
							profileOffsets.Add((Int32) (offset - 5)); // Push 'profile'
							profileOffsets.Add((Int32) offset); // CallFunction
							profileOffsets.Add((Int32) (offset + 1)); // Pop
						}
						int n = Convert.ToInt32(((System.ValueType) pop(evalStack)));
						for (int k = 0; k < n; k++)
						{
							pop(evalStack);
						}
						evalStack.Push(dummy);
						break;
					
					case ActionConstants.sactionReturn: 
						// return function() { ... } doesn't push...
						pop(evalStack);
						break;
					
					case ActionConstants.sactionModulo: 
						// pop, push
						break;
					
					case ActionConstants.sactionNewObject: 
						pop(evalStack);
						int num = Convert.ToInt32(((ValueType) pop(evalStack)));
						for (int k = 0; k < num; k++)
						{
							pop(evalStack);
						}
						evalStack.Push(dummy);
						break;
					
					case ActionConstants.sactionDefineLocal2: 
					case ActionConstants.sactionDelete2: 
					case ActionConstants.sactionAdd2: 
					case ActionConstants.sactionLess2: 
						// pop
						pop(evalStack);
						break;
					
					case ActionConstants.sactionInitArray: 
						// pop, if the first pop is non-zero, keep popping
						num = Convert.ToInt32(((ValueType) pop(evalStack)));
						for (int k = 0; k < num; k++)
						{
							pop(evalStack);
						}
						evalStack.Push(dummy);
						break;
					
					case ActionConstants.sactionInitObject: 
						num = Convert.ToInt32(((ValueType) pop(evalStack))) * 2;
						for (int k = 0; k < num; k++)
						{
							pop(evalStack);
						}
						evalStack.Push(dummy);
						break;
					
					case ActionConstants.sactionTargetPath: 
					case ActionConstants.sactionEnumerate: 
					case ActionConstants.sactionToNumber: 
					case ActionConstants.sactionToString: 
					case ActionConstants.sactionTypeOf: 
						// no action
						break;
					
					case ActionConstants.sactionStoreRegister: 
						StoreRegister r = (StoreRegister) a;
						registers[r.register] = evalStack.Peek();
						break;
					
					case ActionConstants.sactionEquals2: 
						// pop, pop, push
						// if (evalStack.size() >= 2)
						{
							pop(evalStack);
						}
						break;
					
					case ActionConstants.sactionPushDuplicate: 
						evalStack.Push(dummy);
						break;
					
					case ActionConstants.sactionStackSwap: 
						// pop, pop, push, push
						break;
					
					case ActionConstants.sactionGetMember: 
						// pop, pop, concat, push
						Object o1 = pop(evalStack);
						Object o2 = pop(evalStack);
						if (pool != null)
						{
							try
							{
								evalStack.Push(pool[Int32.Parse(o2.ToString())] + "." + pool[Int32.Parse(o1.ToString())]);
							}
							catch (Exception)
							{
								if (o1 == dummy || o2 == dummy)
								{
									evalStack.Push(dummy);
								}
								else
								{
                                    evalStack.Push(o2 + "." + o1);
								}
							}
						}
						else
						{
							evalStack.Push(o2 + "." + o1);
						}
						break;
					
					case ActionConstants.sactionSetMember: 
						// pop, pop, pop
						pop(evalStack);
						pop(evalStack);
						pop(evalStack);
						break;
					
					case ActionConstants.sactionIncrement: 
					case ActionConstants.sactionDecrement: 
						break;
					
					case ActionConstants.sactionCallMethod: 
						pop(evalStack);
						pop(evalStack);
						Object obj2 = pop(evalStack);
						if (obj2 is String)
						{
							try
							{
								n = Int32.Parse((String) obj2);
							}
							catch (FormatException)
							{
								n = 1;
							}
						}
						else
						{
							n = Convert.ToInt32(((ValueType) obj2));
						}
						for (int k = 0; k < n; k++)
						{
							pop(evalStack);
						}
						evalStack.Push(dummy);
						break;
					
					case ActionConstants.sactionNewMethod: 
						/*Object meth =*/ pop(evalStack);
						/*Object cls =*/ pop(evalStack);
						num = Convert.ToInt32(((ValueType) pop(evalStack)));
						for (int k = 0; k < num; k++)
						{
							pop(evalStack);
						}
						evalStack.Push(dummy);
						break;
					
					case ActionConstants.sactionWith: 
						// pop
						pop(evalStack);
						break;
					
					case ActionConstants.sactionConstantPool: 
						pool = ((ConstantPool) a).pool;
						// no action
						break;
					
					case ActionConstants.sactionStrictMode: 
						break;
					
					
					case ActionConstants.sactionBitAnd: 
					case ActionConstants.sactionBitOr: 
					case ActionConstants.sactionBitLShift: 
						// pop, push
						break;
					
					case ActionConstants.sactionBitXor: 
					case ActionConstants.sactionBitRShift: 
					case ActionConstants.sactionBitURShift: 
						pop(evalStack);
						break;
						
						// Flash 6 actions
					
					case ActionConstants.sactionInstanceOf: 
						pop(evalStack);
						break;
					
					case ActionConstants.sactionEnumerate2: 
						// pop, push, more pushes?
						break;
					
					case ActionConstants.sactionStrictEquals: 
					case ActionConstants.sactionGreater: 
					case ActionConstants.sactionStringGreater: 
						pop(evalStack);
						break;
						
						// FEATURE_EXCEPTIONS
					
					case ActionConstants.sactionTry: 
						// do nothing
						break;
					
					case ActionConstants.sactionThrow: 
						pop(evalStack);
						break;
						
						// FEATURE_AS2_INTERFACES
					
					case ActionConstants.sactionCastOp: 
						break;
					
					case ActionConstants.sactionImplementsOp: 
						break;
						
						// Reserved for Quicktime
					
					case ActionConstants.sactionQuickTime: 
						break;
					
					default: 
						break;
					
				}
			}
		}
Exemple #27
0
        // look for the expected dialog to appear. If it does, make an accessibilty
        // helper for it.
        public override void Execute()
        {
            // base.Execute(ts); // can't call this yet as it executes the children
            WaitMsec();           // do call this but make sure Wait is reset to zero!
            Wait = 0;             // reset to zero so there is no delay after the dialog is found.
            // number is needed in diagnostics for the log
            if (Number == -1)
            {
                Number = TestState.getOnly().IncInstructionCount;
            }

            /// If present, use the selected dialog model title
            Context con = (Context)Ancestor(typeof(Context));

            if (m_select != null && m_select != "")
            {              // make a new model context node and move dialog's children to it
                m_select = Utilities.evalExpr(m_select);
                XmlDocument doc    = m_elt.OwnerDocument;
                XmlElement  modElt = doc.CreateElement("model");
                modElt.SetAttribute("select", m_select);
                XmlNodeList children = m_elt.ChildNodes;
                int         count    = children.Count;
                while (count > 0)
                {                                     // move dialog children to model
                    XmlNode child = children.Item(0); //get the first child
                    modElt.AppendChild(child);        // automatically removed from m_elt!!
                    count = children.Count;
                }
                m_elt.AppendChild(modElt);
                // set the title to look for
                // can only have one text node
                XmlNodeList pathNodes = Instructionator.selectNodes(this, m_select, makeName());
                m_log.isNotNull(pathNodes, makeNameTag() + " select='" + m_select + "' returned no model");
                m_log.isTrue(pathNodes.Count > 0, makeNameTag() + " select='" + m_select + "' returned no model nodes");
                // This is the model node
                XmlNode modNode = pathNodes.Item(0);
                if (m_title == null || m_title == "")
                {                  // no title override, so set the title from the model
                    string titleCheck = XmlFiler.getAttribute(modNode, "title");
                    if (titleCheck != null)
                    {
                        m_title = titleCheck;
                        m_log.paragraph("on-dialog title set from selected model " + titleCheck);
                    }
                }
                else
                {
                    m_log.paragraph("on-dialog title set from @title " + m_title);
                }
                string nameCheck = XmlFiler.getAttribute(modNode, "name");
                if (nameCheck != null)
                {
                    m_name = nameCheck;
                    m_log.paragraph("on-dialog name set from selected model " + nameCheck);
                }
                m_select = null;                 // can only do this one time in do-once or model
            }
            // if no name, try title
            if (m_title != null && m_title != "" && (m_name == null || m_name == ""))
            {
                m_name = m_title;
            }

            m_log.isNotNull(m_title, makeNameTag() + " No @title in script or model for this dialog.");
            m_log.isFalse(m_title == "", makeNameTag() + " @title in script or model is blank.");
            m_log.isFalse(m_name == null && !m_title.StartsWith("rexp#"), makeNameTag() + " No @name step in script or model for this dialog.");
            m_log.isFalse(m_name == "" && !m_title.StartsWith("rexp#"), makeNameTag() + " @name step in script or model is blank.");
            //if (m_title != null && m_title != "") m_title = Utilities.evalExpr(m_title);
            //if (m_name != null && m_name != "") m_name = Utilities.evalExpr(m_name);
            m_title = Utilities.evalExpr(m_title);
            m_name  = Utilities.evalExpr(m_name);

            m_log.paragraph(image());

            if (Application != null)
            {
                try { Application.Process.WaitForInputIdle(); }
                catch (Win32Exception e)
                { m_log.paragraph(makeNameTag() + " WaitForInputIdle: " + e.Message); }
            }
            // Give the window m_Rest seconds to show up
            int    startTick = System.Environment.TickCount;
            IntPtr foundHwndPtr;
            string name = null;
            Regex  rx   = null;

            if (m_title != null && m_title.StartsWith("rexp#"))
            {               // Create a regular expression object
                try { rx = new Regex(m_title.Substring(5)); }
                catch (ArgumentException e)
                {
                    m_log.fail(makeNameTag() + " title from rexp# [" + m_title.Substring(5)
                               + "] error: " + e.Message);
                }
            }

            while (!m_found)
            {               // If there is a regular expression, try it.
                if (rx != null)
                {           // try the main window name then other windows it may own via the regular expression
                    m_log.paragraph("Searching all processes");
                    Process[] allProcs = Process.GetProcesses();
                    for (int p = 0; p < allProcs.Length; p++)
                    {
                        Process pro = allProcs[p];
                        try {
                            if (rx.IsMatch(pro.MainWindowTitle))
                            {
                                m_found = true;
                                m_ah    = new AccessibilityHelper(pro.Handle);
                                break;
                            }
                        }
                        catch (Exception e) {
                            m_log.paragraph(makeNameTag() + " main title from rexp# [" + m_title.Substring(5)
                                            + "] process error: " + e.Message);
                        }
                        #region Attempt to explore process threads - useful?
                        // try the windows that belong to this process

                        /*try {
                         *      foreach (ProcessThread pt in pro.Threads)
                         *      {
                         *
                         *              string para = "on-dialog matching proc [" + pro.ProcessName + ":";
                         *              if (pt.Site != null) para += pt.Site.Name + "]";
                         *              else                 para += "]";
                         *              m_log.paragraph(para);
                         *              if (pt.Site != null && rx.IsMatch(pt.Site.Name)) {
                         *                      m_found = true;
                         *                      m_ah = new AccessibilityHelper(pro.Handle);
                         *                      break;
                         *              }
                         *      }
                         * }
                         * catch (Exception e)
                         * {
                         *      m_log.paragraph("on-dialog title from rexp# [" + m_title.Substring(5)
                         + "] process error: " + e.Message);
                         + } */
                        #endregion
                    }
                }
                if (!m_found)
                {                   // get the window handle for windows with the right name
                    // unfortuneately, other windows, or partially formed windows
                    // seem to be obtained too.
                    m_log.paragraph("Searching the desktop for a window via FindWindow");
                    if (rx != null)
                    {
                        foundHwndPtr = FindWindow(null, null);
                    }
                    else
                    {
                        foundHwndPtr = FindWindow(null, m_title);
                    }
                    if ((int)foundHwndPtr != 0)
                    {                       // is this the window? Is it completely formed?
                        m_ah = new AccessibilityHelper(foundHwndPtr);
                        if (m_ah == null)
                        {
                            m_log.paragraph(makeNameTag() + " Obtained window with no Accessibiilty!");
                        }
                        else                        // this window has accessibility - hope it's fully built
                        {                           // is this or one of its children the window?
                            name = m_ah.Name;       //when name1 = "", m_ah is probably bad - i.e. not an object
                            if (name == "")
                            {
                            }                               // do nothing, keep looking
                            else if (name.Equals(m_title) || name.Equals(this.m_name))
                            {                               // this is likely it
                                m_found = true;
                            }
                            else                            // m_ah might be the ah for the main app or dialog window
                            {                               // Maybe one of its children is the window we want
                                m_log.paragraph("Searching for a child window");
                                m_ah = m_ah.FindChild(m_title, AccessibleRole.Dialog);
                                if (m_ah != null)
                                {                                 // is this the window?
                                    name = m_ah.Name;             // name1 can't be null
                                    if (name == "")
                                    {
                                    }                                       // do nothing, keep looking
                                    else if (name.Equals(m_title) || name.Equals(this.m_name))
                                    {                                       // this might be it
                                        m_found = true;
                                    }
                                }
                            }
                        }
                    }
                }

                if (Utilities.NumTicks(startTick, System.Environment.TickCount) > m_until)
                {
                    break;                      // time is up
                }
                System.Threading.Thread.Sleep(100);
            }

            m_Rest = 0;             // don't wait later when base.Execute is invoked

            if (m_found)
            {
                m_DlgHwndStack.Push(m_ah.HWnd);
            }
            else
            {               // Didn't find the window
                m_ah = null;
            }

            string contextPass, contextFail;
            PassFailInContext(OnPass, OnFail, out contextPass, out contextFail);                //  out m_onPass, out m_onFail);
            m_log.paragraph(makeNameTag() + " passIn=" + OnPass + " failIn=" + OnFail + " pass="******" fail=" + contextFail);
            if (!m_found && contextFail == "skip")
            {
                return;                 // quietly exit
            }
            m_log.isTrue(m_found, makeNameTag() + m_title + @"' was not created or not accessible");
            if (name == null)
            {
                m_log.paragraph(makeNameTag() + " Wierd: ah exists but name was null - should NEVER happen!!");
                name = "";
            }
            if (contextPass == "assert")
            {
                m_log.fail(makeNameTag() + m_title + " was not supposed to display.");
            }

            base.Execute();
            m_log.result(this);
            base.Finished = true;               // finished processing this dialog context
            m_DlgHwndStack.Pop();

            if (m_DlgHwndStack.Count > 0)
            {
                int hwnd = (int)m_DlgHwndStack.Peek();
                SendMessage((IntPtr)hwnd,
                            (int)Msg.WM_SETFOCUS, 0, 0);
                m_log.paragraph(makeNameTag() + " Sent Focus message to containing context object");
                //	m_ah.Parent.SendWindowMessage((int)SIL.FieldWorks.Common.Utils.Win32.WinMsgs.WM_SETFOCUS,0,0);
            }
        }
        public static void Main(string[] args)
        {
            // The path to the documents directory.
            string dataDir = Path.GetFullPath("../../../Data/");

            // Load the source PDF file
            Document doc = new Document(dataDir + "input.pdf");

            // Define the default resolution for image
            int defaultResolution = 72;

            System.Collections.Stack graphicsState = new System.Collections.Stack();
            // Define array list object which will hold image names
            System.Collections.ArrayList imageNames = new System.Collections.ArrayList(doc.Pages[1].Resources.Images.Names);
            // Insert an object to stack
            graphicsState.Push(new System.Drawing.Drawing2D.Matrix(1, 0, 0, 1, 0, 0));

            // Get all the operators on first page of document
            foreach (Operator op in doc.Pages[1].Contents)
            {
                // Use GSave/GRestore operators to revert the transformations back to previously set
                Operator.GSave    opSaveState    = op as Operator.GSave;
                Operator.GRestore opRestoreState = op as Operator.GRestore;
                // Instantiate ConcatenateMatrix object as it defines current transformation matrix.
                Operator.ConcatenateMatrix opCtm = op as Operator.ConcatenateMatrix;
                // Create Do operator which draws objects from resources. It draws Form objects and Image objects
                Operator.Do opDo = op as Operator.Do;

                if (opSaveState != null)
                {
                    // Save previous state and push current state to the top of the stack
                    graphicsState.Push(((System.Drawing.Drawing2D.Matrix)graphicsState.Peek()).Clone());
                }
                else if (opRestoreState != null)
                {
                    // Throw away current state and restore previous one
                    graphicsState.Pop();
                }
                else if (opCtm != null)
                {
                    System.Drawing.Drawing2D.Matrix cm = new System.Drawing.Drawing2D.Matrix(
                        (float)opCtm.Matrix.A,
                        (float)opCtm.Matrix.B,
                        (float)opCtm.Matrix.C,
                        (float)opCtm.Matrix.D,
                        (float)opCtm.Matrix.E,
                        (float)opCtm.Matrix.F);

                    // Multiply current matrix with the state matrix
                    ((System.Drawing.Drawing2D.Matrix)graphicsState.Peek()).Multiply(cm);

                    continue;
                }
                else if (opDo != null)
                {
                    // In case this is an image drawing operator
                    if (imageNames.Contains(opDo.Name))
                    {
                        System.Drawing.Drawing2D.Matrix lastCTM = (System.Drawing.Drawing2D.Matrix)graphicsState.Peek();
                        // Create XImage object to hold images of first pdf page
                        XImage image = doc.Pages[1].Resources.Images[opDo.Name];

                        // Get image dimensions
                        double scaledWidth  = Math.Sqrt(Math.Pow(lastCTM.Elements[0], 2) + Math.Pow(lastCTM.Elements[1], 2));
                        double scaledHeight = Math.Sqrt(Math.Pow(lastCTM.Elements[2], 2) + Math.Pow(lastCTM.Elements[3], 2));
                        // Get Height and Width information of image
                        double originalWidth  = image.Width;
                        double originalHeight = image.Height;

                        // Compute resolution based on above information
                        double resHorizontal = originalWidth * defaultResolution / scaledWidth;
                        double resVertical   = originalHeight * defaultResolution / scaledHeight;

                        // Display Dimension and Resolution information of each image
                        Console.Out.WriteLine(
                            string.Format(dataDir + "image {0} ({1:.##}:{2:.##}): res {3:.##} x {4:.##}",
                                          opDo.Name, scaledWidth, scaledHeight, resHorizontal,
                                          resVertical));
                    }
                }
            }
        }
        internal bool LoadContent(ModernMenuItem item, out bool isLeft, out bool AnimationShown)
        {
            int previousIndex, currentIndex;

            currentIndex  = item.Index;
            previousIndex = 0;
            if (recentActions.Count > 0)
            {
                ModernMenuItem previousItem = recentActions.Peek() as ModernMenuItem;
                previousIndex = previousItem.Index;
            }
            isLeft = currentIndex <= previousIndex;
            System.Diagnostics.Debug.WriteLine("IsLeft=" + isLeft);
            AnimationShown = false;
            if (item.Items != null && item.Items.Count > 0)
            {
                return(true);
            }


            if (this.Content is ModernContent currentContent && !suppressCanBeClosed && !currentContent.CanBeClosed())
            {
                return(false);
            }



            recentActions.Push(item);
            if (item.ContentType != null && item.ContentType.IsSubclassOf(typeof(ModernContent)))
            {
                Storyboard story = isLeft ? ((Storyboard)FindResource("ContentLeftInStoryboard")).Clone() : ((Storyboard)FindResource("ContentRightInStoryboard")).Clone();
                if (Cache.ContainsKey(item))
                {
                    //item has already in the Cache
                    ModernContent content = Cache[item];
                    loadedMenu = item;
                    if (LoadContentSub(content, out AnimationShown, story))
                    {
                        return(true);
                    }
                }
                else
                {
                    ModernContent content = (ModernContent)Activator.CreateInstance(item.ContentType);
                    Cache.Add(item, content);
                    loadedMenu = item;
                    if (LoadContentSub(content, out AnimationShown, story))
                    {
                        return(true);
                    }
                }
            }
            else
            {
                this.Content             = null;
                this.CommandArea         = null;
                this.IsContentDetachable = false;
                this.IsContentDetached   = false;
                loadedMenu    = item;
                nextStatusBar = DefaultStatusBar;
                if (this.StatusBar != nextStatusBar)
                {
                    if (this.StatusBar != null)
                    {
                        this.StatusBar.BeginStoryboard(HideStatusbarStoryboard);
                        System.Diagnostics.Debug.WriteLine("Hide StatueBar line 190");
                    }
                    else
                    {
                        this.StatusBar = nextStatusBar;
                        if (this.StatusBar != null)
                        {
                            this.StatusBar.BeginStoryboard(ShowStatusbarStoryboard);
                            System.Diagnostics.Debug.WriteLine("Show StatusBar line 198");
                        }
                    }
                }
            }
            return(true);
        }
        private bool EvaluatePostfix()
        {
            operandStack.Clear();
            Operand num;

            System.Array postfix = postfixStack.ToArray();
            System.Array.Reverse(postfix);

            foreach (var token in postfix)
            {
                if (token.GetType() == typeof(Operator))
                {
                    num = new Operand();

                    switch (((Operator)token).type)
                    {
                    case OperatorType.BINARY:
                        if (operandStack.Count < 2)
                        {
                            lastError = "Evaluation error, a binary operator needs 2 operands";
                            return(false);
                        }

                        operandStack.Push(((Operator)token).semantic(ref num,
                                                                     ((Operand)operandStack.Pop()), ((Operand)operandStack.Pop())));
                        break;

                    case OperatorType.UNARY:
                        if (operandStack.Count < 1)
                        {
                            lastError = "Evaluation error, an unary operator needs 1 operand";
                            return(false);
                        }

                        operandStack.Push(((Operator)token).semantic(ref num,
                                                                     ((Operand)operandStack.Pop())));
                        break;
                    }
                }
                else if (token.GetType() == typeof(Operand))
                {
                    operandStack.Push(token);
                }
                else if (token.GetType() == typeof(FunctionCall))
                {
                    num = new Operand();
                    argumentList.Clear();

                    for (int i = 0; i < ((FunctionCall)token).args; i++)
                    {
                        if (operandStack.Count != 0)
                        {
                            argumentList.Add(operandStack.Pop());
                        }
                        else
                        {
                            lastError = "Evaluation error, wrong argument count";
                            return(false);
                        }
                    }

                    operandStack.Push(((FunctionCall)token).definition(ref num,
                                                                       (Operand[])argumentList.ToArray(typeof(Operand))));
                }
            }

            if (operandStack.Count != 1)
            {
                lastError = "Evaluation error, unstacked operands";
                return(false);
            }

            lastResult = ((Operand)operandStack.Peek());
            varTable.Remove("ans");
            varTable.Add("ans", lastResult);
            return(true);
        }
Exemple #31
0
        static void Main(string[] args)
        {
            int cant = 3;

            //int [] vectores = new int [cant];
            //int [] positivos = new int [cant];
            //int [] negativos=new int [cant];
            System.Collections.Stack pila      = new System.Collections.Stack();
            System.Collections.Stack positivos = new System.Collections.Stack();
            System.Collections.Stack negativos = new System.Collections.Stack();

            for (int i = 0; i < cant; i++)
            {
                Console.WriteLine("Ingrese numero {0}", i + 1);
                pila.Push(Valor1.Validar(int.Parse(Console.ReadLine())));



                if ((int)pila.Peek() >= 0)
                {
                    positivos.Push(pila.Peek());
                }
                else
                {
                    negativos.Push(pila.Peek());
                }
            }

            Console.WriteLine("\nNormal:\n");
            foreach (int valor in pila)
            {
                if (valor == 0)
                {
                    Console.WriteLine("");
                }
                else
                {
                    Console.WriteLine("{0}\n", valor);
                }
            }
            Console.WriteLine("\nPositivos:\n");
            foreach (int valor in positivos)
            {
                if (valor == 0)
                {
                    Console.WriteLine("");
                }
                else
                {
                    Console.WriteLine("{0}\n", valor);
                }
            }
            Console.WriteLine("\nNegativos:\n");
            foreach (int valor in negativos)
            {
                if (valor == 0)
                {
                    Console.WriteLine("");
                }
                else
                {
                    Console.WriteLine("{0}\n", valor);
                }
            }

            int cantidad  = pila.Count;
            int cantidad2 = positivos.Count;
            int cantidad3 = negativos.Count;

            for (int i = 0; i < cantidad; i++)
            {
                pila.Pop();
            }



            for (int i = 0; i < cantidad2; i++)
            {
                positivos.Pop();
            }



            for (int i = 0; i < cantidad3; i++)
            {
                negativos.Pop();
            }
            Console.ReadKey();
            Console.WriteLine("pila: {0}\npositivos: {1}\nnegativos: {2}\n", pila.Count, positivos.Count, negativos.Count);



            Console.ReadKey();
        }
Exemple #32
0
        // look for the expected dialog to appear. If it does, make an accessibilty
        // helper for it.
        public override void Execute()
        {
            // base.Execute(ts); // can't call this yet as it executes the children
            Wait();             // do call this but make sure Rest is reset to zero!
            Rest = 0;           // reset to zero so there is no delay after the dialog is found.
            // number is needed in diagnostics for the log
            if (Number == -1)
            {
                Number = TestState.getOnly().IncInstructionCount;
            }

            Process proc = Application.Process;

            /// If present, use the selected dialog model title
            Context con = (Context)Ancestor(typeof(Context));

            if (m_select != null && m_select != "")
            {              // make a new model context node and move dialog's children to it
                XmlDocument doc    = m_elt.OwnerDocument;
                XmlElement  modElt = doc.CreateElement("model");
                modElt.SetAttribute("select", m_select);
                XmlNodeList children = m_elt.ChildNodes;
                int         count    = children.Count;
                while (count > 0)
                {                                     // move dialog children to model
                    XmlNode child = children.Item(0); //get the first child
                    modElt.AppendChild(child);        // automatically removed from m_elt!!
                    count = children.Count;
                }
                m_elt.AppendChild(modElt);
                // set the title to look for
                // can only have one text node
                XmlNodeList pathNodes = XmlInstructionBuilder.selectNodes(this, m_select, makeName());
                m_log.isNotNull(pathNodes, "dialog " + this.Id + " select='" + m_select + "' returned no model");
                m_log.isTrue(pathNodes.Count > 0, "dialog " + this.Id + " select='" + m_select + "' returned no model nodes");
                // This is the model node
                XmlNode modNode = pathNodes.Item(0);
                m_title  = XmlFiler.getAttribute(modNode, "title");
                m_name   = XmlFiler.getAttribute(modNode, "name");
                m_select = null;                 // can only do this one time in do-once or model
            }
            if (m_title != null && m_title != "")
            {
                m_title = Utilities.evalExpr(m_title);
            }
            if (m_name != null && m_name != "")
            {
                m_name = Utilities.evalExpr(m_name);
            }

            m_log.paragraph(image());

            // Give the window m_Rest seconds to show up
            int    startTick = System.Environment.TickCount;
            IntPtr foundHwndPtr;
            string name = null;

            while (!m_found)
            {               // If there is a regular expression, try it.
                if (m_title != null && m_title.StartsWith("rexp#"))
                {           // match the window title via the regular expression
                    Process[] allProcs = Process.GetProcesses();
                    Regex     rx       = null;
                    try { rx = new Regex(m_title.Substring(5)); }
                    catch (ArgumentException e)
                    {
                        m_log.paragraph("on-dialog title from rexp# " + m_title.Substring(5)
                                        + " error: " + e.Message);
                        break;
                    }
                    for (int p = 0; p < allProcs.Length; p++)
                    {
                        Process             pro = allProcs[p];
                        AccessibilityHelper ah  = new AccessibilityHelper(pro.Handle);
                        if (rx.IsMatch(ah.Name))
                        {
                            m_ah    = ah;
                            m_found = true;
                            break;
                        }
                    }
                }
                else
                {                   // get the window handle for windows with the right name
                    // unfortuneately, other windows, or partially formed windows
                    // seem to be obtained too.
                    foundHwndPtr = FindWindow(null, m_title);
                    if ((int)foundHwndPtr != 0)
                    {                       // is this the window? Is it completely formed?
                        m_ah = new AccessibilityHelper(foundHwndPtr);
                        if (m_ah == null)
                        {
                            m_log.paragraph("Obtained window with no Accessibiilty!");
                        }
                        else                        // this window has accessibility - hope it's fully built
                        {                           // is this or one of its children the window?
                            name = m_ah.Name;       //when name1 = "", m_ah is probably bad - i.e. not an object
                            if (name == "")
                            {
                            }                               // do nothing, keep looking
                            else if (name.Equals(m_title) || name.Equals(this.m_name))
                            {                               // this is likely it
                                m_found = true;
                            }
                            else                            // m_ah might be the ah for the main app or dialog window
                            {                               // Maybe one of its children is the window we want
                                m_ah = m_ah.FindChild(m_title, AccessibleRole.Dialog);
                                if (m_ah != null)
                                {                                 // is this the window?
                                    name = m_ah.Name;             // name1 can't be null
                                    if (name == "")
                                    {
                                    }                                       // do nothing, keep looking
                                    else if (name.Equals(m_title) || name.Equals(this.m_name))
                                    {                                       // this might be it
                                        m_found = true;
                                    }
                                }
                            }
                        }
                    }
                }

                if (Utilities.NumTicks(startTick, System.Environment.TickCount) > m_until)
                {
                    break;                      // time is up
                }
                System.Threading.Thread.Sleep(100);
            }

            m_Rest = 0;             // don't wait later when base.Execute is invoked

            if (m_found)
            {
                m_DlgHwndStack.Push(m_ah.HWnd);
            }
            else
            {               // Didn't find the window
                m_ah = null;
            }

            string contextPass, contextFail;

            PassFailInContext(OnPass, OnFail, out contextPass, out contextFail);                //  out m_onPass, out m_onFail);
            m_log.paragraph("on-dialog: passIn=" + OnPass + " failIn=" + OnFail + " pass="******" fail=" + contextFail);
            if (!m_found && contextFail == "skip")
            {
                return;                 // quietly exit
            }
            isTrue(m_found, "Dialog '" + m_title + @"' was not created or not accessible");
            if (name == null)
            {
                m_log.paragraph("Wierd: ah exists but name was null - should NEVER happen!!");
                name = "";
            }
            if (contextPass == "assert")
            {
                fail("Dialog '" + m_title + "' was not supposed to display.");
            }

            base.Execute();
            m_log.result(this);
            base.Finished = true;               // finished processing this dialog context
            m_DlgHwndStack.Pop();

            if (m_DlgHwndStack.Count > 0)
            {
                int hwnd = (int)m_DlgHwndStack.Peek();
                SIL.FieldWorks.Common.Utils.Win32.SendMessage((IntPtr)hwnd,
                                                              (int)SIL.FieldWorks.Common.Utils.Win32.WinMsgs.WM_SETFOCUS, 0, 0);
                m_log.paragraph("Sent Focus message to containing context object");
                //	m_ah.Parent.SendWindowMessage((int)SIL.FieldWorks.Common.Utils.Win32.WinMsgs.WM_SETFOCUS,0,0);
            }
        }
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Images();

            // Load the source PDF file
            Document doc = new Document(dataDir+ "ImageInformation.pdf");

            // Define the default resolution for image
            int defaultResolution = 72;
            System.Collections.Stack graphicsState = new System.Collections.Stack();
            // Define array list object which will hold image names
            System.Collections.ArrayList imageNames = new System.Collections.ArrayList(doc.Pages[1].Resources.Images.Names);
            // Insert an object to stack
            graphicsState.Push(new System.Drawing.Drawing2D.Matrix(1, 0, 0, 1, 0, 0));

            // Get all the operators on first page of document
            foreach (Operator op in doc.Pages[1].Contents)
            {
                // Use GSave/GRestore operators to revert the transformations back to previously set
                Operator.GSave opSaveState = op as Operator.GSave;
                Operator.GRestore opRestoreState = op as Operator.GRestore;
                // Instantiate ConcatenateMatrix object as it defines current transformation matrix.
                Operator.ConcatenateMatrix opCtm = op as Operator.ConcatenateMatrix;
                // Create Do operator which draws objects from resources. It draws Form objects and Image objects
                Operator.Do opDo = op as Operator.Do;

                if (opSaveState != null)
                {
                    // Save previous state and push current state to the top of the stack
                    graphicsState.Push(((System.Drawing.Drawing2D.Matrix)graphicsState.Peek()).Clone());
                }
                else if (opRestoreState != null)
                {
                    // Throw away current state and restore previous one
                    graphicsState.Pop();
                }
                else if (opCtm != null)
                {
                    System.Drawing.Drawing2D.Matrix cm = new System.Drawing.Drawing2D.Matrix(
                       (float)opCtm.Matrix.A,
                       (float)opCtm.Matrix.B,
                       (float)opCtm.Matrix.C,
                       (float)opCtm.Matrix.D,
                       (float)opCtm.Matrix.E,
                       (float)opCtm.Matrix.F);

                    // Multiply current matrix with the state matrix
                    ((System.Drawing.Drawing2D.Matrix)graphicsState.Peek()).Multiply(cm);

                    continue;
                }
                else if (opDo != null)
                {
                    // In case this is an image drawing operator
                    if (imageNames.Contains(opDo.Name))
                    {
                        System.Drawing.Drawing2D.Matrix lastCTM = (System.Drawing.Drawing2D.Matrix)graphicsState.Peek();
                        // Create XImage object to hold images of first pdf page
                        XImage image = doc.Pages[1].Resources.Images[opDo.Name];

                        // Get image dimensions
                        double scaledWidth = Math.Sqrt(Math.Pow(lastCTM.Elements[0], 2) + Math.Pow(lastCTM.Elements[1], 2));
                        double scaledHeight = Math.Sqrt(Math.Pow(lastCTM.Elements[2], 2) + Math.Pow(lastCTM.Elements[3], 2));
                        // Get Height and Width information of image
                        double originalWidth = image.Width;
                        double originalHeight = image.Height;

                        // Compute resolution based on above information
                        double resHorizontal = originalWidth * defaultResolution / scaledWidth;
                        double resVertical = originalHeight * defaultResolution / scaledHeight;

                        // Display Dimension and Resolution information of each image
                        Console.Out.WriteLine(
                                string.Format(dataDir + "image {0} ({1:.##}:{2:.##}): res {3:.##} x {4:.##}",
                                             opDo.Name, scaledWidth, scaledHeight, resHorizontal,
                                             resVertical));
                    }
                }
            }
            
            
        }
 /* Returns the root node of the AST.  It only makes sense to call
  * this after a successful parse. */
 internal Node rootNode()
 {
     return((Node)nodes.Peek());
 }
        public static void MostrarColeccionesNoGenerics()
        {
            Console.Clear();
            Console.WriteLine("******************************");
            Console.WriteLine("*****Pilas No Genéricas*******");
            Console.WriteLine("******************************");
            Console.ReadLine();

            //DECLARO E INSTANCIO UNA COLECCION DE TIPO LIFO
            System.Collections.Stack pila = new System.Collections.Stack();

            pila.Push(1);
            pila.Push(2);
            pila.Push(3);
            pila.Push(4);

            Console.WriteLine("Agrego elementos a la pila...");
            Console.WriteLine("Utilizo pila.Push()");
            Console.WriteLine("Orden de los elementos: 1 - 2 - 3 - 4");
            Console.ReadLine();

            Console.WriteLine("Muestro el primer elemento de la pila...");
            Console.WriteLine("Utilizo pila.Peek()");
            Console.ReadLine();

            Console.WriteLine(pila.Peek());
            Console.ReadLine();

            Console.WriteLine("Muestro todos los elementos de la pila...");
            Console.WriteLine("Recorro con un foreach. No saco los elementos de la pila.");
            Console.ReadLine();

            foreach (int elemento in pila)
            {
                Console.WriteLine(elemento);
            }

            Console.ReadLine();

            Console.WriteLine("Desapilo todos los elementos de la pila...");
            Console.WriteLine("Utilizo pila.Pop(). Recorro con un for");
            Console.ReadLine();

            int cantidad = pila.Count;

            for (int i = 0; i < cantidad; i++)
            {
                Console.WriteLine("Elemento {0} = {1}", i, pila.Pop());
            }

            Console.ReadLine();

            Console.WriteLine("Cantidad de elementos en la pila = {0}", pila.Count);
            Console.ReadLine();

            Console.Clear();
            Console.WriteLine("******************************");
            Console.WriteLine("****Colas No Genéricas********");
            Console.WriteLine("******************************");
            Console.ReadLine();

            System.Collections.Queue cola = new System.Collections.Queue();

            cola.Enqueue(1);
            cola.Enqueue(2);
            cola.Enqueue(3);
            cola.Enqueue(4);

            Console.WriteLine("Agrego elementos a la cola...");
            Console.WriteLine("Utilizo pila.Enqueue()");
            Console.WriteLine("Orden de los elementos: 1 - 2 - 3 - 4");
            Console.ReadLine();

            Console.WriteLine("Muestro el primer elemento de la cola...");
            Console.WriteLine("Utilizo cola.Peek()");
            Console.ReadLine();

            Console.WriteLine(cola.Peek());
            Console.ReadLine();

            Console.WriteLine("Muestro todos los elementos de la cola...");
            Console.WriteLine("Recorro con un foreach");
            Console.ReadLine();

            foreach (int elemento in cola)
            {
                Console.WriteLine(elemento);
            }

            Console.ReadLine();

            Console.WriteLine("Saco todos los elementos de la cola...");
            Console.WriteLine("Utilizo cola.Dequeue(). Recorro con un for");
            Console.ReadLine();

            cantidad = cola.Count;

            for (int i = 0; i < cantidad; i++)
            {
                Console.WriteLine("Elemento {0} = {1}", i, cola.Dequeue());
            }

            Console.ReadLine();

            Console.WriteLine("Cantidad de elementos en la cola = {0}", cola.Count);
            Console.ReadLine();

            Console.Clear();
            Console.WriteLine("******************************");
            Console.WriteLine("******Listas Dinamicas********");
            Console.WriteLine("******************************");
            Console.ReadLine();

            System.Collections.ArrayList vec = new System.Collections.ArrayList();

            vec.Add(1);
            vec.Add(4);
            vec.Add(3);
            vec.Add(2);

            Console.WriteLine("Agrego elementos al ArrayList...");
            Console.WriteLine("Utilizo vec.Add()");
            Console.WriteLine("Orden de los elementos: 1 - 4 - 3 - 2");
            Console.ReadLine();

            Console.WriteLine("Muestro todos los elementos del ArrayList...");
            Console.WriteLine("Recorro con un foreach");
            Console.ReadLine();

            foreach (int elemento in vec)
            {
                Console.WriteLine(elemento);
            }

            Console.ReadLine();

            Console.WriteLine("Ordeno los elementos del ArrayList...");
            Console.WriteLine("Utilizo vec.Sort(). Recorro con un for");
            Console.ReadLine();

            vec.Sort();

            cantidad = vec.Count;

            for (int i = 0; i < cantidad; i++)
            {
                Console.WriteLine("Elemento {0} = {1}", i, vec[i]);
            }

            Console.ReadLine();

            Console.WriteLine("Ordeno los elementos del ArrayList...");
            Console.WriteLine("Utilizo vec.Reverse(). Recorro con un for");
            Console.ReadLine();

            vec.Reverse();

            cantidad = vec.Count;

            for (int i = 0; i < cantidad; i++)
            {
                Console.WriteLine("Elemento {0} = {1}", i, vec[i]);
            }

            Console.ReadLine();

            Console.Clear();
            Console.WriteLine("******************************");
            Console.WriteLine("*********HashTable************");
            Console.WriteLine("******************************");
            Console.ReadLine();

            System.Collections.Hashtable ht = new System.Collections.Hashtable();

            ht.Add(1, "valor 1");
            ht.Add(4, "valor 4");
            ht.Add(3, "valor 3");
            ht.Add(2, "valor 2");

            Console.WriteLine("Agrego elementos al HashTable...");
            Console.WriteLine("Utilizo vec.Add()");
            Console.WriteLine("Orden de los elementos: 1 - 4 - 3 - 2");
            Console.ReadLine();

            Console.WriteLine("Muestro todos los elementos del HashTable...");
            Console.WriteLine("Recorro con un for");
            Console.ReadLine();

            cantidad = ht.Count;

            for (int i = 1; i <= cantidad; i++)
            {
                Console.WriteLine("Elemento {0} = {1}", i, ht[i]);
            }

            Console.ReadLine();
        }