public void VisitAnd()
        {
            var variable1 = new FuzzyVariable("MyFuzzyVariable1", new NumericVariable("MyNumVariable1"));
            var variable2 = new FuzzyVariable("MyFuzzyVariable2", new NumericVariable("MyNumVariable2"));
            var valueExpr1 =
                new ValueExpression(
                    variable1,
                    new FuzzyTerm("MyTerm1", new MembershipFunction()));
            var valueExpr2 =
                new ValueExpression(
                    variable2,
                    new FuzzyTerm("MyTerm2", new MembershipFunction()));

            var andExpr = new AndExpression(valueExpr1, valueExpr2);

            var sut = new GetInvolvedVariables();

            var result = sut.Visit(andExpr);
            Assert.AreEqual(2, result.Count);
            Assert.IsTrue(result.Contains(variable1));
            Assert.IsTrue(result.Contains(variable2));

            result = andExpr.Accept(sut);
            Assert.AreEqual(2, result.Count);
            Assert.IsTrue(result.Contains(variable1));
            Assert.IsTrue(result.Contains(variable2));
        }
예제 #2
0
        public void Constructor()
        {
            var term = new FuzzyTerm("Term", new MembershipFunction());
            var var = new FuzzyVariable("Variable", null, term);

            var expr = new ValueExpression(var, term);
            var sut = new NotExpression(expr);

            Assert.AreEqual(expr, sut.Expression);
        }
예제 #3
0
        public void Constructor_Fails()
        {
            var term = new FuzzyTerm("Term", new MembershipFunction());
            var var = new FuzzyVariable("Variable", null, term);

            var expr = new ValueExpression(var, term);

            Assert.AreEqual("rightExpression", Assert.Throws<ArgumentNullException>(() => new AndExpression(expr, null)).ParamName);
            Assert.AreEqual("leftExpression", Assert.Throws<ArgumentNullException>(() => new AndExpression(null, expr)).ParamName);
        }
예제 #4
0
        public void Constructor()
        {
            var termA = new FuzzyTerm("TermA", new MembershipFunction());
            var termB = new FuzzyTerm("TermB", new MembershipFunction());
            var varA = new FuzzyVariable("Variable A", null, termA);
            var varB = new FuzzyVariable("Variable B", null, termB);

            var exprA = new ValueExpression(varA, termA);
            var exprB = new ValueExpression(varB, termB);

            var sut = new AndExpression(exprA, exprB);

            Assert.AreEqual(exprA, sut.LeftExpression);
            Assert.AreEqual(exprB, sut.RightExpression);
        }
예제 #5
0
        public void VisitValue()
        {
            var valueExpr =
                new ValueExpression(
                    new FuzzyVariable("MyFuzzyVariable", new NumericVariable("MyNumVariable")),
                    new FuzzyTerm("MyTerm", new MembershipFunction()));

            var sut = new ToStringVisitor();

            var result = sut.Visit(valueExpr);
            Assert.AreEqual("MyFuzzyVariable=MyTerm", result);

            result = valueExpr.Accept(sut);
            Assert.AreEqual("MyFuzzyVariable=MyTerm", result);
        }
        public void VisitValue()
        {
            var variable = new FuzzyVariable("MyFuzzyVariable", new NumericVariable("MyNumVariable"));
            var valueExpr =
                new ValueExpression(
                    variable,
                    new FuzzyTerm("MyTerm", new MembershipFunction()));

            var sut = new GetInvolvedVariables();

            var result = sut.Visit(valueExpr);
            Assert.AreEqual(1, result.Count);
            Assert.AreEqual(variable, result[0]);

            result = valueExpr.Accept(sut);
            Assert.AreEqual(1, result.Count);
            Assert.AreEqual(variable, result[0]);
        }
예제 #7
0
        public void VisitOr()
        {
            var valueExpr1 =
                new ValueExpression(
                    new FuzzyVariable("MyFuzzyVariable1", new NumericVariable("MyNumVariable1")),
                    new FuzzyTerm("MyTerm1", new MembershipFunction()));
            var valueExpr2 =
                new ValueExpression(
                    new FuzzyVariable("MyFuzzyVariable2", new NumericVariable("MyNumVariable2")),
                    new FuzzyTerm("MyTerm2", new MembershipFunction()));

            var orExpr = new OrExpression(valueExpr1, valueExpr2);

            var sut = new ToStringVisitor();

            var result = sut.Visit(orExpr);
            Assert.AreEqual("MyFuzzyVariable1=MyTerm1 || MyFuzzyVariable2=MyTerm2", result);

            result = orExpr.Accept(sut);
            Assert.AreEqual("MyFuzzyVariable1=MyTerm1 || MyFuzzyVariable2=MyTerm2", result);
        }
예제 #8
0
        public void Accept()
        {
            var term = new FuzzyTerm("Term", new MembershipFunction());
            var var = new FuzzyVariable("Variable", null, term);
            
            var mocks = new MockRepository();

            var visitor = mocks.StrictMock<IExpressionVisitor<int>>();

            var sut = new ValueExpression(var, term);

            Expect.Call(visitor.Visit(sut)).Return(42);

            mocks.ReplayAll();

            var result = sut.Accept(visitor);

            Assert.AreEqual(42, result);

            mocks.VerifyAll();
        }
예제 #9
0
 public override void LoadFrom(ValueExpression value)
 {
     this.Value = ((StringConstantValue)value).Value;
 }
        private void PerformActMainframeSetText(Act act)
        {
            ActMainframeSetText MFST = (ActMainframeSetText)act;

            switch (MFST.SetTextMode)
            {
            case ActMainframeSetText.eSetTextMode.SetSingleField:
                if (MFST.LocateBy == eLocateBy.ByXY)
                {
                    string XY = MFST.LocateValueCalculated;

                    String[] XYSeparated = XY.Split(',');

                    int x = Int32.Parse(XYSeparated.ElementAt(0));
                    int y = Int32.Parse(XYSeparated.ElementAt(1));
                    if (x >= Coloumn || y >= Rows)
                    {
                        throw new ArgumentOutOfRangeException("X,Y out of bounds please use X/Y less than Rows/Columns configured in agent");
                    }
                    MFE.SetCaretIndex(x, y);
                }
                else
                {
                    MFE.SetCaretIndex(Int32.Parse(act.LocateValueCalculated));
                }

                MFE.SendText(act.ValueForDriver);

                break;

            case ActMainframeSetText.eSetTextMode.SetMultipleFields:

                if (MFST.ReloadValue)
                {
                    MFST.LoadCaretValueList();
                }
                foreach (ActInputValue AIV in MFST.CaretValueList)
                {
                    MFE.SetCaretIndex(Int32.Parse(AIV.Param));
                    ValueExpression VE = new ValueExpression(this.Environment, this.BusinessFlow);
                    VE.Value = AIV.Value;
                    MFE.SendText(VE.ValueCalculated);
                }

                break;

            default:
                throw new NotSupportedException("This action is not implemented yet");
            }
            if (MFST.SendAfterSettingText)
            {
                mDriverWindow.Refresh();
                try
                {
                    Thread.Sleep(DelayBwSetTextandSend * 1000);
                }
                catch
                {
                    Thread.Sleep(3000);
                }
                MFE.SendKey(TnKey.Enter);
            }
        }
예제 #11
0
        public override void PerformDBAction()
        {
            Connect();
            string          SQL      = Act.SQL;
            string          keyspace = Act.Keyspace;
            ValueExpression VE       = new ValueExpression(Db.ProjEnvironment, Db.BusinessFlow, Db.DSList);

            VE.Value = SQL;
            string SQLCalculated = VE.ValueCalculated;

            try
            {
                switch (Action)
                {
                case Actions.ActDBValidation.eDBValidationType.FreeSQL:
                    //To Use JSON Appraoch only if Cassandra version is 2.2 or onwards
                    try
                    {
                        if (IfUseJSON() && (!SQLCalculated.ToLower().Contains("select json ")))
                        {
                            if (SQLCalculated.ToLower().Contains("select"))
                            {
                                SQLCalculated = Regex.Replace(SQLCalculated, "select", "select json ", RegexOptions.IgnoreCase);
                            }
                            RowSet RS = session.Execute(SQLCalculated);
                            UpdateOutValues(RS);
                        }
                        else
                        {
                            RowSet RS = session.Execute(SQLCalculated);
                            UpdateRowSetWithUDT(RS, SQLCalculated);
                        }
                    }
                    catch (Exception e)
                    {
                        Act.Error = "Please check the version of the Database and update on the Environment(by default it will take 2.2)" + e;
                        Reporter.ToLog(eLogLevel.ERROR, e.Message);
                    }
                    break;

                case Actions.ActDBValidation.eDBValidationType.RecordCount:

                    string SQLRecord = keyspace + "." + SQLCalculated;
                    int    count     = GetRecordCount(SQLRecord);
                    Act.AddOrUpdateReturnParamActual("Record Count", count.ToString());
                    break;

                case Actions.ActDBValidation.eDBValidationType.SimpleSQLOneValue:
                    string where = Act.Where;
                    string table = Act.Table;
                    string col   = Act.Column;
                    string sql   = null;
                    try
                    {
                        if (IfUseJSON())
                        {
                            sql = "Select json " + col + " from " + keyspace + "." + table + " where " + where + ";";
                            RowSet R = session.Execute(sql);

                            UpdateOutValues(R);
                        }
                        else
                        {
                            sql = "Select " + col + " from " + keyspace + "." + table + " where " + where + ";";
                            RowSet R = session.Execute(sql);

                            UpdateRowSetWithUDT(R, sql);
                        }
                    }
                    catch (Exception e)
                    {
                        Act.Error = "Please check the version of the Database and update on the Environment(by default it will take 2.2)";
                        Reporter.ToLog(eLogLevel.ERROR, e.Message);
                    }
                    break;

                case Actions.ActDBValidation.eDBValidationType.UpdateDB:
                    RowSet RS1 = session.Execute(SQLCalculated);
                    break;

                default:
                    throw new Exception("Action Not SUpported");
                }
            }
            catch (Exception e)
            {
                Act.Error = "Failed to execute";
                Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {e.Message}", e);
            }
            if (!Db.KeepConnectionOpen)
            {
                Disconnect();
            }
        }
예제 #12
0
        private static IMongoQuery DateQuery(String parameterName, Operator optor, String modifier, ValueExpression operand)
        {
            if (optor == Operator.IN)
            {
                IEnumerable<ValueExpression> opMultiple = ((ChoiceValue)operand).Choices;
                return M.Query.Or(opMultiple.Select(choice => DateQuery(parameterName, Operator.EQ, modifier, choice)));
            }

            string start = parameterName + ".start";
            string end = parameterName + ".end";

            var typedOperand = ((UntypedValue)operand).AsDateValue();
            //            var value = GroomDate(typedOperand.Value);
            var fdtValue = new FhirDateTime(typedOperand.Value);
            var value = BsonDateTime.Create(fdtValue.ToDateTimeOffset());

            switch (optor)
            {
                case Operator.EQ:
                    return
                        M.Query.And(
                            M.Query.Or(M.Query.Exists(start), M.Query.Exists(end)),
                            M.Query.Or(M.Query.LTE(start, value), M.Query.NotExists(start)),
                            M.Query.Or(M.Query.GT(end, value), M.Query.NotExists(end))
                        );
                case Operator.GT:
                    return
                        M.Query.Or(
                            M.Query.GT(parameterName, value),
                            M.Query.GT(start, value)
                        );
                case Operator.GTE:
                    return
                        M.Query.Or(
                            M.Query.GTE(parameterName, value),
                            M.Query.GTE(start, value)
                        );
                case Operator.LT:
                    return
                        M.Query.Or(
                            M.Query.LT(parameterName, value),
                            M.Query.LT(end, value)
                        );
                case Operator.LTE:
                    return
                        M.Query.Or(
                            M.Query.LTE(parameterName, value),
                            M.Query.LTE(end, value)
                        );
                case Operator.ISNULL:
                    return M.Query.EQ(parameterName, null); //We don't use M.Query.NotExists, because that would exclude resources that have this field with an explicit null in it.
                case Operator.NOTNULL:
                    return M.Query.NE(parameterName, null); //We don't use M.Query.Exists, because that would include resources that have this field with an explicit null in it.
                default:
                    throw new ArgumentException(String.Format("Invalid operator {0} on date parameter {1}", optor.ToString(), parameterName));
            }
        }
예제 #13
0
        private void XMLValidation(string xml)
        {
            XmlDocument xmlReqDoc = new XmlDocument();

            xmlReqDoc.LoadXml(xml);

            // Steps
            // 1. Read Source File and replace Place Holders
            // 2. Copy To target file
            // 3. Wait for processed file to exist
            // 4. read target file into Act.ReturnValues
            try
            {
                foreach (ActInputValue aiv in DynamicElements)
                {
                    ValueExpression VE = new ValueExpression(RunOnEnvironment, RunOnBusinessFlow, DSList);
                    VE.Value = @aiv.Param;
                    // var.Value = VE.ValueCalculated;

                    XmlNode node = xmlReqDoc.SelectSingleNode(VE.ValueCalculated);
                    if (node.InnerText != null)
                    {
                        AddOrUpdateReturnParamActualWithPath("InnerText", node.InnerText.ToString(), VE.ValueCalculated);
                    }

                    if (aiv.Value == null || aiv.Value == String.Empty)
                    {
                        foreach (XmlAttribute XA in node.Attributes)
                        {
                            ActReturnValue rv = ReturnValues.Where(x => x.Path == XA.Name).FirstOrDefault();
                            if (rv == null)
                            {
                                AddOrUpdateReturnParamActualWithPath(aiv.Param, XA.Value.ToString(), XA.Name);
                            }
                            else
                            {
                                rv.Actual = XA.Value.ToString();
                            }
                        }
                    }
                    else
                    {
                        if (node.Attributes != null)
                        {
                            var            nameAttribute = node.Attributes[@aiv.Value];
                            ActReturnValue rv            = ReturnValues.Where(x => x.Path == aiv.Value).FirstOrDefault();
                            if (rv == null)
                            {
                                AddOrUpdateReturnParamActualWithPath(aiv.Param, nameAttribute.Value.ToString(), aiv.Value);
                            }
                            else
                            {
                                rv.Actual = nameAttribute.Value.ToString();
                            }
                        }
                    }
                }
            }

            catch (Exception e)
            {
                Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {e.Message}", e);
                throw new System.ArgumentException("Node not found at provided path");
            }
        }
