Ejemplo n.º 1
0
        private void TestReferenceTypeVariables()
        {
            ExpressionContext  context   = new ExpressionContext();
            VariableCollection variables = context.Variables;

            variables.Add("a", "string");
            variables.Add("b", 100);

            var    e      = new DynamicExpression <string>("a + b + a.tostring()", ExpressionLanguage.Flee);
            string result = e.Invoke(context);

            Assert.AreEqual("string" + 100 + "string", result);

            variables["a"].Value = "test";
            variables["b"].Value = 1;
            result = e.Invoke(context);
            Assert.AreEqual("test" + 1 + "test", result);

            // Test null value
            variables.Add("nullvar", null);

            var e2 = new DynamicExpression <bool>("nullvar = null", ExpressionLanguage.Flee);

            Assert.IsTrue(e2.Invoke(context));
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            //Sample Scenario 1
            ExpressionContext context = new ExpressionContext();

            context.ParserOptions.DecimalSeparator          = '.';
            context.ParserOptions.FunctionArgumentSeparator = ',';
            VariableCollection variables = context.Variables;

            variables.Add("a", 1);
            variables.Add("b", 1);

            IGenericExpression <bool> e = context.CompileGeneric <bool>("a=1 AND b=0");
            bool result = e.Evaluate();

            //Sample Scenario 2
            ExpressionContext  context2   = new ExpressionContext();
            VariableCollection variables2 = context2.Variables;

            variables2.Add("a", 100);
            variables2.Add("b", 1);
            variables2.Add("c", 24);

            IGenericExpression <bool> ge = context2.CompileGeneric <bool>("(a = 100 OR b > 0) AND c <> 2");
            bool result2 = ge.Evaluate();

            IGenericExpression <decimal> ge1 = context2.CompileGeneric <decimal>("1/2");
            decimal result3 = ge1.Evaluate();

            System.Console.ReadKey();
        }
Ejemplo n.º 3
0
        private void TestValueTypeVariables()
        {
            ExpressionContext  context   = new ExpressionContext();
            VariableCollection variables = context.Variables;

            variables.Add("a", 100);
            variables.Add("b", -100);
            variables.Add("c", DateTime.Now);

            var e1     = new DynamicExpression <int>("a+b", ExpressionLanguage.Flee);
            int result = e1.Invoke(context);

            Assert.AreEqual(100 + -100, result);

            variables["B"].Value = 1000;
            result = e1.Invoke(context);
            Assert.AreEqual(100 + 1000, result);

            var e2 = new DynamicExpression <string>("c.tolongdatestring() + c.Year.tostring()", ExpressionLanguage.Flee);

            Assert.AreEqual(DateTime.Now.ToLongDateString() + DateTime.Now.Year, e2.Invoke(context));

            // Test null value
            //variables["a"].Value = null;
            //e1 = new DynamicExpression<int>("a", ExpressionLanguage.Flee);
            //Assert.AreEqual(0, e1.Invoke(context));
        }
