Ejemplo n.º 1
0
        private ExprType CalcExpressionType(ActivityArgument arg)
        {
            ExprType result;

            var resArg = arg.As <ResourceArgument>();

            if (resArg != null)
            {
                var resType = resArg.ConformsToType ?? Resource.Resource_Type;
                result = ExprTypeHelper.EntityOfType(resType);
            }
            else
            {
                var resListArg = arg.As <ResourceListArgument>();
                if (resListArg != null)
                {
                    var resType = resListArg.ConformsToType ?? Resource.Resource_Type;

                    result            = ExprType.EntityList.Clone();
                    result.EntityType = resType;
                }
                else
                {
                    var argType = arg.GetArgumentType();
                    result = ArgTypeAliasToExprType[argType.Alias];
                }
            }

            return(result);
        }
        public StructuredQuery CreateQuery(string script, EntityRef rootType)
        {
            StructuredQuery sq = new StructuredQuery();

            sq.RootEntity = new ResourceEntity
            {
                EntityTypeId = rootType
            };

            BuilderSettings settings = new BuilderSettings();

            settings.RootContextType = ExprTypeHelper.EntityOfType(rootType);
            settings.TestMode        = true;
            IExpression expr = Factory.ExpressionCompiler.Compile(script, settings);
            string      xml  = expr.ToXml( );

            QueryBuilderSettings qbSettings = new QueryBuilderSettings();

            qbSettings.StructuredQuery = sq;
            qbSettings.ContextEntity   = (ResourceEntity)sq.RootEntity;

            ScalarExpression queryExpr = Factory.ExpressionCompiler.CreateQueryEngineExpression(expr, qbSettings);

            sq.SelectColumns.Add(new SelectColumn {
                Expression = queryExpr
            });
            return(sq);
        }