예제 #14
0
        //No modifiers allowed on number parameters, hence not in the method signature.
        private static IMongoQuery NumberQuery(String parameterName, Operator optor, ValueExpression operand)
        {
            string typedOperand;
            try
            {
                typedOperand = ((UntypedValue)operand).AsNumberValue().ToString();
            }
            catch (InvalidCastException)
            {
                throw new ArgumentException(String.Format("Invalid number value {0} on number parameter {1}", operand, parameterName));
            }
            catch (FormatException)
            {
                throw new ArgumentException(String.Format("Invalid number value {0} on number parameter {1}", operand, parameterName));
            }

            switch (optor)
            {
                case Operator.APPROX:
                //TODO
                case Operator.CHAIN:
                //Invalid in this context
                case Operator.EQ:
                    return M.Query.EQ(parameterName, typedOperand);
                case Operator.GT:
                    return M.Query.GT(parameterName, typedOperand);
                case Operator.GTE:
                    return M.Query.GTE(parameterName, typedOperand);
                case Operator.IN:
                    IEnumerable<ValueExpression> opMultiple = ((ChoiceValue)operand).Choices;
                    return M.Query.In(parameterName, new BsonArray(opMultiple.Cast<UntypedValue>().Select(uv => uv.AsNumberValue().ToString())));
                case Operator.ISNULL:
                    return M.Query.EQ(parameterName, null);
                case Operator.LT:
                    return M.Query.LT(parameterName, typedOperand);
                case Operator.LTE:
                    return M.Query.LTE(parameterName, typedOperand);
                case Operator.NOTNULL:
                    return M.Query.NE(parameterName, null);
                default:
                    throw new ArgumentException(String.Format("Invalid operator {0} on number parameter {1}", optor.ToString(), parameterName));
            }
        }
예제 #15
0
 public ILogicalExpression LogicalInverse()
 {
     return(ValueExpression.Create(Value == 0 ? 1 : 0));
 }
 public sealed override void ExplicitVisit(ValueExpression node)
 {
     base.ExplicitVisit(node);
 }
예제 #17
0
 public void Visit(ValueExpression expression)
 {
     Builder.Append(expression.Value);
 }
예제 #18
0
 public void Visit(ValueExpression expression)
 {
 }
예제 #19
0
 public JuelExpression(ValueExpression expression, JuelElContextFactory elContextFactory)
 {
     this.expression       = expression;
     this.elContextFactory = elContextFactory;
 }
예제 #20
0
        private static IMongoQuery TokenQuery(String parameterName, Operator optor, String modifier, ValueExpression operand)
        {
            string systemfield = parameterName + ".system";
            string codefield = parameterName + ".code";
            string displayfield = parameterName + ".display";
            string textfield = parameterName + "_text";

            switch (optor)
            {
                case Operator.EQ:
                    var typedOperand = ((UntypedValue)operand).AsTokenValue();
                    switch (modifier)
                    {
                        case Modifier.TEXT:
                            return M.Query.Or(
                                M.Query.Matches(textfield, new BsonRegularExpression(typedOperand.Value, "i")),
                                M.Query.Matches(displayfield, new BsonRegularExpression(typedOperand.Value, "i")));

                        default:
                            if (typedOperand.AnyNamespace)
                                return M.Query.EQ(codefield, typedOperand.Value);
                            else if (String.IsNullOrWhiteSpace(typedOperand.Namespace))
                                return M.Query.ElemMatch(parameterName,
                                        M.Query.And(
                                            M.Query.NotExists("system"),
                                            M.Query.EQ("code", typedOperand.Value)
                                        ));
                            else
                                return M.Query.ElemMatch(parameterName,
                                        M.Query.And(
                                            M.Query.EQ("system", typedOperand.Namespace),
                                            M.Query.EQ("code", typedOperand.Value)
                                        ));
                    }
                case Operator.IN:
                    IEnumerable<ValueExpression> opMultiple = ((ChoiceValue)operand).Choices;
                    return M.Query.Or(opMultiple.Select(choice => TokenQuery(parameterName, Operator.EQ, modifier, choice)));
                case Operator.ISNULL:
                    return M.Query.And(M.Query.EQ(parameterName, BsonNull.Value), M.Query.EQ(textfield, BsonNull.Value)); //We don't use M.Query.NotExists, because that would exclude resources that have this field with an explicit null in it.
                case Operator.NOTNULL:
                    return M.Query.Or(M.Query.NE(parameterName, BsonNull.Value), M.Query.EQ(textfield, BsonNull.Value)); //We don't use M.Query.Exists, because that would include resources that have this field with an explicit null in it.
                default:
                    throw new ArgumentException(String.Format("Invalid operator {0} on token parameter {1}", optor.ToString(), parameterName));
            }
        }