Ejemplo n.º 4
0
        public void ShouldBeAbleToClearVariablesOfCurrentScope()
        {
            _variables = new VariableCollection();

            _variables.Scopes.SetCurrent("Test Scenario 1");

            _variables.Add(_globalVariableName, _globalVariableValue);

            _variables.Count().Should().Be(1);
            _variables.Contains(_globalVariableName).Should().BeTrue();
            _variables.GetValue(_globalVariableName).Should().Be(_globalVariableValue);

            _variables.Scopes.SetCurrent("Function 1");

            _variables.Add(_localVariableName, _localVariableValue);

            _variables.Count().Should().Be(2);
            _variables.CountCurrentScopeKeys().Should().Be(1);
            _variables.Contains(_globalVariableName).Should().BeTrue();
            _variables.GetValue(_globalVariableName).Should().Be(_globalVariableValue);
            _variables.Contains(_localVariableName).Should().BeTrue();
            _variables.GetValue(_localVariableName).Should().Be(_localVariableValue);

            _variables.RemoveCurrentScopedValues();
            _variables.Count().Should().Be(1);
            _variables.CountCurrentScopeKeys().Should().Be(0);
            _variables.Contains(_globalVariableName).Should().BeTrue();
            _variables.GetValue(_globalVariableName).Should().Be(_globalVariableValue);
            _variables.Contains(_localVariableName).Should().BeFalse();
            _variables.GetValue(_localVariableName).Should().Be(null);
        }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            //Sample Scenario 1
            ExpressionContext  context   = new ExpressionContext();
            VariableCollection variables = context.Variables;

            variables.Add("a", 1);
            variables.Add("b", 1);

            IGenericExpression <bool> e = context.CompileGeneric <bool>("a=1 AND b=0");
            bool result = e.Evaluate();

            //Sample Scenario 2
            ExpressionContext  context2   = new ExpressionContext();
            VariableCollection variables2 = context2.Variables;

            variables2.Add("a", 100);
            variables2.Add("b", 1);
            variables2.Add("c", 24);

            IGenericExpression <bool> ge = context2.CompileGeneric <bool>("(a = 100 OR b > 0) AND c <> 2");
            bool result2 = ge.Evaluate();

            System.Console.ReadKey();
        }
Ejemplo n.º 6
0
        //*************************************************************************
        //*	Private																																*
        //*************************************************************************
        //*************************************************************************
        //*	Protected																															*
        //*************************************************************************
        //*************************************************************************
        //*	Public																																*
        //*************************************************************************

        //*-----------------------------------------------------------------------*
        //*	GetCollection																													*
        //*-----------------------------------------------------------------------*
        /// <summary>
        /// Return the first collection matching the specified expression.
        /// </summary>
        /// <param name="expression">
        /// Basic expression to parse. Any attribute names are square bracketed.
        /// For example, to find a collection where the datatype attribute value
        /// is equal to 'object', use [datatype] = object
        /// </param>
        /// <returns>
        /// Reference to the first matching collection, if found. Otherwise, null.
        /// </returns>
        public AttributeCollection GetCollection(string expression)
        {
            string                    content        = "";
            ExpressionContext         context        = null;
            IGenericExpression <bool> evaluator      = null;
            string                    expressionText = "";
            StringCollection          fieldNames     = new StringCollection();
            string                    keyword        = "";
            MatchCollection           matches        = null;
            //double nValue = 0d;
            AttributeCollection result    = null;
            VariableCollection  variables = null;

            if (expression?.Length > 0)
            {
                expressionText = expression;
                context        = new ExpressionContext();
                variables      = context.Variables;
                matches        = Regex.Matches(expression,
                                               ResourceMain.AttributeKeywordPattern);
                foreach (Match match in matches)
                {
                    keyword = Tools.GetValue(match, "keyword");
                    content = Tools.GetValue(match, "content");
                    if (content.Length > 0)
                    {
                        //	This value is either a field name or a match value.
                        if (keyword.Length > 0)
                        {
                            //	Field name found.
                            fieldNames.AddUnique(content);
                            expressionText = expressionText.Replace(keyword, "F" + content);
                            variables.Add("F" + content, content);
                        }
                        else
                        {
                            //	Normal value.
                            variables.Add(content, content);
                        }
                    }
                }
                foreach (AttributeCollection collection in this)
                {
                    //	Prepare the local variables.
                    foreach (string field in fieldNames)
                    {
                        variables["F" + field] = collection.GetValue(field);
                    }
                    evaluator = context.CompileGeneric <bool>(expressionText);
                    if (evaluator.Evaluate())
                    {
                        result = collection;
                        break;
                    }
                }
            }
            return(result);
        }
Ejemplo n.º 7
0
        public override VariableCollection GetVariables()
        {
            VariableCollection res = base.GetVariables();

            res.Add(Type);
            res.Add(Target);
            res.Add(Workspace);
            return(res);
        }
        public void NoExist()
        {
            var c = new VariableCollection();

            c.Add("int", "x ints");
            Assert.IsFalse(c.Exists("x ints a"));
        }
        public void Simple()
        {
            var c = new VariableCollection();

            c.Add("int", "x");
            Assert.IsTrue(c.Exists("x"));
        }
        public void NestedCapital()
        {
            var c = new VariableCollection();

            c.Add("int", "x Y z");
            Assert.IsTrue(c.Exists("x y Z"));
        }
        public void BagInt()
        {
            var c = new VariableCollection();

            c.Add("int*", "x ints");
            Assert.IsTrue(c.Exists("x ints a"));
        }