Ejemplo n.º 3
0
        private ExprType ResolveParameterType(string parameterName, IDictionary <string, Resource> knownEntities)
        {
            if (knownEntities != null && knownEntities.ContainsKey(parameterName))
            {
                //Note - the following is only looking at the first type for the known entity...
                return(ExprTypeHelper.EntityOfType(knownEntities[parameterName].IsOfType.First()));
            }

            if (parameterName == ownerAccountRuntimeArgName || parameterName == triggeringUserRuntimeArgName)
            {
                return(ExprTypeHelper.EntityOfType(UserAccount.UserAccount_Type));
            }


            if (parameterName == triggeringPersonRuntimeArgName)
            {
                return(ExprTypeHelper.EntityOfType(Person.Person_Type));
            }


            ExprType result = null;

            if (AllOutputTypes.TryGetValue(parameterName, out result))
            {
                return(result);
            }

            if (AllInputAndVariableTypes.TryGetValue(parameterName, out result))
            {
                return(result);
            }

            return(null);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Take the people and the expression and produce a list of numbers or nulls
        /// </summary>
        /// <param name="people"></param>
        /// <param name="expressionString"></param>
        /// <param name="missing"></param>
        /// <returns></returns>
        IEnumerable <string> FetchAddresses(IEnumerable <IEntity> people, string expressionString)
        {
            if (expressionString == null)
            {
                throw new ArgumentException(nameof(expressionString));
            }

            var bSettings = new BuilderSettings
            {
                ScriptHost         = ScriptHostType.Evaluate,
                ExpectedResultType = ExprType.String,
                RootContextType    = ExprTypeHelper.EntityOfType(Person.Person_Type)
            };

            var expression       = Factory.ExpressionCompiler.Compile(expressionString, bSettings);
            var expressionRunner = Factory.ExpressionRunner;


            var addresses = people.Select(p =>
            {
                var evalSettings = new EvaluationSettings {
                    ContextEntity = p
                };
                return((string)expressionRunner.Run(expression, evalSettings).Value);
            });

            return(addresses);
        }
Ejemplo n.º 5
0
        /// <summary>
        ///     Compiles the expression.
        /// </summary>
        /// <param name="contextEntityTypeId">The context entity type identifier.</param>
        /// <param name="expression">The expression.</param>
        /// <returns></returns>
        private IExpression CompileExpression(EntityRef contextEntityTypeId, CalcEngineExpression expression)
        {
            var builderSettings = new BuilderSettings
            {
                RootContextType = ExprTypeHelper.EntityOfType(contextEntityTypeId),
                ScriptHost      = ScriptHostType.Any
            };

            return(Factory.ExpressionCompiler.Compile(expression.Expression, builderSettings));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Create a query that converts a calculation into a report that returns a list of IDs.
        /// </summary>
        /// <param name="filterCalculation">The calculation script.</param>
        /// <param name="entityType">The type of resource to load (and filter).</param>
        /// <param name="exactType">True if the report should return exact types only, false to include derived types.</param>
        public static StructuredQuery BuildFilterQuery(string filterCalculation, EntityRef entityType, bool exactType)
        {
            // Validate
            if (string.IsNullOrEmpty("filterCalculation"))
            {
                throw new ArgumentNullException("filterCalculation");
            }
            if (entityType == null)
            {
                throw new ArgumentNullException("entityType");
            }

            // Compile the calculation into an expression
            BuilderSettings builderSettings = new BuilderSettings {
                ExpectedResultType = ExprType.Bool,
                RootContextType    = ExprTypeHelper.EntityOfType(entityType),
                ScriptHost         = ScriptHostType.Report,
                ScriptHostIsApi    = true
            };
            IExpression filterCalcExpr = Factory.ExpressionCompiler.Compile(filterCalculation, builderSettings);

            // Create the structured query
            var rootEntity = new ResourceEntity {
                EntityTypeId = entityType,
                ExactType    = exactType
            };
            var query = new StructuredQuery()
            {
                RootEntity = rootEntity
            };

            // Generate a report condition for the filter
            QueryBuilderSettings queryBuilderSettings = new QueryBuilderSettings {
                ContextEntity        = rootEntity,
                ConvertBoolsToString = false,
                StructuredQuery      = query
            };
            ScalarExpression filterScalarExpr = Factory.ExpressionCompiler.CreateQueryEngineExpression(filterCalcExpr, queryBuilderSettings);

            rootEntity.Conditions = new List <ScalarExpression> {
                filterScalarExpr
            };

            return(query);
        }
Ejemplo n.º 7
0
 ExprType TypeFromInstance(WfArgumentInstance ai)
 {
     if (ai.InstanceConformsToType != null)
     {
         if (ai.ArgumentInstanceArgument.Is <ResourceArgument>())
         {
             return(ExprTypeHelper.EntityOfType(ai.InstanceConformsToType));
         }
         else
         {
             return(ExprTypeHelper.EntityListOfType(ai.InstanceConformsToType));
         }
     }
     else
     {
         return(CalcExpressionType(ai.ArgumentInstanceArgument));
     }
 }
        /// <summary>
        /// Create compilation settings that are appropriate for a given field.
        /// </summary>
        /// <param name="calculatedField">The calculated field.</param>
        /// <param name="settings">The settings.</param>
        /// <returns></returns>
        internal static BuilderSettings CreateBuilderSettingsForField(Field calculatedField, CalculatedFieldSettings settings)
        {
            // Determine calculation context type
            EntityType type        = calculatedField.FieldIsOnType;
            ExprType   contextType = ExprTypeHelper.EntityOfType(new EntityRef(type.Id));

            // Determine result type
            ExprType expectedResult = ExprTypeHelper.FromFieldEntity(calculatedField);

            expectedResult.DisallowList = true;

            // Create settings
            BuilderSettings builderSettings = new BuilderSettings();

            builderSettings.ScriptHost         = ScriptHostType.Any;
            builderSettings.RootContextType    = contextType;
            builderSettings.ExpectedResultType = expectedResult;

            return(builderSettings);
        }
        /// <summary>
        ///     Compiles the visibility calculations.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="visibilityCalculations">The visibility calculations.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">
        /// </exception>
        private IDictionary <long, IExpression> CompileVisibilityCalculations(EntityRef entityType,
                                                                              IDictionary <long, string> visibilityCalculations)
        {
            var compiledCalculations = new Dictionary <long, IExpression>();

            if (visibilityCalculations.Count == 0)
            {
                return(compiledCalculations);
            }

            var builderSettings = new BuilderSettings
            {
                RootContextType    = ExprTypeHelper.EntityOfType(entityType),
                ScriptHost         = ScriptHostType.Any,
                ExpectedResultType = new ExprType(DataType.Bool) // Visibility calculations should always return a bool
            };

            // Compile calculations
            foreach (var kvp in visibilityCalculations)
            {
                try
                {
                    var expression = Factory.ExpressionCompiler.Compile(kvp.Value, builderSettings);
                    if (expression.ResultType.Type == DataType.Bool)
                    {
                        compiledCalculations[kvp.Key] = expression;
                    }
                }
                catch (Exception ex)
                {
                    // Be resilient to compile errors.
                    EventLog.Application.WriteError(
                        "An error occured compiling visibility calculation {0} for form control {1}. Error {2}.",
                        kvp.Value, kvp.Key, ex);
                }
            }

            return(compiledCalculations);
        }
Ejemplo n.º 10
0
        private static TestValue ReadValue(string dataRaw)
        {
            string[] dataParts = dataRaw.Split(new[] { ':' }, 2);
            dataParts[0] = dataParts[0].Trim();

            var    result   = new TestValue();
            string typeName = dataParts[0];
            bool   isList   = typeName.EndsWith(" list");

            if (isList)
            {
                typeName = typeName.Substring(0, typeName.Length - " list".Length);
            }
            bool disallowList = typeName.EndsWith(" disallowlist");

            if (disallowList)
            {
                typeName = typeName.Substring(0, typeName.Length - " disallowlist".Length);
            }
            bool untrimmed = typeName.EndsWith(" untrimmed");

            if (untrimmed)
            {
                typeName = typeName.Substring(0, typeName.Length - " untrimmed".Length);
            }
            else
            {
                if (dataParts.Length > 1)
                {
                    dataParts[dataParts.Length - 1] = dataParts[dataParts.Length - 1].TrimEnd();
                }
            }

            if (typeName == "int")
            {
                typeName = "Int32";
            }

            string[] typeParts    = typeName.Split(new [] { '(', ')' });
            string   typeNameBase = typeParts[0];

            DataType dataType;

            if (Enum.TryParse(typeNameBase, true, out dataType))
            {
                // scalar
                result.ExprType              = new ExprType(dataType);
                result.ExprType.IsList       = isList;
                result.ExprType.DisallowList = disallowList;

                if (typeParts.Length > 1)
                {
                    result.ExprType.DecimalPlaces = int.Parse(typeParts[1]);
                }
                if (dataParts.Length > 1)
                {
                    var dbType = DataTypeHelper.ToDatabaseType(result.ExprType.Type);
                    if (isList)
                    {
                        var      resultList = new List <object>();
                        string[] values     = dataParts[1].Split(',');
                        foreach (string sValue in values)
                        {
                            object value = null;
                            if (sValue != "null")
                            {
                                if (typeNameBase == "date" || typeNameBase == "datetime")
                                {
                                    result.Value = DateTime.Parse(sValue, (new CultureInfo("en-AU")).DateTimeFormat);
                                    if (typeNameBase == "datetime")
                                    {
                                        // treat date-time test data as local time
                                        result.Value = TimeZoneHelper.ConvertToUtc((DateTime)result.Value,
                                                                                   TimeZoneHelper.SydneyTimeZoneName);
                                    }
                                }
                                else
                                {
                                    value = dbType.ConvertFromString(sValue); // this method is stuffed
                                    if (value is float)
                                    {
                                        value = (decimal)(float)result.Value;
                                    }
                                    if (value is TimeSpan)
                                    {
                                        value = TimeType.NewTime((TimeSpan)result.Value);
                                    }
                                }
                            }
                            resultList.Add(value);
                        }
                        result.Value = resultList;
                    }
                    else
                    {
                        if (dataParts[1] != "null")
                        {
                            if (typeNameBase == "date" || typeNameBase == "datetime")
                            {
                                result.Value = DateTime.Parse(dataParts[1], (new CultureInfo("en-AU")).DateTimeFormat);
                                if (typeNameBase == "datetime")
                                {
                                    // treat date-time test data as local time
                                    result.Value = TimeZoneHelper.ConvertToUtc((DateTime)result.Value,
                                                                               TimeZoneHelper.SydneyTimeZoneName);
                                }
                            }
                            else
                            {
                                result.Value = dbType.ConvertFromString(dataParts[1]); // this method is stuffed
                                if (result.Value is float)
                                {
                                    result.Value = (decimal)(float)result.Value;
                                }
                                if (result.Value is TimeSpan)
                                {
                                    result.Value = TimeType.NewTime((TimeSpan)result.Value);
                                }
                            }
                        }
                    }
                }
                else
                {
                    result.NoValue = true;
                }
            }
            else
            {
                // entity
                result.ResourceTypeName = typeName;
                long       resourceTypeId = Factory.ScriptNameResolver.GetTypeByName(result.ResourceTypeName);
                EntityType resourceType   = EDC.ReadiNow.Model.Entity.Get <EntityType>(resourceTypeId);
                if (resourceType == null)
                {
                    throw new Exception("ResourceType not found");
                }

                result.ExprType        = ExprTypeHelper.EntityOfType(new EntityRef(resourceTypeId));
                result.ExprType.IsList = isList;
                if (dataParts.Length > 1)
                {
                    result.ResourceName = dataParts[1];
                    if (isList)
                    {
                        if (dataParts[1] == "")
                        {
                            result.Value = new EntityType[] { }
                        }
                        ;
                        else
                        {
                            var    resList = new List <IEntity>();
                            string names   = dataParts[1].Trim();
                            if (names != "" && names != "empty")
                            {
                                foreach (string name in names.Split(','))
                                {
                                    var match = Factory.ScriptNameResolver.GetInstance(name.Trim(), resourceType.Id);
                                    if (match == null)
                                    {
                                        throw new Exception(string.Format("Test error: could not find {0} called {1}",
                                                                          typeName, name));
                                    }
                                    resList.Add(match);
                                }
                            }
                            result.Value = resList.ToArray();
                        }
                    }
                    else if (result.ResourceName != "null")
                    {
                        result.Resource = Factory.ScriptNameResolver.GetInstance(result.ResourceName, resourceType.Id);
                        result.Value    = result.Resource;
                    }
                }
                else
                {
                    result.NoValue = true;
                }
            }
            result.Untrimmed = untrimmed;
            return(result);
        }
Ejemplo n.º 11
0
        private void Run(bool runReport)
        {
            SaveSettings();
            long tenantId = cmbTenant.SelectedIndex == 0
                                ? 0
                                : ((TenantEntry)cmbTenant.Items[cmbTenant.SelectedIndex]).Id;

            StringBuilder sb = new StringBuilder();

            try
            {
                using (new TenantAdministratorContext(tenantId))
                    using (new SecurityBypassContext())
                    {
                        // Get context
                        long    contextTypeId = 0;
                        IEntity context       = null;
                        if (!string.IsNullOrEmpty(txtContextType.Text))
                        {
                            contextTypeId = Factory.ScriptNameResolver.GetTypeByName(txtContextType.Text);
                            if (contextTypeId == 0)
                            {
                                sb.AppendLine("Cannot resolve context type: " + txtContextType.Text);
                                return;
                            }
                            else if (!string.IsNullOrEmpty(txtContextResource.Text))
                            {
                                long typeId = Factory.ScriptNameResolver.GetTypeByName(txtContextType.Text);
                                if (typeId != 0)
                                {
                                    context = Factory.ScriptNameResolver.GetInstance(txtContextResource.Text, typeId);
                                }

                                if (context == null)
                                {
                                    sb.AppendLine("Cannot resolve context resource: " + txtContextType.Text);
                                    return;
                                }
                            }
                        }

                        // Compile
                        BuilderSettings bsettings = new BuilderSettings();
                        if (contextTypeId != 0)
                        {
                            bsettings.RootContextType = ExprTypeHelper.EntityOfType(new EntityRef(contextTypeId));
                        }
                        if (runReport)
                        {
                            bsettings.ScriptHost = ScriptHostType.Report;
                        }
                        IExpression expr = Factory.ExpressionCompiler.Compile(txtFormula.Text, bsettings);
                        sb.AppendLine("Type: " + expr.ResultType);


                        if (runReport)
                        {
                            RunReport(sb, contextTypeId, expr);
                        }
                        else
                        {
                            expr = RunEval(sb, context, bsettings, expr);
                        }
                    }
            }
            catch (ParseException ex)
            {
                sb.AppendLine("Script error:");
                sb.AppendLine(ex.Message);
            }
            catch (Exception ex)
            {
                sb.AppendLine(ex.ToString());
            }
            finally
            {
                txtResult.Text = sb.ToString();
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        ///     Inners the eval.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        private static EvalResult InnerEval(EvalRequest request)
        {
            try
            {
                var settings = new BuilderSettings( );

                if (!string.IsNullOrEmpty(request.Context))
                {
                    long      typeId;
                    EntityRef contextType = long.TryParse(request.Context, out typeId)
                                                ? new EntityRef(typeId)
                                                : new EntityRef(request.Context);
                    settings.RootContextType = ExprTypeHelper.EntityOfType(contextType);
                }
                if (!string.IsNullOrEmpty(request.Host))
                {
                    settings.ScriptHost = ( ScriptHostType )Enum.Parse(typeof(ScriptHostType), request.Host);
                }


                var paramTypes  = new Dictionary <string, ExprType>( );
                var paramValues = new Dictionary <string, object>( );

                if (request.Parameters != null)
                {
                    foreach (ExpressionParameter p in request.Parameters)
                    {
                        var type = ( DataType )Enum.Parse(typeof(DataType), p.TypeName);
                        if (type == DataType.Entity)
                        {
                            long typeId;
                            paramTypes[p.Name] = long.TryParse(p.EntityTypeId, out typeId)
                                                                ? ExprTypeHelper.EntityOfType(new EntityRef(typeId))
                                                                : ExprTypeHelper.EntityOfType(new EntityRef(p.EntityTypeId));
                        }
                        else
                        {
                            paramTypes[p.Name] = new ExprType(type);
                        }
                        paramTypes[p.Name].IsList = p.IsList;
                        paramValues[p.Name]       = DataTypeHelpers.StringToObject(p.StringValue, type);
                    }
                    settings.ParameterNames          = paramTypes.Keys.ToList( );
                    settings.StaticParameterResolver = paramName =>
                    {
                        ExprType result2;
                        return(paramTypes.TryGetValue(paramName, out result2) ? result2 : null);
                    };
                }

                // Compile
                IExpression expression = Factory.ExpressionCompiler.Compile(request.Expression, settings);

                // used for runtime parameters
                EvaluationSettings evalSettings = new EvaluationSettings
                {
                    TimeZoneName      = TimeZoneHelper.SydneyTimeZoneName,
                    ParameterResolver = paramName =>
                    {
                        object result1;
                        return(paramValues.TryGetValue(paramName, out result1) ? result1 : null);
                    }
                };
                object result = Factory.ExpressionRunner.Run(expression, evalSettings).Value;

                // Return success result
                return(new EvalResult
                {
                    Value = result.ToString( ),
                    ResultType = expression.ResultType.Type,
                    IsList = expression.ResultType.IsList,
                    EntityTypeId = expression.ResultType.EntityTypeId
                });
            }
            catch (ParseException ex)
            {
                // Return script error result
                return(new EvalResult
                {
                    ErrorMessage = ex.Message
                });
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        ///     Inners the compile.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        private static CompileResult InnerCompile(EvalRequest request)
        {
            try
            {
                var settings = new BuilderSettings( );

                if (!string.IsNullOrEmpty(request.Context))
                {
                    EntityRef contextType = WebApiHelpers.GetId(request.Context);
                    settings.RootContextType = ExprTypeHelper.EntityOfType(contextType);
                }
                if (!string.IsNullOrEmpty(request.Host))
                {
                    settings.ScriptHost = ( ScriptHostType )Enum.Parse(typeof(ScriptHostType), request.Host);
                }

                if (request.ExpectedResultType != null)
                {
                    settings.ExpectedResultType = request.ExpectedResultType.ToExprType();
                }

                var paramTypes = new Dictionary <string, ExprType>( );

                if (request.Parameters != null)
                {
                    foreach (ExpressionParameter p in request.Parameters)
                    {
                        if (p.Name == null)
                        {
                            throw new WebArgumentException("Param 'name' was not specified");
                        }
                        if (p.TypeName == null)
                        {
                            throw new WebArgumentException("Param 'type' was not specified");
                        }

                        var type = ( DataType )Enum.Parse(typeof(DataType), p.TypeName);
                        if (type == DataType.Entity)
                        {
                            if (p.EntityTypeId == null)
                            {
                                throw new WebArgumentException("Param 'entityTypeId' was not specified");
                            }

                            long typeId;
                            paramTypes[p.Name] = long.TryParse(p.EntityTypeId, out typeId)
                                                                ? ExprTypeHelper.EntityOfType(new EntityRef(typeId))
                                                                : ExprTypeHelper.EntityOfType(new EntityRef(p.EntityTypeId));
                        }
                        else
                        {
                            paramTypes[p.Name] = new ExprType(type);
                        }
                        paramTypes[p.Name].IsList = p.IsList;
                    }
                    settings.ParameterNames          = paramTypes.Keys.ToList( );
                    settings.StaticParameterResolver = paramName =>
                    {
                        ExprType result2;
                        return(paramTypes.TryGetValue(paramName, out result2) ? result2 : null);
                    };
                }

                // Compile
                IExpression expression = Factory.ExpressionCompiler.Compile(request.Expression, settings);

                // Return success result
                return(new CompileResult
                {
                    ResultType = expression.ResultType.Type,
                    IsList = expression.ResultType.IsList,
                    EntityTypeId = expression.ResultType.EntityTypeId
                });
            }
            catch (ParseException ex)
            {
                // Return script error result
                return(new CompileResult
                {
                    ErrorMessage = ex.Message
                });
            }
        }