예제 #21
0
        public static List <AnalyzerItemBase> Analyze(BusinessFlow BusinessFlow, Activity parentActivity, Act a, ObservableList <DataSourceBase> DSList)
        {
            // Put all tests on Action here
            List <string>           ActivityUsedVariables           = new List <string>();
            List <string>           mUsedGlobalParameters           = new List <string>();
            List <string>           mMissingStoreToGlobalParameters = new List <string>();
            List <AnalyzerItemBase> IssuesList = new List <AnalyzerItemBase>();
            ObservableList <GlobalAppModelParameter> mModelsGlobalParamsList = WorkSpace.Instance.SolutionRepository.GetAllRepositoryItems <GlobalAppModelParameter>();

            // Check if the action is obsolete and suggest conversion/upgrade/delete
            //if (a is IObsoleteAction)
            //{
            //    if (a.Active)
            //    {
            //        // TODO: get platform from activity in test
            //        Platform.eType ActivitySourcePlatform = Platform.eType.AndroidDevice;  //FIXME temp

            //        // if it is active then create conversion issue
            //        if (((IObsoleteAction)a).IsObsoleteForPlatform(ActivitySourcePlatform))
            //        {
            //            AnalyzeAction AA = CreateNewIssue(IssuesList, BusinessFlow, Activity, a);
            //            AA.Description = GingerDicser.GetTermResValue(eTermResKey.Activity) + " Contains Obsolete action"; ;
            //            AA.Details = a.Description + " Old Class=" + a.ActClass;
            //            AA.HowToFix = "Convert to new action"; // TODO: get name of new action
            //            AA.CanAutoFix = AnalyzerItemBase.eCanFix.Yes;
            //            AA.IssueType = eType.Warning;
            //            AA.Impact = "New action can have more capabilities and more stable, good to upgrade";
            //            AA.Severity = eSeverity.Medium;
            //            AA.FixItHandler = UpgradeAction;
            //            AA.ActivitySourcePlatform = ActivitySourcePlatform;
            //        }
            //    }
            //    else
            //    {
            //        // old action but not active so create issue of delete old unused action
            //        AnalyzeAction AA = CreateNewIssue(IssuesList, BusinessFlow, Activity, a);
            //        AA.Description = GingerDicser.GetTermResValue(eTermResKey.Activity) + " Contains Obsolete action which is not used"; ;
            //        AA.Details = a.Description + " Old Class=" + a.ActClass;
            //        AA.HowToFix = "Delete action";
            //        AA.CanAutoFix = AnalyzerItemBase.eCanFix.Yes;
            //        AA.IssueType = eType.Warning;
            //        AA.Impact = "slower execution, disk space";
            //        AA.Severity = eSeverity.Low;
            //        AA.FixItHandler = DeleteAction;
            //    }
            //}
            //Flow Control -> GoToAction , Check if Action u want to go to exist
            if (a.FlowControls.Count > 0)
            {
                foreach (GingerCore.FlowControlLib.FlowControl f in a.FlowControls)
                {
                    if (f.Active == true)
                    {
                        if (f.FlowControlAction == eFlowControlAction.GoToAction)
                        {
                            string GoToActionName = f.GetNameFromValue();
                            if (parentActivity.GetAct(f.GetGuidFromValue(true), f.GetNameFromValue(true)) == null)
                            {
                                AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a);
                                AA.Description = "Flow control is mapped to Action which does not exist";;
                                AA.Details     = "'" + GoToActionName + "' Action does not exist in '" + parentActivity.ActivityName + "' " + GingerDicser.GetTermResValue(eTermResKey.Activity);
                                AA.HowToFix    = "Remap the Flow Control Action";

                                if (parentActivity.Acts.Where(x => x.Description == f.GetNameFromValue()).FirstOrDefault() != null)
                                {
                                    //can be auto fix
                                    AA.HowToFix        = "Remap Flow Control Action. Auto fix found other Action with the same name so it will fix the mapping to this Action.";
                                    AA.ErrorInfoObject = f;
                                    AA.CanAutoFix      = AnalyzerItemBase.eCanFix.Yes;
                                    AA.FixItHandler    = FixFlowControlWrongActionMapping;
                                }
                                else
                                {
                                    AA.CanAutoFix = AnalyzerItemBase.eCanFix.No;
                                }

                                AA.IssueType = eType.Error;
                                AA.Impact    = "Flow Control will fail on run time";
                                AA.Severity  = eSeverity.High;

                                IssuesList.Add(AA);
                            }
                        }
                        if (f.FlowControlAction == eFlowControlAction.GoToActivity)
                        {
                            string GoToActivity = f.GetNameFromValue();
                            //if (BusinessFlow.Activities.Where(x => (x.ActivityName == GoToActivity)).FirstOrDefault() == null)
                            if (BusinessFlow.GetActivity(f.GetGuidFromValue(true), f.GetNameFromValue(true)) == null)
                            {
                                AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a);
                                AA.Description = "Flow control is mapped to " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " which does not exist";;
                                AA.Details     = "'" + GoToActivity + "' " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " does not exist in the '" + BusinessFlow.Name + " ' " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow);
                                AA.HowToFix    = "Remap the Flow Control Action";

                                if (BusinessFlow.Activities.Where(x => x.ActivityName == f.GetNameFromValue()).FirstOrDefault() != null)
                                {
                                    //can be auto fix
                                    AA.HowToFix        = "Remap Flow Control " + GingerDicser.GetTermResValue(eTermResKey.Activity) + ". Auto fix found other " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " with the same name so it will fix the mapping to this " + GingerDicser.GetTermResValue(eTermResKey.Activity) + ".";
                                    AA.ErrorInfoObject = f;
                                    AA.CanAutoFix      = AnalyzerItemBase.eCanFix.Yes;
                                    AA.FixItHandler    = FixFlowControlWrongActivityMapping;
                                }
                                else
                                {
                                    AA.CanAutoFix = AnalyzerItemBase.eCanFix.No;
                                }

                                AA.IssueType = eType.Error;
                                AA.Impact    = "Flow Control will fail on run time";
                                AA.Severity  = eSeverity.High;

                                IssuesList.Add(AA);
                            }
                        }
                        if (f.FlowControlAction == eFlowControlAction.GoToNextActivity)
                        {
                            if (BusinessFlow.Activities.IndexOf(parentActivity) == (BusinessFlow.Activities.Count() - 1))
                            {
                                AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a);
                                AA.Description = "Flow control is mapped to " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " which does not exist";;
                                AA.Details     = "Flow Control is set to 'GoToNextActivity' but the parent " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " is last one in flow.";
                                AA.HowToFix    = "Remap the Flow Control Action";
                                AA.CanAutoFix  = AnalyzerItemBase.eCanFix.No;
                                AA.IssueType   = eType.Error;
                                AA.Impact      = "Flow Control will fail on run time";
                                AA.Severity    = eSeverity.High;

                                IssuesList.Add(AA);
                            }
                        }
                        if (f.FlowControlAction == eFlowControlAction.SetVariableValue)
                        {
                            if (string.IsNullOrEmpty(f.Value) || ValueExpression.IsThisDynamicVE(f.Value) == false)
                            {
                                string   SetVariableValue = f.GetNameFromValue();
                                string[] vals             = SetVariableValue.Split(new char[] { '=' });
                                if (!BusinessFlow.CheckIfVariableExists(vals[0].ToString().Trim(), parentActivity))
                                {
                                    AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a);
                                    AA.Description = "Flow control mapped to " + GingerDicser.GetTermResValue(eTermResKey.Variable) + " which does not exist";;
                                    AA.Details     = "'" + vals[0].Trim() + "' " + GingerDicser.GetTermResValue(eTermResKey.Variable) + " does not exist in parent items";
                                    AA.HowToFix    = "Remap the Flow Control Action";
                                    AA.CanAutoFix  = AnalyzerItemBase.eCanFix.No;
                                    AA.IssueType   = eType.Error;
                                    AA.Impact      = "Flow Control will fail on run time";
                                    AA.Severity    = eSeverity.High;

                                    IssuesList.Add(AA);
                                }
                            }
                        }
                        if (f.FlowControlAction == eFlowControlAction.RunSharedRepositoryActivity)
                        {
                            if (string.IsNullOrEmpty(f.Value) || ValueExpression.IsThisDynamicVE(f.Value) == false)
                            {
                                //f.CalcualtedValue(BusinessFlow, App.ProjEnvironment, WorkSpace.Instance.SolutionRepository.GetAllRepositoryItems<DataSourceBase>());
                                string RunSharedRepositoryActivity   = f.GetNameFromValue();
                                ObservableList <Activity> activities = WorkSpace.Instance.SolutionRepository.GetAllRepositoryItems <Activity>();
                                if (activities.Where(x => x.ActivityName == RunSharedRepositoryActivity).FirstOrDefault() == null)
                                {
                                    AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a);
                                    AA.Description = "Flow control mapped to Shared Repository " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " which does not exist";
                                    AA.Details     = "'" + RunSharedRepositoryActivity + "' " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " does not exist in Shared Repository";
                                    AA.HowToFix    = "Remap the Flow Control Action";
                                    AA.CanAutoFix  = AnalyzerItemBase.eCanFix.No;
                                    AA.IssueType   = eType.Error;
                                    AA.Impact      = "Flow Control will fail on run time";
                                    AA.Severity    = eSeverity.High;

                                    IssuesList.Add(AA);
                                }
                            }
                        }
                        if (f.FlowControlAction == eFlowControlAction.GoToActivityByName)
                        {
                            if (string.IsNullOrEmpty(f.Value) || ValueExpression.IsThisDynamicVE(f.Value) == false)
                            {
                                string activityToGoTo = f.GetNameFromValue();
                                if (BusinessFlow.Activities.Where(x => x.ActivityName == activityToGoTo).FirstOrDefault() == null)
                                {
                                    AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a);
                                    AA.Description = "Flow control mapped to " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " which does not exist";
                                    AA.Details     = "'" + activityToGoTo + "' " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " does not exist in the parent " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow);
                                    AA.HowToFix    = "Remap the Flow Control Action";
                                    AA.CanAutoFix  = AnalyzerItemBase.eCanFix.No;
                                    AA.IssueType   = eType.Error;
                                    AA.Impact      = "Flow Control will fail on run time";
                                    AA.Severity    = eSeverity.High;

                                    IssuesList.Add(AA);
                                }
                            }
                        }
                    }
                }
            }

            if (a.ActReturnValues.Count > 0)
            {
                foreach (ActReturnValue ARV in a.ActReturnValues)
                {
                    if (ARV.StoreTo != ActReturnValue.eStoreTo.None)
                    {
                        string StoreToValue = ARV.StoreToValue;
                        ActReturnValue.eStoreTo StoreToType = ARV.StoreTo;
                        if (StoreToType == ActReturnValue.eStoreTo.Variable)
                        {
                            if (BusinessFlow.GetAllVariables(parentActivity).Where(x => x.Name == StoreToValue).Select(x => x.Name).FirstOrDefault() == null)
                            {
                                AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a);
                                AA.Description = "Output Values is missing " + GingerDicser.GetTermResValue(eTermResKey.Variable) + " '" + StoreToValue + "'";
                                AA.Details     = "'" + StoreToValue + "' does not exist In " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " '" + BusinessFlow.Name + "' => " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " '" + parentActivity.ActivityName + "' =>" + "Action '" + a.Description + "' ";
                                AA.HowToFix    = "Remap Output Values";
                                AA.CanAutoFix  = AnalyzerItemBase.eCanFix.No;
                                AA.IssueType   = eType.Error;
                                AA.Impact      = "Execution will fail in run time";
                                AA.Severity    = eSeverity.Critical;

                                IssuesList.Add(AA);
                            }
                        }
                        else if (StoreToType == ActReturnValue.eStoreTo.DataSource)
                        {
                            if (StoreToValue != "" && StoreToValue != null)
                            {
                                string chkDataSource = "";
                                Regex  rxDSPattern   = new Regex(@"{(\bDS Name=)\w+\b[^{}]*}", RegexOptions.Compiled);

                                MatchCollection matches = rxDSPattern.Matches(StoreToValue);
                                foreach (Match match in matches)
                                {
                                    chkDataSource = GingerCore.General.CheckDataSource(match.Value, DSList);
                                    if (chkDataSource != "")
                                    {
                                        AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a);
                                        AA.Description = chkDataSource;
                                        AA.Details     = "Invalid '" + StoreToValue + "' StoreTo Value used In " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " '" + BusinessFlow.Name + "' => " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " '" + parentActivity.ActivityName + "' =>" + "Action '" + a.Description + "' ";
                                        AA.HowToFix    = "Remap Output Values";
                                        AA.CanAutoFix  = AnalyzerItemBase.eCanFix.No;
                                        AA.IssueType   = eType.Error;
                                        AA.Impact      = "Execution will fail in run time";
                                        AA.Severity    = eSeverity.Critical;
                                        IssuesList.Add(AA);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            //Disabling the below because there are many actions which shows Locate By/Value but it is not needed for most operation types
            //if (a.ObjectLocatorConfigsNeeded == true && a.ActionDescription != "Script Action" && a.ActionDescription != "File Operations")
            //{
            //    if (a.LocateBy.ToString() == "NA")
            //    {
            //        AnalyzeAction AA = CreateNewIssue(IssuesList, BusinessFlow, parentActivity, a);
            //        AA.Description = "Action is missing LocateBy value";
            //        AA.Details = "Action '" + a.Description + "' In " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " '" + parentActivity.ActivityName + "' is missing LocateBy value";
            //        AA.HowToFix = " Add LocateBy value to '" + a.Description + "'";
            //        AA.CanAutoFix = AnalyzerItemBase.eCanFix.No;    // yes if we have one target app, or just set the first
            //        AA.IssueType = eType.Warning;
            //        AA.Impact = GingerDicser.GetTermResValue(eTermResKey.Activity) + " will not be executed and will fail";
            //        AA.Severity = eSeverity.Medium;
            //    }
            //    if (a.LocateValue == null || a.LocateValue == "")
            //    {
            //        AnalyzeAction AA = CreateNewIssue(IssuesList, BusinessFlow, parentActivity, a);
            //        AA.Description = "Action is missing Locate Value ";
            //        AA.Details = "Action '" + a.Description + "' In " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " '" + parentActivity.ActivityName + "' is missing Locate value";
            //        AA.HowToFix = " Add Locate Value to '" + a.Description + "'";
            //        AA.CanAutoFix = AnalyzerItemBase.eCanFix.No;    // yes if we have one target app, or just set the first
            //        AA.IssueType = eType.Warning;
            //        AA.Impact = GingerDicser.GetTermResValue(eTermResKey.Activity) + " will not be executed and will fail";
            //        AA.Severity = eSeverity.Medium;
            //    }

            //}
            VariableBase.GetListOfUsedVariables(a, ref ActivityUsedVariables);
            if (ActivityUsedVariables.Count > 0)
            {
                foreach (string Var in ActivityUsedVariables)
                {
                    if (BusinessFlow.GetAllVariables(parentActivity).Where(x => x.Name == Var).Select(x => x.Name).FirstOrDefault() == null)
                    {
                        AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a);
                        AA.Description = "The " + GingerDicser.GetTermResValue(eTermResKey.Variable) + " '" + Var + "' is missing";
                        AA.Details     = "The Variable: '" + Var + "' Does not exist In " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " '" + BusinessFlow.Name + "' => " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " '" + parentActivity.ActivityName + "' =>" + "Action '" + a.Description + "' ";
                        AA.HowToFix    = " Create new variable or Delete it from the action.";
                        AA.CanAutoFix  = AnalyzerItemBase.eCanFix.No;
                        AA.IssueType   = eType.Error;
                        AA.Impact      = GingerDicser.GetTermResValue(eTermResKey.Activity) + " will fail due to missing Variable";
                        AA.Severity    = eSeverity.High;

                        IssuesList.Add(AA);
                    }
                }
            }



            GlobalAppModelParameter.GetListOfUsedGlobalParameters(a, ref mUsedGlobalParameters);
            if (mUsedGlobalParameters.Count > 0)
            {
                foreach (string Param in mUsedGlobalParameters)
                {
                    GlobalAppModelParameter globalParam = mModelsGlobalParamsList.Where(x => x.PlaceHolder == Param).FirstOrDefault();
                    if (globalParam == null)
                    {
                        AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a);
                        AA.Description = "The Application Global Parameter " + Param + " is missing";
                        AA.Details     = "The Application Global Parameter: '" + Param + "' Does not exist in Models Global Parameters";
                        AA.HowToFix    = " Create new Application Global Parameter or Delete it from the action.";
                        AA.CanAutoFix  = AnalyzerItemBase.eCanFix.No;
                        AA.IssueType   = eType.Error;
                        AA.Impact      = GingerDicser.GetTermResValue(eTermResKey.Activity) + " will fail due to missing Variable";
                        AA.Severity    = eSeverity.High;
                        IssuesList.Add(AA);
                    }
                }
            }

            GetAllStoreToGlobalParameters(a, mModelsGlobalParamsList, ref mMissingStoreToGlobalParameters);
            if (mMissingStoreToGlobalParameters.Count > 0)
            {
                foreach (string Param in mMissingStoreToGlobalParameters)
                {
                    AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a);
                    AA.Description = "The Output Value with Parameter '" + Param + "' is having store to Parameter which doesn't exist anymore";
                    AA.Details     = "The Output Value with Parameter: '" + Param + "' can be found at " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " '" + BusinessFlow.Name + "' => " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " '" + parentActivity.ActivityName + "' =>" + "Action '" + a.Description + "' ";
                    AA.HowToFix    = " Create new Parameter and change to it in the 'Store to' dropdown under the above path";
                    AA.CanAutoFix  = AnalyzerItemBase.eCanFix.No;
                    AA.IssueType   = eType.Error;
                    AA.Impact      = GingerDicser.GetTermResValue(eTermResKey.Activity) + " will fail due to missing Parameter";
                    AA.Severity    = eSeverity.High;

                    IssuesList.Add(AA);
                }
            }
            // Put All Special Actions Analyze Here
            //actions combination
            if (a.GetType() == typeof(ActLaunchJavaWSApplication))//forbidden combination: Launch & (platform\agent manipulation action)
            {
                List <IAct> driverActs = parentActivity.Acts.Where(x => ((x is ActWithoutDriver && x.GetType() != typeof(ActAgentManipulation)) == false) && x.Active == true).ToList();
                if (driverActs.Count > 0)
                {
                    string        list = string.Join(",", driverActs.Select(x => x.ActionDescription).ToList().ToArray());
                    AnalyzeAction AA   = CreateNewIssue(BusinessFlow, parentActivity, a);
                    AA.Description = GingerDicser.GetTermResValue(eTermResKey.Activity) + " has forbidden combinations";
                    AA.Details     = GingerDicser.GetTermResValue(eTermResKey.Activity) + " has " + a.ActionDescription + " Action with the following platform actions: " + list + ".\nPlatform action inside this current " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " will try to activate the agent before the application is launch(will cause agent issue).";
                    AA.HowToFix    = "Open the " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " and put " + a.ActionDescription + " Action in a separate " + GingerDicser.GetTermResValue(eTermResKey.Activity);
                    AA.CanAutoFix  = AnalyzerItemBase.eCanFix.No;   // we can autofix by delete, but don't want to
                    AA.IssueType   = eType.Error;
                    AA.Impact      = GingerDicser.GetTermResValue(eTermResKey.Activity) + " will be executed and will fail due to java agent connection";
                    AA.Severity    = eSeverity.High;

                    IssuesList.Add(AA);
                }
            }

            if (a.LocateBy == eLocateBy.POMElement || ((a is ActUIElement) && ((ActUIElement)a).ElementLocateBy == eLocateBy.POMElement))
            {
                try
                {
                    string[]            pOMandElementGUIDs = ((ActUIElement)a).ElementLocateValue.Split('_');
                    Guid                selectedPOMGUID    = new Guid(pOMandElementGUIDs[0]);
                    ApplicationPOMModel POM = WorkSpace.Instance.SolutionRepository.GetRepositoryItemByGuid <ApplicationPOMModel>(selectedPOMGUID);
                    if (POM == null)
                    {
                        AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a);
                        AA.Description = "Action's mapped Page Objects Model is missing";
                        AA.Details     = "Action " + a.ActionDescription + " has mapped Page Objects Model which is missing, reason can be that the Page Objects Model has been deleted after mapping it to this action.";
                        AA.HowToFix    = "Open the " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " and the Action in order to map different Page Objects Model and Element";
                        AA.CanAutoFix  = AnalyzerItemBase.eCanFix.No;
                        AA.IssueType   = eType.Error;
                        AA.Impact      = "Action will fail during execution";
                        AA.Severity    = eSeverity.High;

                        IssuesList.Add(AA);
                    }
                    else
                    {
                        Guid        selectedPOMElementGUID = new Guid(pOMandElementGUIDs[1]);
                        ElementInfo selectedPOMElement     = (ElementInfo)POM.MappedUIElements.Where(z => z.Guid == selectedPOMElementGUID).FirstOrDefault();
                        if (selectedPOMElement == null)
                        {
                            AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a);
                            AA.Description = "Page Objects Model Element which mapped to this action is missing";
                            AA.Details     = "Action " + a.ActionDescription + " has mapped Page Objects Model Element which is missing, reason can be that the Element has been deleted after mapping it to this action.";
                            AA.HowToFix    = "Open the " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " and the Action in order to map different Element";
                            AA.CanAutoFix  = AnalyzerItemBase.eCanFix.No;
                            AA.IssueType   = eType.Error;
                            AA.Impact      = "Action will fail during execution";
                            AA.Severity    = eSeverity.High;

                            IssuesList.Add(AA);
                        }
                    }
                }
                catch (Exception ex)
                {
                    AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a);
                    AA.Description = "Action's mapped Page Objects Model or Element is invalid";
                    AA.Details     = "Action " + a.ActionDescription + " has invalid mapped Page Objects Model or Element.";
                    AA.HowToFix    = "Open the " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " and the Action in order to map different Page Objects Model and Element";
                    AA.CanAutoFix  = AnalyzerItemBase.eCanFix.No;
                    AA.IssueType   = eType.Error;
                    AA.Impact      = "Action will fail during execution";
                    AA.Severity    = eSeverity.High;

                    IssuesList.Add(AA);
                }
            }
            return(IssuesList);
        }
예제 #22
0
파일: AstWriter.cs 프로젝트: reshadi2/mcjs
 public void Visit(ValueExpression expression)
 {
     switch (expression.TypeCode)
     {
         case TypeCode.Boolean: outStream.Write(FormatBool((Boolean)expression.Value)); break;
         case TypeCode.Double: outStream.Write((Double)expression.Value); break;
         case TypeCode.String: outStream.Write("\"{0}\"", EscapeString((string)expression.Value)); break;
     }
 }