Ejemplo n.º 12
0
        public void ShouldBeAbleToAddVariables()
        {
            _variables = new VariableCollection();

            _variables.Scopes.SetCurrent("Test Scenario 1");

            _variables.Add(_globalVariableName, _globalVariableValue);
            _variables.Add(_localVariableName, _localVariableValue);

            _variables.Count().Should().Be(2);

            _variables.Contains(_globalVariableName).Should().BeTrue();
            _variables.GetValue(_globalVariableName).Should().Be(_globalVariableValue);

            _variables.Contains(_localVariableName).Should().BeTrue();
            _variables.GetValue(_localVariableName).Should().Be(_localVariableValue);
        }
Ejemplo n.º 13
0
 public void Close(string message)
 {
     VariableCollection vars = new VariableCollection();
     vars.Add("message", message);
     var obj = new JukeboxMessage { Type = "close", Variables = vars, MessageId = -1 };
     WriteMessage(obj);
     Context.Disconnect();
 }
Ejemplo n.º 14
0
        /// <summary>
        /// 每次构造ExpressionContext
        /// </summary>
        /// <returns></returns>
        public static double Test3()
        {
            Stopwatch stopwatch2 = new Stopwatch();

            stopwatch2.Start();
            for (int i = 0; i < 1000000; i++)
            {
                //Sample Scenario 1
                ExpressionContext  context   = new ExpressionContext();
                VariableCollection variables = context.Variables;
                variables.Add("a", 1);
                variables.Add("b", 1);

                IGenericExpression <bool> e = context.CompileGeneric <bool>("a=1 AND b=0");
                bool result = e.Evaluate();
            }
            stopwatch2.Stop();
            return(stopwatch2.ElapsedMilliseconds);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Evaluates an expression to an object like <see cref="bool"/> or <see cref="int"/> bases on a set of variables that should be used when evaluating
        /// For example evaluating to bool:
        ///     Expression:     a > 6 AND b = true
        ///     With variables: a = 7 and b = false (these values will come from user input for parameters in the projectmodel)
        ///     Will result in: false
        /// Uses https://github.com/mparlak/Flee for evaluation
        /// </summary>
        /// <param name="expression">The expression to be evaluated like a > 6 AND b = true</param>
        /// <param name="variables">A dictionary with the values for the variables and the letters they should replace in the evaluation</param>
        /// <returns></returns>
        public static T Evaluate(string expression, Dictionary <string, object> variables)
        {
            var context             = new ExpressionContext();
            VariableCollection vars = context.Variables;

            foreach (KeyValuePair <string, object> variable in variables)
            {
                vars.Add(variable.Key, variable.Value);
            }
            return(context.CompileGeneric <T>(expression).Evaluate());
        }
Ejemplo n.º 16
0
 public static void SetVariable(string name, Variable value)
 {
     if (_variables.ContainsKey(name))
     {
         _variables[name] = value;
     }
     else
     {
         _variables.Add(name, value);
     }
 }
Ejemplo n.º 17
0
 public void SetVariable(string name, Variable value)
 {
     if (_variables.ContainsKey(name))
     {
         _variables[name] = value;
     }
     else
     {
         value.OnValueChange += DataChange;
         _variables.Add(name, value);
     }
 }
Ejemplo n.º 18
0
        public bool SatisfiesFormula(Formula formula)
        {
            VariableCollection variable = _expressionContext.Variables;

            foreach (var statu in _status)
            {
                variable.Add(statu.Key.ToString(), statu.Value);
            }
            bool eval = _expressionContext.CompileGeneric <bool>(formula.Expression).Evaluate();

            variable.Clear();
            return(eval);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 构建一次ExpressionContext,CalculationEngine
        /// </summary>
        /// <returns></returns>
        public static double Test2()
        {
            Stopwatch stopwatch2 = new Stopwatch();

            stopwatch2.Start();
            CalculationEngine  calculationEngine = new CalculationEngine();
            ExpressionContext  context           = new ExpressionContext();
            VariableCollection variables         = context.Variables;

            variables.Add("x", 100);
            variables.Add("y", 200);

            calculationEngine.Add("a", "x+y", context);
            for (int i = 0; i < 1000000; i++)
            {
                variables["x"] = i;
                calculationEngine.Recalculate("a");
                int j = calculationEngine.GetResult <int>("a");
            }

            stopwatch2.Stop();
            return(stopwatch2.ElapsedMilliseconds);
        }
Ejemplo n.º 20
0
        public virtual void Add(IVariable variable)
        {
            Contract.Requires <ArgumentException>(!Contains(variable));
            variable.Owner = this;

            if (variable.Semantic != string.Empty)
            {
                var semanticVars = variables.Where(kvp => kvp.Value.Semantic == variable.Semantic).ToArray();
                if (semanticVars.Length > 0)
                {
                    variable.Index = semanticVars.Length;
                    semanticVars[0].Value.Index = 0;
                }
            }
            variables.Add(variable.Name, variable);
        }
Ejemplo n.º 21
0
        public IVariableCollection ResolveLocalVariables(IMethod method, int sig, out bool hasGenericVars)
        {
            hasGenericVars = false;

            var list = new VariableCollection();

            if (sig == 0)
            {
                return(list);
            }

            var         context = new Context(method);
            SimpleIndex idx     = sig;
            var         row     = Metadata.GetRow(TableId.StandAloneSig, idx.Index - 1);

            var reader = row[Schema.StandAloneSig.Signature].Blob;
            int prolog = reader.ReadPackedInt();

            if (prolog != 0x07)
            {
                throw new BadSignatureException("Invalid local variable signature.");
            }

            int varCount = reader.ReadPackedInt();

            for (int i = 0; i < varCount; ++i)
            {
                var typeSig = TypeSignature.Decode(reader);
                var type    = ResolveType(typeSig, context);

                if (!hasGenericVars && type.IsGenericContext())
                {
                    hasGenericVars = true;
                }

                var v = new Variable
                {
                    Index = i,
                    Type  = type,
                    Name  = string.Format("v{0}", i)
                };
                list.Add(v);
            }

            return(list);
        }
        public static void Map(ref ParametersCollection parameters, VariableCollection variables)
        {
            if (parameters is null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            if (variables is null)
            {
                throw new ArgumentNullException(nameof(variables));
            }

            foreach (var parameter in parameters)
            {
                if (variables.ContainsKey(parameter.Name))
                {
                    variables.Remove(parameter.Name);
                }
                variables.Add(parameter.Name, parameter.Value.Infer());
            }
        }
Ejemplo n.º 23
0
    private static void smethod_6(VariableCollection A_0, Class394 A_1)
    {
        int num = 0x12;

        while (A_1.method_9(BookmarkStart.b("尷唹弻栽ℿぁ㝃", num)))
        {
            if (A_1.method_1() == BookmarkStart.b("尷唹弻栽ℿぁ", num))
            {
                string name = null;
                string str2 = null;
                while (A_1.method_19())
                {
                    string str3 = A_1.method_1();
                    if (str3 != null)
                    {
                        if (!(str3 == BookmarkStart.b("嘷嬹儻嬽", num)))
                        {
                            if (str3 == BookmarkStart.b("丷嬹倻", num))
                            {
                                str2 = A_1.method_3();
                            }
                        }
                        else
                        {
                            name = A_1.method_3();
                        }
                    }
                }
                if (name != null)
                {
                    A_0.Add(name, str2);
                }
            }
            else
            {
                A_1.vmethod_1();
            }
        }
    }
        protected override void PerformMove()
        {
            PotvinCustomerRelocationMove move = CustomerRelocationMoveParameter.ActualValue;

            PotvinEncoding newSolution = move.Individual.Clone() as PotvinEncoding;

            Apply(newSolution, move, ProblemInstance);
            newSolution.Repair();
            VRPToursParameter.ActualValue = newSolution;

            //reset move quality
            VRPEvaluation eval = ProblemInstance.Evaluate(newSolution);

            MoveQualityParameter.ActualValue.Value = eval.Quality;

            //update memory
            VariableCollection memory = MemoriesParameter.ActualValue;
            string             key    = AdditionFrequencyMemoryKeyParameter.Value.Value;

            if (memory != null)
            {
                if (!memory.ContainsKey(key))
                {
                    memory.Add(new Variable(key,
                                            new ItemDictionary <PotvinCustomerRelocationMoveAttribute, IntValue>()));
                }
                ItemDictionary <PotvinCustomerRelocationMoveAttribute, IntValue> additionFrequency =
                    memory[key].Value as ItemDictionary <PotvinCustomerRelocationMoveAttribute, IntValue>;

                PotvinCustomerRelocationMoveAttribute attr = new PotvinCustomerRelocationMoveAttribute(0, move.Tour, move.City);
                if (!additionFrequency.ContainsKey(attr))
                {
                    additionFrequency[attr] = new IntValue(0);
                }

                additionFrequency[attr].Value++;
            }
        }
Ejemplo n.º 25
0
 /// <summary>Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1" />.</summary>
 /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1" />.</param>
 /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only.</exception>
 public void Add(KeyValuePair <string, object> item)
 {
     _collection.Add(item.Key, item.Value);
 }
        /// <summary>
        /// Reads the next variable declaration statement from the file and returns it.
        /// </summary>
        /// <param name="parentReference">The parent code unit.</param>
        /// <param name="unsafeCode">Indicates whether the code being parsed resides in an unsafe code block.</param>
        /// <param name="variables">Returns the list of variables defined in the statement.</param>
        /// <returns>Returns the statement.</returns>
        private VariableDeclarationStatement ParseVariableDeclarationStatement(
            Reference<ICodePart> parentReference, bool unsafeCode, VariableCollection variables)
        {
            Param.AssertNotNull(parentReference, "parentReference");
            Param.Ignore(unsafeCode);
            Param.Ignore(variables);

            bool constant = false;

            // Get the first symbol and make sure it is an unknown word or a const.
            Symbol symbol = this.GetNextSymbol(parentReference);

            CsToken firstToken = null;
            Node<CsToken> firstTokenNode = null;

            var statementReference = new Reference<ICodePart>();

            if (symbol.SymbolType == SymbolType.Const)
            {
                constant = true;

                firstToken = new CsToken(symbol.Text, CsTokenType.Const, symbol.Location, statementReference, this.symbols.Generated);
                firstTokenNode = this.tokens.InsertLast(this.GetToken(CsTokenType.Const, SymbolType.Const, statementReference));

                symbol = this.GetNextSymbol(statementReference);
            }

            if (symbol.SymbolType != SymbolType.Other)
            {
                throw this.CreateSyntaxException();
            }

            // Get the expression representing the type.
            LiteralExpression type = this.GetTypeTokenExpression(statementReference, unsafeCode, true);
            if (type == null || type.Tokens.First == null)
            {
                throw new SyntaxException(this.document.SourceCode, firstToken.LineNumber);
            }

            if (firstTokenNode == null)
            {
                firstTokenNode = type.Tokens.First;
            }

            // Get the rest of the declaration.
            VariableDeclarationExpression expression = this.GetVariableDeclarationExpression(type, ExpressionPrecedence.None, unsafeCode);

            // Get the closing semicolon.
            this.tokens.Add(this.GetToken(CsTokenType.Semicolon, SymbolType.Semicolon, statementReference));

            // Add each of the variables defined in this statement to the variable list being returned.
            if (variables != null)
            {
                VariableModifiers modifiers = constant ? VariableModifiers.Const : VariableModifiers.None;
                foreach (VariableDeclaratorExpression declarator in expression.Declarators)
                {
                    Variable variable = new Variable(
                        expression.Type,
                        declarator.Identifier.Token.Text,
                        modifiers,
                        CodeLocation.Join(expression.Type.Location, declarator.Identifier.Token.Location),
                        statementReference,
                        expression.Tokens.First.Value.Generated || declarator.Identifier.Token.Generated);

                    // There might already be a variable in this scope with the same name. This can happen
                    // in valid situation when there are ifdef's surrounding portions of the code.
                    // Just accept the first variable and ignore others.
                    if (!variables.Contains(declarator.Identifier.Token.Text))
                    {
                        variables.Add(variable);
                    }
                }
            }

            // Create the token list for the statement.
            CsTokenList partialTokens = new CsTokenList(this.tokens, firstTokenNode, this.tokens.Last);

            var statement = new VariableDeclarationStatement(partialTokens, constant, expression);
            statementReference.Target = statement;

            return statement;
        }
Ejemplo n.º 27
0
        public void TestLongBranchLogical1()
        {
            string            expressionText = this.GetIndividualTest("LongBranch1");
            ExpressionContext context        = new ExpressionContext();

            VariableCollection vc = context.Variables;

            vc.Add("M0100_ASSMT_REASON", "0");
            vc.Add("M0220_PRIOR_NOCHG_14D", "1");
            vc.Add("M0220_PRIOR_UNKNOWN", "1");
            vc.Add("M0220_PRIOR_UR_INCON", "1");
            vc.Add("M0220_PRIOR_CATH", "1");
            vc.Add("M0220_PRIOR_INTRACT_PAIN", "1");
            vc.Add("M0220_PRIOR_IMPR_DECSN", "1");
            vc.Add("M0220_PRIOR_DISRUPTIVE", "1");
            vc.Add("M0220_PRIOR_MEM_LOSS", "1");
            vc.Add("M0220_PRIOR_NONE", "1");

            vc.Add("M0220_PRIOR_UR_INCON_bool", true);
            vc.Add("M0220_PRIOR_CATH_bool", true);
            vc.Add("M0220_PRIOR_INTRACT_PAIN_bool", true);
            vc.Add("M0220_PRIOR_IMPR_DECSN_bool", true);
            vc.Add("M0220_PRIOR_DISRUPTIVE_bool", true);
            vc.Add("M0220_PRIOR_MEM_LOSS_bool", true);
            vc.Add("M0220_PRIOR_NONE_bool", true);
            vc.Add("M0220_PRIOR_NOCHG_14D_bool", true);
            vc.Add("M0220_PRIOR_UNKNOWN_bool", true);

            var e = new DynamicExpression(expressionText, ExpressionLanguage.Flee);
            // We only care that the expression is valid and can be evaluated
            object result = e.Invoke(context);
        }
Ejemplo n.º 28
0
        public override AstNode VisitMethodDecl(MethodDecl ast)
        {
            m_currentMethod = ast.MethodInfo;
            m_currentMethodParameters = new VariableCollection<Parameter>();

            foreach (var param in m_currentMethod.Parameters)
            {
                m_currentMethodParameters.Add(param);
            }

            m_currentMethodVariables = new VariableCollection<VariableInfo>();

            foreach (var statement in ast.Statements)
            {
                Visit(statement);
            }

            Visit(ast.ReturnExpression);

            return ast;
        }
Ejemplo n.º 29
0
        public void CalcEngine_Returns_Same_Values_As_VB()
        {
            variables.Add("x", 100);
            ce.Add("a", "x * 2", context);
            variables.Add("y", 1);
            ce.Add("b", "a + y", context);
            ce.Add("c", "b * 2", context);
            ce.Recalculate("a");

            var result = ce.GetResult("c");

            Assert.AreEqual(result, ((100 * 2) + 1) * 2);

            variables["x"] = 345;
            ce.Recalculate("a");
            result = ce.GetResult("c");
            Assert.AreEqual(((345 * 2) + 1) * 2, result);
        }
Ejemplo n.º 30
0
        public void Primer()
        {
            //ExStart
            //ExFor:Document.Variables
            //ExFor:VariableCollection
            //ExFor:VariableCollection.Add
            //ExFor:VariableCollection.Clear
            //ExFor:VariableCollection.Contains
            //ExFor:VariableCollection.Count
            //ExFor:VariableCollection.GetEnumerator
            //ExFor:VariableCollection.IndexOfKey
            //ExFor:VariableCollection.Remove
            //ExFor:VariableCollection.RemoveAt
            //ExSummary:Shows how to work with a document's variable collection.
            Document           doc       = new Document();
            VariableCollection variables = doc.Variables;

            // Every document has a collection of key/value pair variables, which we can add items to.
            variables.Add("Home address", "123 Main St.");
            variables.Add("City", "London");
            variables.Add("Bedrooms", "3");

            Assert.AreEqual(3, variables.Count);

            // We can display the values of variables in the document body using DOCVARIABLE fields.
            DocumentBuilder  builder = new DocumentBuilder(doc);
            FieldDocVariable field   = (FieldDocVariable)builder.InsertField(FieldType.FieldDocVariable, true);

            field.VariableName = "Home address";
            field.Update();

            Assert.AreEqual("123 Main St.", field.Result);

            // Assigning values to existing keys will update them.
            variables.Add("Home address", "456 Queen St.");

            // We will then have to update DOCVARIABLE fields to ensure they display an up-to-date value.
            Assert.AreEqual("123 Main St.", field.Result);

            field.Update();

            Assert.AreEqual("456 Queen St.", field.Result);

            // Verify that the document variables with a certain name or value exist.
            Assert.True(variables.Contains("City"));
            Assert.True(variables.Any(v => v.Value == "London"));

            // The collection of variables automatically sorts variables alphabetically by name.
            Assert.AreEqual(0, variables.IndexOfKey("Bedrooms"));
            Assert.AreEqual(1, variables.IndexOfKey("City"));
            Assert.AreEqual(2, variables.IndexOfKey("Home address"));

            // Enumerate over the collection of variables.
            using (IEnumerator <KeyValuePair <string, string> > enumerator = doc.Variables.GetEnumerator())
                while (enumerator.MoveNext())
                {
                    Console.WriteLine($"Name: {enumerator.Current.Key}, Value: {enumerator.Current.Value}");
                }

            // Below are three ways of removing document variables from a collection.
            // 1 -  By name:
            variables.Remove("City");

            Assert.False(variables.Contains("City"));

            // 2 -  By index:
            variables.RemoveAt(1);

            Assert.False(variables.Contains("Home address"));

            // 3 -  Clear the whole collection at once:
            variables.Clear();

            Assert.That(variables, Is.Empty);
            //ExEnd
        }
        public void Primer()
        {
            //ExStart
            //ExFor:Document.Variables
            //ExFor:VariableCollection
            //ExFor:VariableCollection.Add
            //ExFor:VariableCollection.Clear
            //ExFor:VariableCollection.Contains
            //ExFor:VariableCollection.Count
            //ExFor:VariableCollection.GetEnumerator
            //ExFor:VariableCollection.IndexOfKey
            //ExFor:VariableCollection.Remove
            //ExFor:VariableCollection.RemoveAt
            //ExSummary:Shows how to work with a document's variable collection.
            Document           doc       = new Document();
            VariableCollection variables = doc.Variables;

            // Documents have a variable collection to which name/value pairs can be added
            variables.Add("Home address", "123 Main St.");
            variables.Add("City", "London");
            variables.Add("Bedrooms", "3");

            Assert.AreEqual(3, variables.Count);

            // Variables can be referenced and have their values presented in the document by DOCVARIABLE fields
            DocumentBuilder  builder = new DocumentBuilder(doc);
            FieldDocVariable field   = (FieldDocVariable)builder.InsertField(FieldType.FieldDocVariable, true);

            field.VariableName = "Home address";
            field.Update();

            Assert.AreEqual("123 Main St.", field.Result);

            // Assigning values to existing keys will update them
            variables.Add("Home address", "456 Queen St.");

            // DOCVARIABLE fields also need to be updated in order to show an accurate up to date value
            field.Update();

            Assert.AreEqual("456 Queen St.", field.Result);

            // The existence of variables can be looked up either by name or value like this
            Assert.True(variables.Contains("City"));
            Assert.True(variables.Any(v => v.Value == "London"));

            // Variables are automatically sorted in alphabetical order
            Assert.AreEqual(0, variables.IndexOfKey("Bedrooms"));
            Assert.AreEqual(1, variables.IndexOfKey("City"));
            Assert.AreEqual(2, variables.IndexOfKey("Home address"));

            // Enumerate over the collection of variables
            using (IEnumerator <KeyValuePair <string, string> > enumerator = doc.Variables.GetEnumerator())
                while (enumerator.MoveNext())
                {
                    Console.WriteLine($"Name: {enumerator.Current.Key}, Value: {enumerator.Current.Value}");
                }

            // Variables can be removed either by name or index, or the entire collection can be cleared at once
            variables.Remove("City");

            Assert.False(variables.Contains("City"));

            variables.RemoveAt(1);

            Assert.False(variables.Contains("Home address"));

            variables.Clear();

            Assert.That(variables, Is.Empty);
            //ExEnd
        }
Ejemplo n.º 32
0
 private VariableDeclarationStatement ParseVariableDeclarationStatement(bool unsafeCode, VariableCollection variables)
 {
     bool constant = false;
     Symbol nextSymbol = this.GetNextSymbol();
     CsToken token = null;
     Microsoft.StyleCop.Node<CsToken> firstItemNode = null;
     if (nextSymbol.SymbolType == SymbolType.Const)
     {
         constant = true;
         token = new CsToken(nextSymbol.Text, CsTokenType.Const, nextSymbol.Location, this.symbols.Generated);
         firstItemNode = this.tokens.InsertLast(this.GetToken(CsTokenType.Const, SymbolType.Const));
         nextSymbol = this.GetNextSymbol();
     }
     if (nextSymbol.SymbolType != SymbolType.Other)
     {
         throw this.CreateSyntaxException();
     }
     LiteralExpression typeTokenExpression = this.GetTypeTokenExpression(unsafeCode, true);
     if ((typeTokenExpression == null) || (typeTokenExpression.Tokens.First == null))
     {
         throw new SyntaxException(this.document.SourceCode, token.LineNumber);
     }
     if (firstItemNode == null)
     {
         firstItemNode = typeTokenExpression.Tokens.First;
     }
     VariableDeclarationExpression expression = this.GetVariableDeclarationExpression(typeTokenExpression, ExpressionPrecedence.None, unsafeCode);
     this.tokens.Add(this.GetToken(CsTokenType.Semicolon, SymbolType.Semicolon));
     if (variables != null)
     {
         VariableModifiers modifiers = constant ? VariableModifiers.Const : VariableModifiers.None;
         foreach (VariableDeclaratorExpression expression3 in expression.Declarators)
         {
             Variable variable = new Variable(expression.Type, expression3.Identifier.Token.Text, modifiers, expression3.Tokens.First.Value.Location.StartPoint, expression.Tokens.First.Value.Generated || expression3.Identifier.Token.Generated);
             if (!variables.Contains(expression3.Identifier.Token.Text))
             {
                 variables.Add(variable);
             }
         }
     }
     return new VariableDeclarationStatement(new CsTokenList(this.tokens, firstItemNode, this.tokens.Last), constant, expression);
 }
Ejemplo n.º 33
0
        public override AstNode VisitMethodDecl(MethodDecl ast)
        {
            m_currentMethod = ast.MethodInfo;
            m_currentVariableIndex = 0;
            m_currentMethodParameters = new VariableCollection<Parameter>();

            foreach (var param in m_currentMethod.Parameters)
            {
                m_currentMethodParameters.Add(param);
            }

            m_currentMethodVariables = new VariableCollection<VariableInfo>();

            if (ast.Statements == null || ast.ReturnExpression == null)
            {
                m_errorManager.AddError(c_SE_NotSupported, ast.Name.Span, "A method must have body defined");
                return ast;
            }

            foreach (var statement in ast.Statements)
            {
                Visit(statement);
            }

            Visit(ast.ReturnExpression);

            return ast;
        }