예제 #23
0
        public override void RunAction(Act act)
        {
            if (act.GetType().ToString() == "GingerCore.Actions.ActScreenShot")
            {
                TakeScreenShot(act);
                return;
            }

            try
            {
                switch (act.GetType().ToString())
                {
                case "GingerCore.Actions.MainFrame.ActMainframeGetDetails":

                    ActMainframeGetDetails MFGD = (ActMainframeGetDetails)act;
                    //todo Implement get Type and others

                    int locx = -1;
                    int locy = -1;
                    switch (MFGD.DetailsToFetch)
                    {
                    case ActMainframeGetDetails.eDetailsToFetch.GetText:

                        if (MFGD.LocateBy == eLocateBy.ByCaretPosition)
                        {
                            if (String.IsNullOrEmpty(act.ValueForDriver))
                            {
                                string MFText = MFE.GetTextatPosition(Int32.Parse(MFGD.LocateValueCalculated), 50);
                                MFText = MFText.Split().ElementAt(0).ToString();
                                MFGD.AddOrUpdateReturnParamActual("Value", MFText);
                            }
                            else
                            {
                                act.AddOrUpdateReturnParamActual("Value", MFE.GetTextatPosition(Int32.Parse(act.LocateValueCalculated), Int32.Parse(act.ValueForDriver)));
                            }
                        }
                        else if (MFGD.LocateBy == eLocateBy.ByXY)
                        {
                            string XY = MFGD.LocateValueCalculated;

                            String[] XYSeparated = XY.Split(',');

                            int x = Int32.Parse(XYSeparated.ElementAt(0));
                            int y = Int32.Parse(XYSeparated.ElementAt(1));
                            if (x >= Coloumn || y >= Rows)
                            {
                                throw new Exception("X,Y out of bounds please use X/Y less than Rows/Columns configured in agent");
                            }
                            if (String.IsNullOrEmpty(act.ValueForDriver))
                            {
                                string MFText = MFE.GetTextatPosition(x, y, 50);
                                MFText = MFText.Split().ElementAt(0).ToString();
                                MFGD.AddOrUpdateReturnParamActual("Value", MFText);
                            }
                            else
                            {
                                act.AddOrUpdateReturnParamActual("Value", MFE.GetTextatPosition(x, y, Int32.Parse(act.ValueForDriver)));
                            }
                        }
                        break;

                    case ActMainframeGetDetails.eDetailsToFetch.GetDetailsFromText:

                        String[] MainFrameLines = MFE.screenText.Split('\n');
                        int      instance       = 1;
                        for (int i = 0; i < MainFrameLines.Length; i++)
                        {
                            locx = MainFrameLines[i].IndexOf(MFGD.ValueForDriver);
                            if (locx >= 0)
                            {
                                locy = i;
                                if (MFGD.TextInstanceType == ActMainframeGetDetails.eTextInstance.AllInstance)
                                {
                                    if (locy != -1)
                                    {
                                        act.AddOrUpdateReturnParamActualWithPath("CaretPosition", (locy * (MFColumns + 1) + locx).ToString(), instance.ToString());
                                        act.AddOrUpdateReturnParamActualWithPath("X", locx.ToString(), instance.ToString());
                                        act.AddOrUpdateReturnParamActualWithPath("Y", locy.ToString(), instance.ToString());
                                    }
                                }
                                else if (MFGD.TextInstanceType == ActMainframeGetDetails.eTextInstance.InstanceN)
                                {
                                    int k = Int32.Parse(MFGD.TextInstanceNumber);
                                    if (locy != -1 && instance == k)
                                    {
                                        act.AddOrUpdateReturnParamActual("CaretPosition", (locy * (MFColumns + 1) + locx).ToString());
                                        act.AddOrUpdateReturnParamActual("X", locx.ToString());
                                        act.AddOrUpdateReturnParamActual("Y", locy.ToString());
                                        break;
                                    }
                                }
                                else if (MFGD.TextInstanceType == ActMainframeGetDetails.eTextInstance.AfterCaretPosition)
                                {
                                    if (Int32.Parse(MFGD.LocateValueCalculated.ToString()) < (locy * (MFColumns + 1) + locx))
                                    {
                                        act.AddOrUpdateReturnParamActual("CaretPosition", (locy * (MFColumns + 1) + locx).ToString());
                                        act.AddOrUpdateReturnParamActual("X", locx.ToString());
                                        act.AddOrUpdateReturnParamActual("Y", locy.ToString());
                                        break;
                                    }
                                }
                                else
                                {
                                    if (locy != -1)
                                    {
                                        act.AddOrUpdateReturnParamActual("CaretPosition", (locy * (MFColumns + 1) + locx).ToString());
                                        act.AddOrUpdateReturnParamActual("X", locx.ToString());
                                        act.AddOrUpdateReturnParamActual("Y", locy.ToString());
                                        break;
                                    }
                                }
                            }
                            if (locy != -1)
                            {
                                instance++;
                            }
                        }

                        break;

                    case ActMainframeGetDetails.eDetailsToFetch.GetAllEditableFeilds:

                        XmlDocument    XD  = new XmlDocument();
                        XmlDeclaration dec = XD.CreateXmlDeclaration("1.0", null, null);
                        XD.AppendChild(dec);
                        XmlElement root = XD.CreateElement("EditableFields");
                        XD.AppendChild(root);

                        string CaretValuePair = @"<?xml version='1.0' encoding='UTF-8'?><nodes>";

                        XMLScreen XC = MFE.GetScreenAsXML();
                        foreach (XMLScreenField XSF in XC.Fields)
                        {
                            if (XSF.Attributes.Protected == true)
                            {
                                continue;
                            }
                            string node = "<node caret=\"" + XSF.Location.position.ToString() + "\" text=\"" + XSF.Text + "\"> </node>";

                            CaretValuePair = CaretValuePair + node;

                            XmlElement EditableField = XD.CreateElement("EditableField");
                            EditableField.SetAttribute("Caret", XSF.Location.position.ToString());
                            EditableField.SetAttribute("Text", XSF.Text);
                            root.AppendChild(EditableField);
                        }

                        act.AddOrUpdateReturnParamActual("Fields", XD.OuterXml);

                        break;

                    case ActMainframeGetDetails.eDetailsToFetch.GetCurrentScreenAsXML:

                        Open3270.TN3270.XMLScreen XMLS = MFE.GetScreenAsXML();
                        System.Xml.Serialization.XmlSerializer xsSubmit = new System.Xml.Serialization.XmlSerializer(typeof(Open3270.TN3270.XMLScreen));
                        System.IO.StringWriter sww    = new System.IO.StringWriter();
                        System.Xml.XmlWriter   writer = System.Xml.XmlWriter.Create(sww);

                        xsSubmit.Serialize(writer, XMLS);
                        String ScreenXML = sww.ToString();         // Your XML

                        act.AddOrUpdateReturnParamActual("ScreenXML", ScreenXML);

                        break;
                    }
                    break;

                case "GingerCore.Actions.MainFrame.ActMainframeSendKey":
                    ActMainframeSendKey MFSK = (ActMainframeSendKey)act;
                    MFE.SendKey(MFSK.KeyToSend);
                    break;

                case "GingerCore.Actions.MainFrame.ActMainframeSetText":
                    ActMainframeSetText MFST = (ActMainframeSetText)act;

                    switch (MFST.SetTextMode)
                    {
                    case ActMainframeSetText.eSetTextMode.SetSingleField:
                        if (MFST.LocateBy == eLocateBy.ByXY)
                        {
                            string XY = MFST.LocateValueCalculated;

                            String[] XYSeparated = XY.Split(',');

                            int x = Int32.Parse(XYSeparated.ElementAt(0));
                            int y = Int32.Parse(XYSeparated.ElementAt(1));
                            if (x >= Coloumn || y >= Rows)
                            {
                                throw new Exception("X,Y out of bounds please use X/Y less than Rows/Columns configured in agent");
                            }
                            MFE.SetCaretIndex(x, y);
                        }
                        else
                        {
                            MFE.SetCaretIndex(Int32.Parse(act.LocateValueCalculated));
                        }

                        MFE.SendText(act.ValueForDriver);

                        break;

                    case ActMainframeSetText.eSetTextMode.SetMultipleFields:

                        if (MFST.ReloadValue)
                        {
                            MFST.LoadCaretValueList();
                        }
                        foreach (ActInputValue AIV in MFST.CaretValueList)
                        {
                            MFE.SetCaretIndex(Int32.Parse(AIV.Param));
                            ValueExpression VE = new ValueExpression(this.Environment, this.BusinessFlow);
                            VE.Value = AIV.Value;
                            MFE.SendText(VE.ValueCalculated);
                        }

                        break;
                    }
                    if (MFST.SendAfterSettingText)
                    {
                        mDriverWindow.Refresh();
                        try
                        {
                            Thread.Sleep(DelayBwSetTextandSend * 1000);
                        }
                        catch
                        {
                            Thread.Sleep(3000);
                        }
                        MFE.SendKey(TnKey.Enter);
                    }
                    break;

                default:
                    throw new Exception("Action not Implemented");
                }

                mDriverWindow.Refresh();
            }
            catch (Exception e)
            {
                act.Status = Amdocs.Ginger.CoreNET.Execution.eRunStatus.Failed;
                act.ExInfo = e.Message;
            }
        }
예제 #24
0
        private static IMongoQuery TokenQuery(String parameterName, Operator optor, String modifier, ValueExpression operand)
        {
            //$elemMatch only works on array values. But the MongoIndexMapper only creates an array if there are multiple values for a given parameter.
            //So we also construct a query for when there is only one set of values in the searchIndex, hence there is no array.
            string systemfield = parameterName + ".system";
            string codefield = parameterName + ".code";
            string displayfield = parameterName + ".display";
            string textfield = parameterName + "_text";

            switch (optor)
            {
                case Operator.EQ:
                    var typedOperand = ((UntypedValue)operand).AsTokenValue();
                    switch (modifier)
                    {
                        case Modifier.TEXT:
                            return M.Query.Or(
                                M.Query.Matches(textfield, new BsonRegularExpression(typedOperand.Value, "i")),
                                M.Query.Matches(displayfield, new BsonRegularExpression(typedOperand.Value, "i")));

                        default:
                            var arrayQueries = new List<IMongoQuery>() { M.Query.EQ("code", typedOperand.Value) };
                            var noArrayQueries = new List<IMongoQuery>() { M.Query.Not(M.Query.Type(parameterName, BsonType.Array)), M.Query.EQ(codefield, typedOperand.Value) };
                            if (!typedOperand.AnyNamespace)
                            {
                                if (String.IsNullOrWhiteSpace(typedOperand.Namespace))
                                {
                                    arrayQueries.Add(M.Query.NotExists("system"));
                                    noArrayQueries.Add(M.Query.NotExists(systemfield));
                                }
                                else
                                {
                                    arrayQueries.Add(M.Query.EQ("system", typedOperand.Namespace));
                                    noArrayQueries.Add(M.Query.EQ(systemfield, typedOperand.Namespace));
                                }
                            }
                            var arrayQuery = M.Query.ElemMatch(parameterName, M.Query.And(arrayQueries));
                            var noArrayQuery = M.Query.And(noArrayQueries);
                            return M.Query.Or(arrayQuery, noArrayQuery);
                    }
                case Operator.IN:
                    IEnumerable<ValueExpression> opMultiple = ((ChoiceValue)operand).Choices;
                    return M.Query.Or(opMultiple.Select(choice => TokenQuery(parameterName, Operator.EQ, modifier, choice)));
                case Operator.ISNULL:
                    return M.Query.And(M.Query.EQ(parameterName, BsonNull.Value), M.Query.EQ(textfield, BsonNull.Value)); //We don't use M.Query.NotExists, because that would exclude resources that have this field with an explicit null in it.
                case Operator.NOTNULL:
                    return M.Query.Or(M.Query.NE(parameterName, BsonNull.Value), M.Query.EQ(textfield, BsonNull.Value)); //We don't use M.Query.Exists, because that would include resources that have this field with an explicit null in it.
                default:
                    throw new ArgumentException(String.Format("Invalid operator {0} on token parameter {1}", optor.ToString(), parameterName));
            }
        }
예제 #25
0
 private string CalculateValue(string valueTocalc)
 {
     return(ValueExpression.Calculate(valueTocalc).Trim());
 }
        public override void Execute()
        {
            VariableBase Var = RunOnBusinessFlow.GetHierarchyVariableByName(VariableName);

            if (Var == null)
            {
                Status = Amdocs.Ginger.CoreNET.Execution.eRunStatus.Failed;
                Error  = GingerDicser.GetTermResValue(eTermResKey.Variable) + " was not found.";
                return;
            }
            string calculatedValue = string.Empty;

            if (ValueExpression != null)
            {
                ValueExpression.DecryptFlag = false;
                calculatedValue             = ValueExpression.Calculate(this.Value);
            }
            else
            {
                calculatedValue = this.Value;
            }

            if (SetVariableValueOption == VariableBase.eSetValueOptions.SetValue)
            {
                if (Var.GetType() == typeof(VariableString))
                {
                    ((VariableString)Var).Value = calculatedValue;
                }
                else if (Var.GetType() == typeof(VariableSelectionList))
                {
                    if (((VariableSelectionList)Var).OptionalValuesList.Where(pv => pv.Value == calculatedValue).SingleOrDefault() != null)
                    {
                        ((VariableSelectionList)Var).Value = calculatedValue;
                    }
                    else
                    {
                        Status = Amdocs.Ginger.CoreNET.Execution.eRunStatus.Failed;
                        Error  = "The value '" + calculatedValue + "' is not part of the possible values of the '" + Var.Name + "' " + GingerDicser.GetTermResValue(eTermResKey.Variable) + ".";
                        return;
                    }
                }
                else if (Var.GetType() == typeof(VariableList))
                {
                    string[] possibleVals = ((VariableList)Var).Formula.Split(',');
                    if (possibleVals != null && possibleVals.Contains(calculatedValue))
                    {
                        ((VariableList)Var).Value = calculatedValue;
                    }
                    else
                    {
                        Status = Amdocs.Ginger.CoreNET.Execution.eRunStatus.Failed;
                        Error  = "The value '" + calculatedValue + "' is not part of the possible values of the '" + Var.Name + "' " + GingerDicser.GetTermResValue(eTermResKey.Variable) + ".";
                        return;
                    }
                }
                else if (Var.GetType() == typeof(VariableDynamic))
                {
                    ((VariableDynamic)Var).ValueExpression = this.Value;
                }
            }
            else if (SetVariableValueOption == VariableBase.eSetValueOptions.ResetValue)
            {
                (Var).ResetValue();
            }
            else if (SetVariableValueOption == VariableBase.eSetValueOptions.ClearSpecialChar)
            {
                string specChar = ValueExpression.Calculate(this.Value);
                if (string.IsNullOrEmpty(specChar))
                {
                    specChar = @"{}(),\""";
                }
                if (!string.IsNullOrEmpty(((VariableString)Var).Value))
                {
                    foreach (char c in specChar)
                    {
                        ((VariableString)Var).Value = ((VariableString)Var).Value.Replace(c.ToString(), "");
                    }
                }
            }
            else if (SetVariableValueOption == VariableBase.eSetValueOptions.AutoGenerateValue)
            {
                ((VariableBase)Var).GenerateAutoValue();
            }
            else if (SetVariableValueOption == VariableBase.eSetValueOptions.StartTimer)
            {
                if (Var.GetType() == typeof(VariableTimer))
                {
                    ((VariableTimer)Var).StartTimer();
                }
                else
                {
                    Status = Amdocs.Ginger.CoreNET.Execution.eRunStatus.Failed;
                    Error  = "Operation type " + SetVariableValueOption + " is not supported for " + GingerDicser.GetTermResValue(eTermResKey.Variable) + " of type " + Var.GetType();
                    return;
                }
            }

            else if (SetVariableValueOption == VariableBase.eSetValueOptions.StopTimer)
            {
                if (Var.GetType() == typeof(VariableTimer))
                {
                    ((VariableTimer)Var).StopTimer();
                }
                else
                {
                    Status = Amdocs.Ginger.CoreNET.Execution.eRunStatus.Failed;
                    Error  = "Operation type " + SetVariableValueOption + " is not supported for " + GingerDicser.GetTermResValue(eTermResKey.Variable) + " of type " + Var.GetType();

                    return;
                }
            }
            else if (SetVariableValueOption == VariableBase.eSetValueOptions.ContinueTimer)
            {
                if (Var.GetType() == typeof(VariableTimer))
                {
                    ((VariableTimer)Var).ContinueTimer();
                }
                else
                {
                    Status = Amdocs.Ginger.CoreNET.Execution.eRunStatus.Failed;
                    Error  = "Operation type " + SetVariableValueOption + " is not supported for variable of type " + Var.GetType();
                    return;
                }
            }
            else
            {
                Status = Amdocs.Ginger.CoreNET.Execution.eRunStatus.Failed;
                Error  = "Unknown set " + GingerDicser.GetTermResValue(eTermResKey.Variable) + " value operation.";
                return;
            }

            ExInfo = GingerDicser.GetTermResValue(eTermResKey.Variable) + " '" + Var.Name + "' value was set to: '" + Var.Value + "'";
        }
예제 #27
0
        public void SetUp(List <string> args)
        {
            if (verbose)
            {
                Console.WriteLine("import path:");

                foreach (string directory in pathResolver.Directories)
                {
                    Console.WriteLine("  " + directory);
                }
            }

            AppDomain domain = Thread.GetDomain();

            rootModule = new Module(null, null);

            foreach (Assembly assembly in domain.GetAssemblies())
            {
                AssemblyLoaded(assembly);
            }

            domain.AssemblyLoad += OnDomainAssemblyLoad;

            rootModule.SetName("null", null);
            rootModule.SetName("true", true);
            rootModule.SetName("false", false);
            rootModule.SetName("args", args);

            DefaultWhitespace.SetUp(rootModule, grammar);
            LineComment.SetUp(rootModule, grammar);
            BlockComment.SetUp(rootModule, grammar);
            Whitespace.SetUp(rootModule, grammar);
            Name.SetUp(rootModule, grammar);
            Name.SetUp(rootModule, grammar);
            Number.SetUp(rootModule, grammar);
            Base.String.SetUp(rootModule, grammar);

            Expression.SetUp(rootModule, grammar);
            ValueExpression.SetUp(rootModule, grammar);
            NameExpression.SetUp(rootModule, grammar);
            ParenExpression.SetUp(rootModule, grammar);
            MemberExpression.SetUp(rootModule, grammar);
            CallExpression.SetUp(rootModule, grammar);
            CallInParentScopeExpression.SetUp(rootModule, grammar);
            NewExpression.SetUp(rootModule, grammar);
            TypeExpression.SetUp(rootModule, grammar);
            IsExpression.SetUp(rootModule, grammar);
            AsExpression.SetUp(rootModule, grammar);
            UnaryExpression.SetUp(rootModule, grammar);
            NotExpression.SetUp(rootModule, grammar);
            MultiplicativeExpression.SetUp(rootModule, grammar);
            MultiplyExpression.SetUp(rootModule, grammar);
            DivideExpression.SetUp(rootModule, grammar);
            AdditiveExpression.SetUp(rootModule, grammar);
            AddExpression.SetUp(rootModule, grammar);
            SubtractExpression.SetUp(rootModule, grammar);
            ComparisonExpression.SetUp(rootModule, grammar);
            LessExpression.SetUp(rootModule, grammar);
            LessOrEqualExpression.SetUp(rootModule, grammar);
            EqualityExpression.SetUp(rootModule, grammar);
            InequalityExpression.SetUp(rootModule, grammar);
            GreaterExpression.SetUp(rootModule, grammar);
            GreaterOrEqualExpression.SetUp(rootModule, grammar);
            JunctionExpression.SetUp(rootModule, grammar);
            AndExpression.SetUp(rootModule, grammar);
            AssignmentExpression.SetUp(rootModule, grammar);
            AssignExpression.SetUp(rootModule, grammar);

            /*
             *  NameExpression = ValueExpression
             * ParenExpression = ValueExpression
             *
             * CallExpression < ValueExpression
             * CallInParentScopeExpression = CallExpression
             * MemberExpression = CallExpression
             *
             * NewExpression < CallExpression
             * TypeExpression < NewExpression
             * UnaryExpression < TypeExpression
             * MultiplicativeExpression < UnaryExpression
             * AdditiveExpression < MultiplicativeExpression
             * ComparisonExpression < AdditiveExpression
             * JunctionExpression < ComparisonExpression
             * AssignmentExpression < JunctionExpression
             */

            Precedence.SetPrecedence(NameExpression.pattern.Precedence,
                                     ValueExpression.pattern.Precedence, Relation.Equal);

            Precedence.SetPrecedence(ParenExpression.pattern.Precedence,
                                     ValueExpression.pattern.Precedence, Relation.Equal);

            Precedence.SetPrecedence(CallExpression.pattern.Precedence,
                                     ValueExpression.pattern.Precedence, Relation.Lower);

            Precedence.SetPrecedence(CallInParentScopeExpression.pattern.Precedence,
                                     CallExpression.pattern.Precedence, Relation.Equal);

            Precedence.SetPrecedence(MemberExpression.pattern.Precedence,
                                     CallExpression.pattern.Precedence, Relation.Equal);

            Precedence.SetPrecedence(NewExpression.pattern.Precedence,
                                     CallExpression.pattern.Precedence, Relation.Lower);

            Precedence.SetPrecedence(TypeExpression.pattern.Precedence,
                                     NewExpression.pattern.Precedence, Relation.Lower);

            Precedence.SetPrecedence(UnaryExpression.pattern.Precedence,
                                     TypeExpression.pattern.Precedence, Relation.Lower);

            Precedence.SetPrecedence(MultiplicativeExpression.pattern.Precedence,
                                     UnaryExpression.pattern.Precedence, Relation.Lower);

            Precedence.SetPrecedence(AdditiveExpression.pattern.Precedence,
                                     MultiplicativeExpression.pattern.Precedence, Relation.Lower);

            Precedence.SetPrecedence(ComparisonExpression.pattern.Precedence,
                                     AdditiveExpression.pattern.Precedence, Relation.Lower);

            Precedence.SetPrecedence(JunctionExpression.pattern.Precedence,
                                     ComparisonExpression.pattern.Precedence, Relation.Lower);

            Precedence.SetPrecedence(AssignmentExpression.pattern.Precedence,
                                     JunctionExpression.pattern.Precedence, Relation.Lower);

            Grammar.PatternChanged(ValueExpression.pattern,
                                   NameExpression.pattern,
                                   ParenExpression.pattern,
                                   MemberExpression.pattern,
                                   CallExpression.pattern,
                                   NewExpression.pattern,
                                   TypeExpression.pattern,
                                   UnaryExpression.pattern,
                                   MultiplicativeExpression.pattern,
                                   AdditiveExpression.pattern,
                                   ComparisonExpression.pattern,
                                   JunctionExpression.pattern,
                                   AssignmentExpression.pattern);

            PatternExpression.SetUp(rootModule, grammar);
            ReferencePatternExpression.SetUp(rootModule, grammar);
            AnyPatternExpression.SetUp(rootModule, grammar);
            TextPatternExpression.SetUp(rootModule, grammar);
            Option.SetUp(rootModule, grammar);
            BlockPatternExpression.SetUp(rootModule, grammar);
            ParenPatternExpression.SetUp(rootModule, grammar);
            TokenPatternExpression.SetUp(rootModule, grammar);
            RangePatternExpression.SetUp(rootModule, grammar);
            RepeatPatternExpression.SetUp(rootModule, grammar);
            AndPatternExpression.SetUp(rootModule, grammar);
            NotPatternExpression.SetUp(rootModule, grammar);
            LabelPatternExpression.SetUp(rootModule, grammar);
            SequencePatternExpression.SetUp(rootModule, grammar);
            AltPatternExpression.SetUp(rootModule, grammar);

            /*
             *  EndPatternExpression = ReferencePatternExpression
             * AnyPatternExpression = ReferencePatternExpression
             *  TextPatternExpression = ReferencePatternExpression
             *  BlockPatternExpression = ReferencePatternExpression
             *  ParenPatternExpression = ReferencePatternExpression
             *  TokenPatternExpression = ReferencePatternExpression
             *
             *  RangePatternExpression < ReferencePatternExpression
             *
             *  AndPatternExpression < RangePatternExpression
             *  NotPatternExpression = AndPatternExpression
             *  RepeatPatternExpression = AndPatternExpression
             *
             *  LabelPatternExpression < AndPatternExpression
             *  SequencePatternExpression < LabelPatternExpression
             *  AltPatternExpression < SequencePatternExpression
             */

            Precedence.SetPrecedence(AnyPatternExpression.pattern.Precedence,
                                     ReferencePatternExpression.pattern.Precedence, Relation.Equal);

            Precedence.SetPrecedence(TextPatternExpression.pattern.Precedence,
                                     ReferencePatternExpression.pattern.Precedence, Relation.Equal);

            Precedence.SetPrecedence(BlockPatternExpression.pattern.Precedence,
                                     ReferencePatternExpression.pattern.Precedence, Relation.Equal);

            Precedence.SetPrecedence(ParenPatternExpression.pattern.Precedence,
                                     ReferencePatternExpression.pattern.Precedence, Relation.Equal);

            Precedence.SetPrecedence(TokenPatternExpression.pattern.Precedence,
                                     ReferencePatternExpression.pattern.Precedence, Relation.Equal);

            Precedence.SetPrecedence(RangePatternExpression.pattern.Precedence,
                                     ReferencePatternExpression.pattern.Precedence, Relation.Lower);

            Precedence.SetPrecedence(AndPatternExpression.pattern.Precedence,
                                     RangePatternExpression.pattern.Precedence, Relation.Lower);

            Precedence.SetPrecedence(NotPatternExpression.pattern.Precedence,
                                     AndPatternExpression.pattern.Precedence, Relation.Equal);

            Precedence.SetPrecedence(RepeatPatternExpression.pattern.Precedence,
                                     AndPatternExpression.pattern.Precedence, Relation.Equal);

            Precedence.SetPrecedence(LabelPatternExpression.pattern.Precedence,
                                     AndPatternExpression.pattern.Precedence, Relation.Lower);

            Precedence.SetPrecedence(SequencePatternExpression.pattern.Precedence,
                                     LabelPatternExpression.pattern.Precedence, Relation.Lower);

            Precedence.SetPrecedence(AltPatternExpression.pattern.Precedence,
                                     SequencePatternExpression.pattern.Precedence, Relation.Lower);

            Grammar.PatternChanged(ReferencePatternExpression.pattern,
                                   AnyPatternExpression.pattern,
                                   TextPatternExpression.pattern,
                                   BlockPatternExpression.pattern,
                                   ParenPatternExpression.pattern,
                                   TokenPatternExpression.pattern,
                                   RangePatternExpression.pattern,
                                   RepeatPatternExpression.pattern,
                                   AndPatternExpression.pattern,
                                   NotPatternExpression.pattern,
                                   LabelPatternExpression.pattern,
                                   SequencePatternExpression.pattern,
                                   AltPatternExpression.pattern);

            Statement.SetUp(rootModule, grammar);
            ExpressionStatement.SetUp(rootModule, grammar);
            CompoundStatement.SetUp(rootModule, grammar);
            PrintStatement.SetUp(rootModule, grammar);
            IfStatement.SetUp(rootModule, grammar);
            WhileStatement.SetUp(rootModule, grammar);
            ReturnStatement.SetUp(rootModule, grammar);
            ThrowStatement.SetUp(rootModule, grammar);
            TryStatement.SetUp(rootModule, grammar);
            ModuleStatement.SetUp(rootModule, grammar);
            FunctionStatement.SetUp(rootModule, grammar);
            Member.SetUp(rootModule, grammar);
            PatternMember.SetUp(rootModule, grammar);
            FieldMember.SetUp(rootModule, grammar);
            ConstructorMember.SetUp(rootModule, grammar);
            MethodMember.SetUp(rootModule, grammar);
            ClassStatement.SetUp(rootModule, grammar);
            SetPrecedenceStatement.SetUp(rootModule, grammar);
            UsingStatement.SetUp(rootModule, grammar);
            ImportStatement.SetUp(rootModule, grammar);
            TopLevelStatement.SetUp(rootModule, grammar);
            Program.SetUp(rootModule, grammar);

            Grammar.PatternChanged(Member.pattern, Statement.pattern);

            grammar.RootPattern = Program.pattern;

            hasBeenSetUp = true;
        }
예제 #28
0
파일: ActExcel.cs 프로젝트: ramizilb/Ginger
        public void WriteData()
        {
            string sql        = "";
            string ConnString = GetConnectionString();
            string result     = System.Text.RegularExpressions.Regex.Replace(GetInputParamCalculatedValue("ColMappingRules"), @",(?=[^']*'(?:[^']*'[^']*')*[^']*$)", "~^GINGER-EXCEL-COMMA-REPLACE^~");

            string[] varColMaps = result.Split(',');

            string sSetDataUsed = "";

            using (OleDbConnection Conn = new OleDbConnection(ConnString))
            {
                try
                {
                    Conn.Open();
                }
                catch (Exception ex)
                {
                    System.Threading.Thread.Sleep(3000);
                    Conn.Open();
                    Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.StackTrace}");
                }

                OleDbCommand Cmd = new OleDbCommand();
                Cmd.Connection = Conn;

                string SheetName = GetInputParamCalculatedValue("SheetName").Trim();

                if (String.IsNullOrEmpty(SheetName))
                {
                    this.Error += "Sheet Name is empty or not selected. Please Select correct sheet name on action configurations";
                    Conn.Close();
                    return;
                }

                if (!SheetName.EndsWith("$"))
                {
                    SheetName += "$";
                }
                if (SelectAllRows == false)
                {
                    sql = "Select TOP 1 * from [" + SheetName + "]";
                }
                else
                {
                    sql = "Select * from [" + SheetName + "]";
                }

                string where = GetInputParamCalculatedValue("SelectRowsWhere");
                if (!string.IsNullOrEmpty(where))
                {
                    sql += " WHERE " + where;
                }
                Cmd.CommandText = sql;
                DataTable dt = new DataTable();

                OleDbDataAdapter da = new OleDbDataAdapter();
                da.SelectCommand = Cmd;
                string updateSQL = "";
                try
                {
                    da.Fill(dt);

                    if (!string.IsNullOrEmpty(GetInputParamCalculatedValue("SetDataUsed")))
                    {
                        sSetDataUsed = @", " + GetInputParamCalculatedValue("SetDataUsed");
                    }

                    // we expect only 1 record
                    if (dt.Rows.Count == 1 && SelectAllRows == false)
                    {
                        DataRow r = dt.Rows[0];
                        //Read data to variables
                        foreach (string vc in varColMaps)
                        {
                            string strPrimaryKeyColumn = GetInputParamCalculatedValue("PrimaryKeyColumn");
                            if (strPrimaryKeyColumn.Contains("`"))
                            {
                                strPrimaryKeyColumn = strPrimaryKeyColumn.Replace("`", "");
                            }

                            string rowKey = r[strPrimaryKeyColumn].ToString();

                            int res;
                            int.TryParse(rowKey, out res);

                            if (res == 0 || r[strPrimaryKeyColumn].GetType() == typeof(System.String))
                            {
                                rowKey = "'" + rowKey + "'";
                            }

                            //TODO: fix me in OO Style

                            //Do mapping
                            string ColName = vc.Split('=')[0];
                            string Value   = vc.Split('=')[1];
                            Value = Value.Replace("~^GINGER-EXCEL-COMMA-REPLACE^~", ",");
                            string txt = Value;

                            //keeping the translation of vars to support prevoius implementation
                            VariableBase var = RunOnBusinessFlow.GetHierarchyVariableByName(Value);
                            if (var != null)
                            {
                                ValueExpression VE = new ValueExpression(RunOnEnvironment, RunOnBusinessFlow, DSList);
                                VE.Value  = var.Value;
                                var.Value = VE.ValueCalculated;
                                txt       = var.Value;
                            }

                            //remove '' from value
                            txt = txt.TrimStart(new char[] { '\'' });
                            txt = txt.TrimEnd(new char[] { '\'' });

                            //TODO: create one long SQL to do the update in one time and not for each var
                            updateSQL = @"UPDATE [" + GetInputParamCalculatedValue("SheetName") + "$] SET " +
                                        ColName + " = '" + txt + "'" + sSetDataUsed +
                                        " WHERE " + GetInputParamCalculatedValue("PrimaryKeyColumn") + "=" + rowKey + ";";

                            this.ExInfo += updateSQL + Environment.NewLine;

                            OleDbCommand myCommand = new OleDbCommand();
                            myCommand.Connection  = Conn;
                            myCommand.CommandText = updateSQL;
                            myCommand.ExecuteNonQuery();
                        }
                        // Do the update that row is used
                    }
                    else if (dt.Rows.Count > 0 && SelectAllRows == true)
                    {
                        updateSQL = @"UPDATE [" + GetInputParamCalculatedValue("SheetName") + "$] SET ";
                        foreach (string vc in varColMaps)
                        {
                            //TODO: fix me in OO Style

                            //Do mapping
                            string ColName = vc.Split('=')[0];
                            string Value   = vc.Split('=')[1];
                            Value = Value.Replace("~^GINGER-EXCEL-COMMA-REPLACE^~", ",");
                            string txt = Value;

                            //keeping the translation of vars to support prevoius implementation
                            VariableBase var = RunOnBusinessFlow.GetHierarchyVariableByName(Value);
                            if (var != null)
                            {
                                ValueExpression VE = new ValueExpression(RunOnEnvironment, RunOnBusinessFlow, DSList);
                                VE.Value  = var.Value;
                                var.Value = VE.ValueCalculated;
                                if (var != null)
                                {
                                    txt = var.Value;
                                }
                                else
                                {
                                    txt = Value;
                                }
                            }

                            //remove '' from value
                            txt = txt.TrimStart(new char[] { '\'' });
                            txt = txt.TrimEnd(new char[] { '\'' });

                            //TODO: create one long SQL to do the update in one time and not for each var
                            updateSQL = updateSQL + ColName + " = '" + txt + "',";
                        }
                        updateSQL = updateSQL.Substring(0, updateSQL.Length - 1);
                        updateSQL = updateSQL + sSetDataUsed;
                        if (!string.IsNullOrEmpty(where))
                        {
                            updateSQL += " WHERE " + where + ";";
                        }
                        this.ExInfo += updateSQL + Environment.NewLine;

                        OleDbCommand myCommand = new OleDbCommand();
                        myCommand.Connection  = Conn;
                        myCommand.CommandText = updateSQL;
                        myCommand.ExecuteNonQuery();
                    }
                    else if (dt.Rows.Count == 0)
                    {
                        this.ExInfo = "No Rows updated with given criteria";
                    }
                }
                catch (Exception ex)
                {
                    // Reporter.ToLog(eLogLevel.ERROR, "Wrting into excel got error " + ex.Message);
                    this.Error = "Error when trying to update the excel: " + ex.Message + Environment.NewLine + "UpdateSQL=" + updateSQL;
                }
                finally
                {
                    Conn.Close();
                }

                // then show a message if needed
                if (dt.Rows.Count == 0)
                {
                    //TODO: reporter
                    // Reporter.ToUser("No rows found in excel file matching criteria - " + sql);
                    //  throw new Exception("No rows found in excel file matching criteria - " + sql);
                }
            }
        }
예제 #29
0
 public void Visit(ValueExpression expression)
 {
 }
예제 #30
0
        public static List <AnalyzerItemBase> Analyze(GingerRunner GR, BusinessFlow BusinessFlow)
        {
            List <AnalyzerItemBase> IssuesList = new List <AnalyzerItemBase>();

            //code added to analyze for BFFlowControls in Runner BF.
            if (BusinessFlow.BFFlowControls.Count > 0)
            {
                foreach (FlowControl f in BusinessFlow.BFFlowControls)
                {
                    if (f.Active == true)
                    {
                        if (f.BusinessFlowControlAction == eBusinessFlowControlAction.GoToBusinessFlow)
                        {
                            string       GoToBusinessFlow = f.GetNameFromValue();
                            BusinessFlow bf           = null;
                            Guid         guidToLookBy = Guid.Empty;

                            if (!string.IsNullOrEmpty(f.GetGuidFromValue().ToString()))
                            {
                                guidToLookBy = Guid.Parse(f.GetGuidFromValue().ToString());
                            }

                            List <BusinessFlow> lstBusinessFlow = null;
                            if (guidToLookBy != Guid.Empty)
                            {
                                lstBusinessFlow = GR.BusinessFlows.Where(x => x.InstanceGuid == guidToLookBy).ToList();
                            }

                            if (lstBusinessFlow == null || lstBusinessFlow.Count == 0)
                            {
                                bf = null;
                            }
                            else if (lstBusinessFlow.Count == 1)
                            {
                                bf = (BusinessFlow)lstBusinessFlow[0];
                            }
                            else//we have more than 1
                            {
                                BusinessFlow firstActive = (BusinessFlow)lstBusinessFlow.Where(x => x.Active == true).FirstOrDefault();
                                if (firstActive != null)
                                {
                                    bf = firstActive;
                                }
                                else
                                {
                                    bf = (BusinessFlow)lstBusinessFlow[0];//no one is Active so returning the first one
                                }
                            }
                            if (bf == null)
                            {
                                AnalyzeRunnerBusinessFlow ABF = CreateNewIssue(IssuesList, GR, BusinessFlow);
                                ABF.Description = "Flow control is mapped to " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " which does not exist";
                                ABF.Details     = "'" + GoToBusinessFlow + "' " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " does not exist in the '" + GR.Name + " ' " + GingerDicser.GetTermResValue(eTermResKey.RunSet);
                                ABF.HowToFix    = "Remap the Flow Control Action";
                                ABF.IssueType   = eType.Error;
                                ABF.CanAutoFix  = AnalyzerItemBase.eCanFix.No;
                                ABF.Impact      = "Flow Control will fail on run time";
                                ABF.Severity    = eSeverity.High;
                            }
                        }
                        if (f.BusinessFlowControlAction == eBusinessFlowControlAction.SetVariableValue)
                        {
                            if (string.IsNullOrEmpty(f.Value) || ValueExpression.IsThisDynamicVE(f.Value) == false)
                            {
                                string   SetVariableValue = f.GetNameFromValue();
                                string[] vals             = SetVariableValue.Split(new char[] { '=' });
                                if ((BusinessFlow.GetAllHierarchyVariables().Where(x => x.Name == vals[0].Trim()).Select(x => x.Name).FirstOrDefault() == null))
                                {
                                    AnalyzeRunnerBusinessFlow ABF = CreateNewIssue(IssuesList, GR, BusinessFlow);
                                    ABF.Description = "Flow control mapped to " + GingerDicser.GetTermResValue(eTermResKey.Variable) + " which does not exist";;
                                    ABF.Details     = "'" + vals[0].Trim() + "' " + GingerDicser.GetTermResValue(eTermResKey.Variable) + " does not exist in parent items";
                                    ABF.HowToFix    = "Remap the Flow Control Action";
                                    ABF.CanAutoFix  = AnalyzerItemBase.eCanFix.No;
                                    ABF.IssueType   = eType.Error;
                                    ABF.Impact      = "Flow Control will fail on run time";
                                    ABF.Severity    = eSeverity.High;
                                }
                            }
                        }
                    }
                }
            }
            return(IssuesList);
        }
 public override void ExplicitVisit(ValueExpression fragment)
 {
     _fragments.Add(fragment);
 }
예제 #32
0
 public override void Eval(TemplateContext context, System.IO.StringWriter writer)
 {
     context.Variables[Name] = ValueExpression.Eval(context);
 }
예제 #33
0
 public static InPredicate In(this CommonFactory factory, ValueExpression what, params ValueExpression[] values)
 {
     return(factory.In(what, ArrayQueryHelper.NewAQ(values, false)));
 }
예제 #34
0
        public override async Task <DialogTurnResult> BeginDialogAsync(DialogContext dc, object options = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (options is CancellationToken)
            {
                throw new ArgumentException($"{nameof(options)} cannot be a cancellation token");
            }

            if (this.Disabled != null && this.Disabled.GetValue(dc.State) == true)
            {
                return(await dc.EndDialogAsync(cancellationToken : cancellationToken).ConfigureAwait(false));
            }

            lock (this.Condition)
            {
                if (this.caseExpressions == null)
                {
                    this.caseExpressions = new Dictionary <string, Expression>();

                    foreach (var @case in this.Cases)
                    {
                        if (long.TryParse(@case.Value, out long intVal))
                        {
                            // you don't have to put quotes around numbers, "23" => 23 OR "23"
                            this.caseExpressions[@case.Value] = Expression.OrExpression(
                                Expression.EqualsExpression(this.Condition, Expression.ConstantExpression(intVal)),
                                Expression.EqualsExpression(this.Condition, Expression.ConstantExpression(@case.Value)));
                        }
                        else if (float.TryParse(@case.Value, out float floatVal))
                        {
                            // you don't have to put quotes around numbers, "23" => 23 OR "23"
                            this.caseExpressions[@case.Value] = Expression.OrExpression(
                                Expression.EqualsExpression(this.Condition, Expression.ConstantExpression(floatVal)),
                                Expression.EqualsExpression(this.Condition, Expression.ConstantExpression(@case.Value)));
                        }
                        else if (bool.TryParse(@case.Value, out bool boolVal))
                        {
                            // you don't have to put quotes around bools, "true" => true OR "true"
                            this.caseExpressions[@case.Value] = Expression.OrExpression(
                                Expression.EqualsExpression(this.Condition, Expression.ConstantExpression(boolVal)),
                                Expression.EqualsExpression(this.Condition, Expression.ConstantExpression(@case.Value)));
                        }
                        else
                        {
                            // if someone does "=23" that will be numeric comparison or "='23'" that will be string comparison, or it can be a
                            // real expression bound to memory.
                            var(value, _) = new ValueExpression(@case.Value).TryGetValue(dc.State);
                            this.caseExpressions[@case.Value] = Expression.EqualsExpression(this.Condition, Expression.ConstantExpression(value));
                        }
                    }
                }
            }

            ActionScope actionScope = this.DefaultScope;

            foreach (var caseScope in this.Cases)
            {
                var(value, error) = this.caseExpressions[caseScope.Value].TryEvaluate(dc.State);

                // Compare both expression results. The current switch case triggers if the comparison is true.
                if (value != null && ((bool)value) == true)
                {
                    actionScope = caseScope;
                    break;
                }
            }

            return(await dc.ReplaceDialogAsync(actionScope.Id, null, cancellationToken : cancellationToken).ConfigureAwait(false));
        }
예제 #35
0
        public override void RunAction(Act act)
        {
            //TODO: add func to Act + Enum for switch
            string actClass = act.GetType().ToString();

            //TODO: avoid hard coded string...
            actClass = actClass.Replace("GingerCore.Actions.", "");
            switch (actClass)
            {
            case "ActConsoleCommand":
                mWait = ((ActConsoleCommand)act).WaitTime;

                ValueExpression VE = new ValueExpression(this.Environment, this.BusinessFlow);

                string ExpString = ((ActConsoleCommand)act).ExpString;
                VE.Value   = ExpString;
                mExpString = VE.ValueCalculated;
                ActConsoleCommand ACC     = (ActConsoleCommand)act;
                string            command = GetCommandText(ACC);
                act.ExInfo   = command;
                taskFinished = false;
                if (command.StartsWith("GINGER_RC="))
                {
                    //This is FTP command and we already have the result
                    act.AddOrUpdateReturnParamActual("GINGER_RC", command.Replace("GINGER_RC=", ""));
                }
                else
                {
                    string sRC;
                    //Send the command via driver
                    if (ACC.ConsoleCommand == ActConsoleCommand.eConsoleCommand.Script)
                    {
                        //TODO: externalize static const for ~~~GINGER_RC_END~~~ and all hard coded multi use strings
                        sRC = mConsoleDriverWindow.RunConsoleCommand(command, "~~~GINGER_RC_END~~~");
                    }
                    else
                    {
                        sRC = mConsoleDriverWindow.RunConsoleCommand(command);
                    }
                    if (mExpString != null && sRC.Contains(mExpString) == false)
                    {
                        act.Error  = @"Expected String """ + mExpString + @""" not found in command output";
                        act.Status = Amdocs.Ginger.CoreNET.Execution.eRunStatus.Failed;
                        return;
                    }

                    act.AddOrUpdateReturnParamActual("Result", sRC);

                    sRC = sRC.Replace("\r", "");
                    sRC = sRC.Replace("\t", "");
                    string[] RCValues = sRC.Split('\n');
                    foreach (string RCValue in RCValues)
                    {
                        if (RCValue.Trim().Length > 0)
                        {
                            string Param;
                            string Value;
                            int    i = -1;
                            if (!string.IsNullOrEmpty(ACC.Delimiter))
                            {
                                i = RCValue.IndexOf(ACC.Delimiter);
                            }
                            else
                            {
                                i = RCValue.IndexOf('=');
                            }

                            if ((i > 0) && (i != RCValue.IndexOf("==")) && (i != RCValue.IndexOf("!=") + 1))
                            {
                                Param = (RCValue.Substring(0, i)).Trim();
                                //the rest is the value
                                Value = RCValue.Substring(Param.Length + 1);

                                Value = new string(Value.Where(ch => !char.IsControl(ch)).ToArray());
                                act.AddOrUpdateReturnParamActual(Param, Value);
                            }
                        }
                    }
                }
                break;

            case "ActScreenShot":
                TakeScreenShot(act);
                break;

            default:
                throw new Exception("Action unknown/Not Impl in Driver - " + this.GetType().ToString());
            }
        }
예제 #36
0
        public ChoiceValue(ValueExpression[] choices)
        {
            if (choices == null) throw Error.ArgumentNull("choices");

            Choices = choices;
        }
예제 #37
0
        private static IMongoQuery StringQuery(String parameterName, Operator optor, String modifier, ValueExpression operand)
        {
            switch (optor)
            {
            case Operator.EQ:
                var typedOperand = ((UntypedValue)operand).AsStringValue().ToString();
                switch (modifier)
                {
                case Modifier.EXACT:
                    return(M.Query.EQ(parameterName, typedOperand));

                case Modifier.CONTAINS:
                    return(M.Query.Matches(parameterName, new BsonRegularExpression(new Regex($".*{typedOperand}.*", RegexOptions.IgnoreCase))));

                case Modifier.TEXT:         //the same behaviour as :phonetic in previous versions.
                    return(M.Query.Matches(parameterName + "soundex", "^" + typedOperand));

                //case Modifier.BELOW:
                //    return M.Query.Matches(parameterName, typedOperand + ".*")
                case Modifier.NONE:
                case null:
                    //partial from begin
                    return(M.Query.Matches(parameterName, new BsonRegularExpression("^" + typedOperand, "i")));

                default:
                    throw new ArgumentException(String.Format("Invalid modifier {0} on string parameter {1}", modifier, parameterName));
                }

            case Operator.IN:     //We'll only handle choice like :exact
                IEnumerable <ValueExpression> opMultiple = ((ChoiceValue)operand).Choices;
                return(SafeIn(parameterName, new BsonArray(opMultiple.Cast <UntypedValue>().Select(sv => sv.Value))));

            case Operator.ISNULL:
                return(M.Query.Or(M.Query.NotExists(parameterName), M.Query.EQ(parameterName, BsonNull.Value)));    //With only M.Query.NotExists, that would exclude resources that have this field with an explicit null in it.

            case Operator.NOTNULL:
                return(M.Query.NE(parameterName, BsonNull.Value));    //We don't use M.Query.Exists, because that would include resources that have this field with an explicit null in it.

            default:
                throw new ArgumentException(String.Format("Invalid operator {0} on string parameter {1}", optor.ToString(), parameterName));
            }
        }
예제 #38
0
        private static IMongoQuery QuantityQuery(String parameterName, Operator optor, String modifier, ValueExpression operand)
        {
            var quantity = operand.ToModelQuantity();
            Fhir.Metrics.Quantity q = quantity.ToUnitsOfMeasureQuantity().Canonical();
            string decimals = UnitsOfMeasureHelper.SearchableString(q);
            BsonValue value = q.GetValueAsBson();

            List<IMongoQuery> queries = new List<IMongoQuery>();
            switch (optor)
            {
                case Operator.EQ:
                    queries.Add(M.Query.Matches("decimals", new BsonRegularExpression("^" + decimals)));
                    break;

                default:
                    queries.Add(ExpressionQuery("value", optor, value));
                    break;
            }

            if (quantity.System != null)
                queries.Add(M.Query.EQ("system", quantity.System.ToString()));

            queries.Add(M.Query.EQ("unit", q.Metric.ToString()));

            IMongoQuery query = M.Query.ElemMatch(parameterName, M.Query.And(queries));
            return query;
        }
예제 #39
0
        private static IMongoQuery QuantityQuery(String parameterName, Operator optor, String modifier, ValueExpression operand)
        {
            //$elemMatch only works on array values. But the MongoIndexMapper only creates an array if there are multiple values for a given parameter.
            //So we also construct a query for when there is only one set of values in the searchIndex, hence there is no array.
            var quantity = operand.ToModelQuantity();

            Fhir.Metrics.Quantity q = quantity.ToUnitsOfMeasureQuantity().Canonical();
            string    decimals      = q.SearchableString();
            BsonValue value         = q.GetValueAsBson();

            List <IMongoQuery> arrayQueries   = new List <IMongoQuery>();
            List <IMongoQuery> noArrayQueries = new List <IMongoQuery>()
            {
                M.Query.Not(M.Query.Type(parameterName, BsonType.Array))
            };

            switch (optor)
            {
            case Operator.EQ:
                arrayQueries.Add(M.Query.Matches("decimals", new BsonRegularExpression("^" + decimals)));
                noArrayQueries.Add(M.Query.Matches(parameterName + ".decimals", new BsonRegularExpression("^" + decimals)));
                break;

            default:
                arrayQueries.Add(ExpressionQuery("value", optor, value));
                noArrayQueries.Add(ExpressionQuery(parameterName + ".value", optor, value));
                break;
            }

            if (quantity.System != null)
            {
                arrayQueries.Add(M.Query.EQ("system", quantity.System.ToString()));
                noArrayQueries.Add(M.Query.EQ(parameterName + ".system", quantity.System.ToString()));
            }
            arrayQueries.Add(M.Query.EQ("unit", q.Metric.ToString()));
            noArrayQueries.Add(M.Query.EQ(parameterName + ".unit", q.Metric.ToString()));

            var arrayQuery   = M.Query.ElemMatch(parameterName, M.Query.And(arrayQueries));
            var noArrayQuery = M.Query.And(noArrayQueries);

            IMongoQuery query = M.Query.Or(arrayQuery, noArrayQuery);

            return(query);
        }
예제 #40
0
 public abstract void Visit(ValueExpression expression);
예제 #41
0
        private static IMongoQuery TokenQuery(String parameterName, Operator optor, String modifier, ValueExpression operand)
        {
            //$elemMatch only works on array values. But the MongoIndexMapper only creates an array if there are multiple values for a given parameter.
            //So we also construct a query for when there is only one set of values in the searchIndex, hence there is no array.
            string systemfield = parameterName + ".system";
            string codefield   = parameterName + ".code";
            string textfield   = parameterName + ".text";

            switch (optor)
            {
            case Operator.EQ:
                var typedEqOperand = ((UntypedValue)operand).AsTokenValue();
                if (modifier == Modifier.TEXT)
                {
                    return(M.Query.Matches(textfield, new BsonRegularExpression(typedEqOperand.Value, "i")));
                }
                else     //Search on code and system
                {
                    //Set up two variants of queries, for dealing with single token values in the index, and multiple (in an array).
                    var arrayQueries   = new List <IMongoQuery>();
                    var noArrayQueries = new List <IMongoQuery>()
                    {
                        M.Query.Not(M.Query.Type(parameterName, BsonType.Array))
                    };

                    if (modifier == Modifier.NOT)     //NOT modifier only affects matching the code, not the system
                    {
                        noArrayQueries.Add(M.Query.Exists(parameterName));
                        noArrayQueries.Add(M.Query.NE(codefield, typedEqOperand.Value));
                        arrayQueries.Add(M.Query.Exists(parameterName));
                        arrayQueries.Add(M.Query.NE("code", typedEqOperand.Value));
                    }
                    else
                    {
                        noArrayQueries.Add(M.Query.EQ(codefield, typedEqOperand.Value));
                        arrayQueries.Add(M.Query.EQ("code", typedEqOperand.Value));
                    }

                    //Handle the system part, if present.
                    if (!typedEqOperand.AnyNamespace)
                    {
                        if (String.IsNullOrWhiteSpace(typedEqOperand.Namespace))
                        {
                            arrayQueries.Add(M.Query.NotExists("system"));
                            noArrayQueries.Add(M.Query.NotExists(systemfield));
                        }
                        else
                        {
                            arrayQueries.Add(M.Query.EQ("system", typedEqOperand.Namespace));
                            noArrayQueries.Add(M.Query.EQ(systemfield, typedEqOperand.Namespace));
                        }
                    }

                    //Combine code and system
                    var arrayEqQuery   = M.Query.ElemMatch(parameterName, M.Query.And(arrayQueries));
                    var noArrayEqQuery = M.Query.And(noArrayQueries);
                    return(M.Query.Or(arrayEqQuery, noArrayEqQuery));
                }

            case Operator.IN:
                IEnumerable <ValueExpression> opMultiple = ((ChoiceValue)operand).Choices;
                return(M.Query.Or(opMultiple.Select(choice => TokenQuery(parameterName, Operator.EQ, modifier, choice))));

            case Operator.ISNULL:
                return(M.Query.And(M.Query.EQ(parameterName, BsonNull.Value), M.Query.EQ(textfield, BsonNull.Value)));    //We don't use M.Query.NotExists, because that would exclude resources that have this field with an explicit null in it.

            case Operator.NOTNULL:
                return(M.Query.Or(M.Query.NE(parameterName, BsonNull.Value), M.Query.EQ(textfield, BsonNull.Value)));    //We don't use M.Query.Exists, because that would include resources that have this field with an explicit null in it.

            default:
                throw new ArgumentException(String.Format("Invalid operator {0} on token parameter {1}", optor.ToString(), parameterName));
            }
        }
예제 #42
0
        private static IMongoQuery QuantityQuery(String parameterName, Operator optor, String modifier, ValueExpression operand)
        {
            Quantity quantity = operand.ToQuantity().Standardize();
            string decimals = quantity.GetDecimalSearchableValue();

            List<IMongoQuery> queries = new List<IMongoQuery>();
            switch (optor)
            {
                case Operator.EQ:
                    queries.Add(M.Query.Matches("decimals", new BsonRegularExpression("^" + decimals, "i")));
                    break;

                default:
                    queries.Add(ExpressionQuery("value", optor, new BsonDouble((double)quantity.Value)));
                    break;
            }

            if (quantity.System != null)
                queries.Add(M.Query.EQ("system", quantity.System.ToString()));

            queries.Add(M.Query.EQ("unit", quantity.Units));

            IMongoQuery query = M.Query.ElemMatch(parameterName, M.Query.And(queries));
            return query;
        }
예제 #43
0
        private static IMongoQuery UriQuery(String parameterName, Operator optor, String modifier, ValueExpression operand)
        {
            //CK: Ugly implementation by just using existing features on the StringQuery.
            //TODO: Implement :ABOVE.
            String localModifier = "";

            switch (modifier)
            {
            case Modifier.BELOW:
                //Without a modifier the default string search is left partial, which is what we need for Uri:below :-)
                break;

            case Modifier.ABOVE:
                //Not supported by string search, still TODO.
                throw new NotImplementedException(String.Format("Modifier {0} on Uri parameter {1} not supported yet.", modifier, parameterName));

            case Modifier.NONE:
            case null:
                localModifier = Modifier.EXACT;
                break;

            case Modifier.MISSING:
                localModifier = Modifier.MISSING;
                break;

            default:
                throw new ArgumentException(String.Format("Invalid modifier {0} on Uri parameter {1}", modifier, parameterName));
            }
            return(StringQuery(parameterName, optor, localModifier, operand));
        }
예제 #44
0
        public CompositeValue(ValueExpression[] components)
        {
            if (components == null) throw Error.ArgumentNull("components");

            Components = components;
        }
예제 #45
0
        private static IMongoQuery DateQuery(String parameterName, Operator optor, String modifier, ValueExpression operand)
        {
            if (optor == Operator.IN)
            {
                IEnumerable <ValueExpression> opMultiple = ((ChoiceValue)operand).Choices;
                return(M.Query.Or(opMultiple.Select(choice => DateQuery(parameterName, Operator.EQ, modifier, choice))));
            }

            string start = parameterName + ".start";
            string end   = parameterName + ".end";

            var fdtValue   = ((UntypedValue)operand).AsDateTimeValue();
            var valueLower = BsonDateTime.Create(fdtValue.LowerBound());
            var valueUpper = BsonDateTime.Create(fdtValue.UpperBound());

            switch (optor)
            {
            case Operator.EQ:
                return
                    (M.Query.And(M.Query.GTE(end, valueLower), M.Query.LT(start, valueUpper)));

            case Operator.GT:
                return
                    (M.Query.GTE(start, valueUpper));

            case Operator.GTE:
                return
                    (M.Query.GTE(start, valueLower));

            case Operator.LT:
                return
                    (M.Query.LT(end, valueLower));

            case Operator.LTE:
                return
                    (M.Query.LT(end, valueUpper));

            case Operator.ISNULL:
                return(M.Query.EQ(parameterName, null));    //We don't use M.Query.NotExists, because that would exclude resources that have this field with an explicit null in it.

            case Operator.NOTNULL:
                return(M.Query.NE(parameterName, null));    //We don't use M.Query.Exists, because that would include resources that have this field with an explicit null in it.

            default:
                throw new ArgumentException(String.Format("Invalid operator {0} on date parameter {1}", optor.ToString(), parameterName));
            }
        }
예제 #46
0
 private static IMongoQuery StringQuery(String parameterName, Operator optor, String modifier, ValueExpression operand)
 {
     switch (optor)
     {
         case Operator.EQ:
             var typedOperand = ((UntypedValue)operand).AsStringValue().ToString();
             switch (modifier)
             {
                 case Modifier.EXACT:
                     return M.Query.EQ(parameterName, typedOperand);
                 case Modifier.TEXT: //the same behaviour as :phonetic in previous versions.
                     return M.Query.Matches(parameterName + "soundex", "^" + typedOperand);
                 //case Modifier.BELOW:
                 //    return M.Query.Matches(parameterName, typedOperand + ".*")
                 case Modifier.NONE:
                 case null:
                     //partial from begin
                     return M.Query.Matches(parameterName, new BsonRegularExpression("^" + typedOperand, "i"));
                 default:
                     throw new ArgumentException(String.Format("Invalid modifier {0} on string parameter {1}", modifier, parameterName));
             }
         case Operator.IN: //We'll only handle choice like :exact
             IEnumerable<ValueExpression> opMultiple = ((ChoiceValue)operand).Choices;
             return M.Query.In(parameterName, new BsonArray(opMultiple.Cast<UntypedValue>().Select(uv => uv.AsStringValue().ToString())));
         case Operator.ISNULL:
             return M.Query.Or(M.Query.NotExists(parameterName), M.Query.EQ(parameterName, BsonNull.Value)); //With only M.Query.NotExists, that would exclude resources that have this field with an explicit null in it.
         case Operator.NOTNULL:
             return M.Query.NE(parameterName, BsonNull.Value); //We don't use M.Query.Exists, because that would include resources that have this field with an explicit null in it.
         default:
             throw new ArgumentException(String.Format("Invalid operator {0} on string parameter {1}", optor.ToString(), parameterName));
     }
 }
예제 #47
0
        private static IMongoQuery CompositeQuery(ModelInfo.SearchParamDefinition parameterDef, Operator optor, String modifier, ValueExpression operand)
        {
            if (optor == Operator.IN)
            {
                var choices = ((ChoiceValue)operand);
                var queries = new List <IMongoQuery>();
                foreach (var choice in choices.Choices)
                {
                    queries.Add(CompositeQuery(parameterDef, Operator.EQ, modifier, choice));
                }
                return(M.Query.Or(queries));
            }
            else if (optor == Operator.EQ)
            {
                var typedOperand = (CompositeValue)operand;
                var queries      = new List <IMongoQuery>();
                var components   = typedOperand.Components;
                var subParams    = parameterDef.CompositeParams;

                if (components.Count() != subParams.Count())
                {
                    throw new ArgumentException(String.Format("Parameter {0} requires exactly {1} composite values, not the currently provided {2} values.", parameterDef.Name, subParams.Count(), components.Count()));
                }

                for (int i = 0; i < subParams.Count(); i++)
                {
                    var subCrit = new Criterium();
                    subCrit.Operator  = Operator.EQ;
                    subCrit.ParamName = subParams[i];
                    subCrit.Operand   = components[i];
                    subCrit.Modifier  = modifier;
                    queries.Add(subCrit.ToFilter(parameterDef.Resource));
                }
                return(M.Query.And(queries));
            }
            throw new ArgumentException(String.Format("Invalid operator {0} on composite parameter {1}", optor.ToString(), parameterDef.Name));
        }
예제 #48
0
        private static IMongoQuery QuantityQuery(String parameterName, Operator optor, String modifier, ValueExpression operand)
        {
            //$elemMatch only works on array values. But the MongoIndexMapper only creates an array if there are multiple values for a given parameter.
            //So we also construct a query for when there is only one set of values in the searchIndex, hence there is no array.
            var quantity = operand.ToModelQuantity();
            Fhir.Metrics.Quantity q = quantity.ToUnitsOfMeasureQuantity().Canonical();
            string decimals = q.SearchableString();
            BsonValue value = q.GetValueAsBson();

            List<IMongoQuery> arrayQueries = new List<IMongoQuery>();
            List<IMongoQuery> noArrayQueries = new List<IMongoQuery>() { M.Query.Not(M.Query.Type(parameterName, BsonType.Array)) };
            switch (optor)
            {
                case Operator.EQ:
                    arrayQueries.Add(M.Query.Matches("decimals", new BsonRegularExpression("^" + decimals)));
                    noArrayQueries.Add(M.Query.Matches(parameterName + ".decimals", new BsonRegularExpression("^" + decimals)));
                    break;

                default:
                    arrayQueries.Add(ExpressionQuery("value", optor, value));
                    noArrayQueries.Add(ExpressionQuery(parameterName + ".value", optor, value));
                    break;
            }

            if (quantity.System != null)
            {
                arrayQueries.Add(M.Query.EQ("system", quantity.System.ToString()));
                noArrayQueries.Add(M.Query.EQ(parameterName + ".system", quantity.System.ToString()));
            }
            arrayQueries.Add(M.Query.EQ("unit", q.Metric.ToString()));
            noArrayQueries.Add(M.Query.EQ(parameterName + ".unit", q.Metric.ToString()));

            var arrayQuery = M.Query.ElemMatch(parameterName, M.Query.And(arrayQueries));
            var noArrayQuery = M.Query.And(noArrayQueries);

            IMongoQuery query = M.Query.Or(arrayQuery, noArrayQuery);
            return query;
        }
예제 #49
0
 /// <summary>
 ///     Assign a ValueExpression to an EL variable, replacing any previously assignment to the same
 ///     variable. The assignment for the variable is removed if the expression is null.
 /// </summary>
 /// <param name="variable">
 ///     The variable name
 /// </param>
 /// <param name="expression">
 ///     The ValueExpression to be assigned to the variable.
 /// </param>
 /// <returns>
 ///     The previous ValueExpression assigned to this variable, null if there is no previous
 ///     assignment to this variable.
 /// </returns>
 public abstract ValueExpression SetVariable(string variable, ValueExpression expression);
예제 #50
0
 private static IMongoQuery UriQuery(String parameterName, Operator optor, String modifier, ValueExpression operand)
 {
     //CK: Ugly implementation by just using existing features on the StringQuery.
     //TODO: Implement :ABOVE.
     String localModifier = "";
     switch (modifier)
     {
         case Modifier.BELOW:
             //Without a modifier the default string search is left partial, which is what we need for Uri:below :-)
             break;
         case Modifier.ABOVE:
             //Not supported by string search, still TODO.
             throw new NotImplementedException(String.Format("Modifier {0} on Uri parameter {1} not supported yet.", modifier, parameterName));
         case Modifier.NONE:
         case null:
             localModifier = Modifier.EXACT;
             break;
         case Modifier.MISSING:
             localModifier = Modifier.MISSING;
             break;
         default:
             throw new ArgumentException(String.Format("Invalid modifier {0} on Uri parameter {1}", modifier, parameterName));
     }
     return StringQuery(parameterName, optor, localModifier, operand);
 }
예제 #51
0
        protected ValueTokenType GetValueTokenType(BlittableJsonReaderObject parameters, ValueExpression value, bool unwrapArrays)
        {
            if (value.Value == ValueTokenType.Parameter)
            {
                if (parameters == null)
                {
                    QueryBuilder.ThrowParametersWereNotProvided(QueryText);
                    return(ValueTokenType.Null); // never hit
                }

                if (parameters.TryGetMember(value.Token, out var parameterValue) == false)
                {
                    QueryBuilder.ThrowParameterValueWasNotProvided(value.Token, QueryText, parameters);
                }

                return(QueryBuilder.GetValueTokenType(parameterValue, QueryText, parameters, unwrapArrays));
            }

            return(value.Value);
        }
예제 #52
0
        private static IMongoQuery CompositeQuery(ModelInfo.SearchParamDefinition parameterDef, Operator optor, String modifier, ValueExpression operand)
        {
            if (optor == Operator.IN)
            {
                var choices = ((ChoiceValue)operand);
                var queries = new List<IMongoQuery>();
                foreach (var choice in choices.Choices)
                {
                    queries.Add(CompositeQuery(parameterDef, Operator.EQ, modifier, choice));
                }
                return M.Query.Or(queries);
            }
            else if (optor == Operator.EQ)
            {
                var typedOperand = (CompositeValue)operand;
                var queries = new List<IMongoQuery>();
                var components = typedOperand.Components;
                var subParams = parameterDef.CompositeParams;

                if (components.Count() != subParams.Count())
                {
                    throw new ArgumentException(String.Format("Parameter {0} requires exactly {1} composite values, not the currently provided {2} values.", parameterDef.Name, subParams.Count(), components.Count()));
                }

                for (int i = 0; i < subParams.Count(); i++)
                {
                    var subCrit = new Criterium();
                    subCrit.Operator = Operator.EQ;
                    subCrit.ParamName = subParams[i];
                    subCrit.Operand = components[i];
                    subCrit.Modifier = modifier;
                    queries.Add(subCrit.ToFilter(parameterDef.Resource));
                }
                return M.Query.And(queries);
            }
            throw new ArgumentException(String.Format("Invalid operator {0} on composite parameter {1}", optor.ToString(), parameterDef.Name));
        }
예제 #53
0
 private string ProcessLine(string line)
 {
     return(ValueExpression.Calculate(line));
 }
예제 #54
0
        public override void Execute()
        {
            VariableBase Var = RunOnBusinessFlow.GetHierarchyVariableByName(VariableName);

            if (Var == null)
            {
                Status = Amdocs.Ginger.CoreNET.Execution.eRunStatus.Failed;
                Error  = GingerDicser.GetTermResValue(eTermResKey.Variable) + " was not found.";
                return;
            }
            string calculatedValue = string.Empty;

            if (ValueExpression != null)
            {
                ValueExpression.DecryptFlag = false;
                calculatedValue             = ValueExpression.Calculate(this.Value);
            }
            else
            {
                calculatedValue = this.Value;
            }

            if (SetVariableValueOption == VariableBase.eSetValueOptions.SetValue)
            {
                if (Var.GetType() == typeof(VariableString))
                {
                    ((VariableString)Var).Value = calculatedValue;
                }
                else if (Var.GetType() == typeof(VariableSelectionList))
                {
                    if (((VariableSelectionList)Var).OptionalValuesList.Where(pv => pv.Value == calculatedValue).SingleOrDefault() != null)
                    {
                        ((VariableSelectionList)Var).Value = calculatedValue;
                    }
                    else
                    {
                        Status = Amdocs.Ginger.CoreNET.Execution.eRunStatus.Failed;
                        Error  = "The value '" + calculatedValue + "' is not part of the possible values of the '" + Var.Name + "' " + GingerDicser.GetTermResValue(eTermResKey.Variable) + ".";
                        return;
                    }
                }
                else if (Var.GetType() == typeof(VariableList))
                {
                    string[] possibleVals = ((VariableList)Var).Formula.Split(',');
                    if (possibleVals != null && possibleVals.Contains(calculatedValue))
                    {
                        ((VariableList)Var).Value = calculatedValue;
                    }
                    else
                    {
                        Status = Amdocs.Ginger.CoreNET.Execution.eRunStatus.Failed;
                        Error  = "The value '" + calculatedValue + "' is not part of the possible values of the '" + Var.Name + "' " + GingerDicser.GetTermResValue(eTermResKey.Variable) + ".";
                        return;
                    }
                }
                else if (Var.GetType() == typeof(VariableDynamic))
                {
                    ((VariableDynamic)Var).ValueExpression = this.Value;
                }
                else if (Var.GetType() == typeof(VariableNumber))
                {
                    try
                    {
                        var varNumber = ((VariableNumber)Var);
                        if (varNumber.CheckNumberInRange(float.Parse(calculatedValue)))
                        {
                            varNumber.Value = calculatedValue;
                        }
                        else
                        {
                            Error = $"The value {calculatedValue} is not in the range, {Var.Name}:-[Min value: {varNumber.MinValue}, Max value: {varNumber.MaxValue}]   {GingerDicser.GetTermResValue(eTermResKey.Variable) }.";
                            return;
                        }
                    }
                    catch (System.Exception ex)
                    {
                        Error = $"Error occured during SetValue for Variable number type..:- {ex.Message}";
                        return;
                    }
                }
                else if (Var.GetType() == typeof(VariableDateTime))
                {
                    var varDateTime = ((VariableDateTime)Var);
                    try
                    {
                        if (!varDateTime.IsValidDateTimeFormat(calculatedValue))
                        {
                            Error = $"The Value [{calculatedValue}] is not in correct format, expected format is [{varDateTime.DateTimeFormat}], {GingerDicser.GetTermResValue(eTermResKey.Variable)}.";
                            return;
                        }

                        if (varDateTime.CheckDateTimeWithInRange(calculatedValue))
                        {
                            varDateTime.Value = calculatedValue;
                        }
                        else
                        {
                            Error = $"The value {calculatedValue} is not in the date range {Var.Name}:-[Min value:{varDateTime.MinDateTime}, Max value:{varDateTime.MaxDateTime}] {GingerDicser.GetTermResValue(eTermResKey.Variable)}.";
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        Error = $"Invalid DateTimeFormat,{Var.Name}:-[DateTimeFormat:{varDateTime.DateTimeFormat}] :- {ex.Message}";
                        return;
                    }
                }
            }
            else if (SetVariableValueOption == VariableBase.eSetValueOptions.ResetValue)
            {
                (Var).ResetValue();
            }
            else if (SetVariableValueOption == VariableBase.eSetValueOptions.ClearSpecialChar)
            {
                string specChar = ValueExpression.Calculate(this.Value);
                if (string.IsNullOrEmpty(specChar))
                {
                    specChar = @"{}(),\""";
                }
                if (!string.IsNullOrEmpty(((VariableString)Var).Value))
                {
                    foreach (char c in specChar)
                    {
                        ((VariableString)Var).Value = ((VariableString)Var).Value.Replace(c.ToString(), "");
                    }
                }
            }
            else if (SetVariableValueOption == VariableBase.eSetValueOptions.AutoGenerateValue)
            {
                ((VariableBase)Var).GenerateAutoValue();
            }
            else if (SetVariableValueOption == VariableBase.eSetValueOptions.StartTimer)
            {
                if (Var.GetType() == typeof(VariableTimer))
                {
                    ((VariableTimer)Var).StartTimer();
                }
                else
                {
                    Status = Amdocs.Ginger.CoreNET.Execution.eRunStatus.Failed;
                    Error  = "Operation type " + SetVariableValueOption + " is not supported for " + GingerDicser.GetTermResValue(eTermResKey.Variable) + " of type " + Var.GetType();
                    return;
                }
            }

            else if (SetVariableValueOption == VariableBase.eSetValueOptions.StopTimer)
            {
                if (Var.GetType() == typeof(VariableTimer))
                {
                    ((VariableTimer)Var).StopTimer();
                }
                else
                {
                    Status = Amdocs.Ginger.CoreNET.Execution.eRunStatus.Failed;
                    Error  = "Operation type " + SetVariableValueOption + " is not supported for " + GingerDicser.GetTermResValue(eTermResKey.Variable) + " of type " + Var.GetType();

                    return;
                }
            }
            else if (SetVariableValueOption == VariableBase.eSetValueOptions.ContinueTimer)
            {
                if (Var.GetType() == typeof(VariableTimer))
                {
                    ((VariableTimer)Var).ContinueTimer();
                }
                else
                {
                    Status = Amdocs.Ginger.CoreNET.Execution.eRunStatus.Failed;
                    Error  = "Operation type " + SetVariableValueOption + " is not supported for variable of type " + Var.GetType();
                    return;
                }
            }
            else
            {
                Status = Amdocs.Ginger.CoreNET.Execution.eRunStatus.Failed;
                Error  = "Unknown set " + GingerDicser.GetTermResValue(eTermResKey.Variable) + " value operation.";
                return;
            }

            ExInfo = GingerDicser.GetTermResValue(eTermResKey.Variable) + " '" + Var.Name + "' value was set to: '" + Var.Value + "'";
        }
예제 #55
0
 public override void ExplicitVisit(ValueExpression node) { this.action(node); }