Example #1
0
        protected internal override bool ValidateInitializer(IDefinitionInstallerContext installer)
        {
            if (installer == null)
            {
                throw new ArgumentNullException();
            }
            // 2. Get the global.
            GlobalVariableOrConstantBinding globalBinding = installer.GetGlobalVariableOrConstantBinding(this.GlobalName.Value);
            ClassBinding classBinding = installer.GetClassBinding(this.GlobalName.Value);

            // 3. Check that such a binding exists ... but not both
            if (!((globalBinding == null) ^ (classBinding == null)))
            {
                return(installer.ReportError(this.GlobalName, InstallerErrors.GlobalInvalidName));
            }
            if ((classBinding != null) && (classBinding.Value == null))
            {
                throw new InvalidOperationException("Should have been set in ClassDefinition.CreataGlobalObject().");
            }

            if (classBinding != null)
            {
                return(this.Factory.ValidateClassInitializer(this, classBinding.Value, installer,
                                                             new IntermediateCodeValidationErrorSink(this.MethodSourceCodeService, installer)));
            }

            if (globalBinding.IsConstantBinding && globalBinding.HasBeenSet)
            {
                return(installer.ReportError(this.GlobalName, InstallerErrors.GlobalIsConstant));
            }

            return(this.Factory.ValidateGlobalInitializer(this, installer,
                                                          new IntermediateCodeValidationErrorSink(this.MethodSourceCodeService, installer)));
        }
        public ClassBindingMap(IDictionary <string, string> ClassListMap, ClassBinding WhichBinding = ClassBinding.Properties)
        {
            if (ClassListMap == null)
            {
                throw new ArgumentNullException();
            }
            if (ClassListMap.Count == 0)
            {
                throw new IndexOutOfRangeException();
            }

            switch (WhichBinding)
            {
            case ClassBinding.Properties:
                PropertiesMapping = ClassListMap;
                break;

            case ClassBinding.Fields:
                VariableMapping = ClassListMap;
                break;

            case ClassBinding.All:
                PropertiesMapping = ClassListMap;
                VariableMapping   = ClassListMap;
                break;

            default:
                throw new NotImplementedException("ClassBinding enum is not known.");
            }
        }
        /// <summary>
        /// Adds a given type to the mapper.
        /// </summary>
        /// <typeparam name="T">DTO to add</typeparam>
        public static void Add <T>()
        {
            var type = typeof(T);

            if (_bindings.ContainsKey(type))
            {
                return;
            }

            var constructorInfo = type.GetConstructors().Where((a) => a.GetParameters().Length == 0).FirstOrDefault();

            if (constructorInfo == null)
            {
                throw new ArgumentException($"There is no default public constructor for the type {type.FullName}");
            }

            var classBinding = new ClassBinding(type, constructorInfo);

            foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                var ignoreAttribute = property.GetCustomAttribute <SqlIgnoreAttribute>();
                if (ignoreAttribute != null)
                {
                    continue;
                }

                var name = property.GetCustomAttribute <SqlColumnNameAttribute>()?.Column ?? property.Name;

                classBinding.AddPropertyBinding(new ColumnPropertyBinding(property, name));
            }

            _bindings[type] = classBinding;
        }
        protected internal bool ValidateMethod(IDefinitionInstallerContext installer)
        {
            if (installer == null)
            {
                throw new ArgumentNullException();
            }
            // 1. Check if the selector is not complete garbage.
            if (String.IsNullOrWhiteSpace(this.Selector.Value))
            {
                return(installer.ReportError(this.Selector, InstallerErrors.MethodInvalidSelector));
            }
            // 2. Get the class.
            ClassBinding classBinding = installer.GetClassBinding(this.ClassName.Value);

            // 3. Check that such a binding exists
            if (classBinding == null)
            {
                return(installer.ReportError(this.ClassName, InstallerErrors.MethodInvalidClassName));
            }
            if (classBinding.Value == null)
            {
                throw new InvalidOperationException("Should have been set in ClassDefinition.CreataGlobalObject().");
            }

            // 3. Create the binding ... We allow duplicates and overwriting existing methods
            return(this.InternalValidateMethod(installer, classBinding.Value,
                                               new IntermediateCodeValidationErrorSink(this.MethodSourceCodeService, installer)));
        }
Example #5
0
        public static CompiledInitializer AddClassInitializer(SmalltalkRuntime runtime, SmalltalkNameScope scope, Type delegateType, string delegateName, string className)
        {
            ClassBinding binding = scope.GetClassBinding(className);

            if (binding == null)
            {
                throw new ArgumentException(String.Format("Class named {0} does not exist.", className));
            }
            return(NativeLoadHelper.AddInitializer(scope, InitializerType.ClassInitializer, binding, delegateType, delegateName));
        }
Example #6
0
        public SmalltalkClass GetClass(Symbol name)
        {
            ClassBinding binding = this.Runtime.GlobalScope.GetClassBinding(name);

            if (binding == null)
            {
                return(null);
            }
            return(binding.Value);
        }
Example #7
0
        private static ClassMemberBinding TranslateBinding(MethodCallExpression expression)
        {
            if (expression.Object == null)
            {
                var methodInfo = expression.Method;
                var classType  = methodInfo.ReflectedType;
                // fluent-syntactic-sugar Dsl.RuleSet.Context class is replaced by actual runtime RuleEngine.Context class
                if (classType != typeof(RuleSet.Context))
                {
                    var @class    = new ClassBinding(classType);
                    var arguments = TranslateArguments(expression.Arguments);
                    return(new ClassMemberBinding(methodInfo.Name, @class, arguments));
                }

                var contextClass       = new ClassBinding(typeof(Context));
                var contextArguments   = TranslateMessageContextPropertyArgument(expression.Arguments);
                var classMemberBinding = new ClassMemberBinding(methodInfo.Name, contextClass, contextArguments);

                // contextRead is just a way to get 'Read' method's name in a refactoring-safe way should its name change;
                // besides, performance is irrelevant as this code is never executed at runtime but only during deployment.
                Expression <Func <Context, object> > contextRead = c => c.Read(null);
                if (methodInfo.Name == ((MethodCallExpression)contextRead.Body).Method.Name)
                {
                    // RuleEngine.Context.Read() will actually return an object, whereas Dsl.RuleSet.Context would return a
                    // strong-typed value. Because one has written DSL expressions involving the strong-typed value, it has
                    // to be casted into the expected type, or else RuleEngine will throw a type mismatch exception. It is
                    // important to call the respective .To<TypeCode>() conversion methods and not the .ChangeType() one as
                    // the latter throws when Context.Read() returns null.
                    classMemberBinding = new ClassMemberBinding(
                        "To" + Type.GetTypeCode(expression.Type),
                        new ClassBinding(typeof(Convert)),
                        new ArgumentCollection {
                        new UserFunction(classMemberBinding)
                    });
                    classMemberBinding.SideEffects = false;
                }

                return(classMemberBinding);
            }

            //var methodCallExpression = expression.Object as MethodCallExpression;
            //if (methodCallExpression != null)
            //{
            //   var @class = TranslateBinding(methodCallExpression);
            //   var arguments = TranslateArguments(expression.Arguments);
            //   return new ClassMemberBinding(expression.Method.Name, @class, arguments);
            //}

            throw new NotSupportedException(
                      string.Format(
                          "Cannot translate MethodCallExpression \"{0}\" because {1} is neither null nor a static: " +
                          "writing rules against a specific object/instance is not supported.",
                          expression,
                          expression.Object));
        }
Example #8
0
        private void RegisterNativeTypeMapping()
        {
            ClassBinding binding = this.Runtime.Classes[this.Name];

            foreach (KeyValuePair <string, string> annotation in binding.Annotations)
            {
                if ((annotation.Key == "ist.runtime.native-class") && !String.IsNullOrWhiteSpace(annotation.Value))
                {
                    this.Runtime.NativeTypeClassMap.RegisterClass(this, annotation.Value);
                }
            }
        }
        static RuleSet CreateRuleset(string rulesetName)
        {
            // create a simple rule
            // IF MySampleBusinessObject.MyValue != XMLdocument.ID
            // THEN MySampleBusinessObject.MySampleMethod1(5)

            //Creating the XML bindings on the SampleSchema XSD

            //Document Binding that binds to the schema name and specifies the selector
            XPathPair          xp_root = new XPathPair("/*[local-name()='Root']", "Root");
            XMLDocumentBinding xdb     = new XMLDocumentBinding("SampleSchema", xp_root);

            //DocumentField Bindings that bind to the fields in the schema that need to be used in rule defintion
            XPathPair xp_ID = new XPathPair("/*[local-name()='Root']/*[local-name()='ID']", "ID");
            XMLDocumentFieldBinding xfb1 = new XMLDocumentFieldBinding(Type.GetType("System.Int32"), xp_ID, xdb);

            //Creating .NET class (property and member) bindings

            // Class Bindings to bind to the class defintions whose properties and memebers will be used in rule defintion
            ClassBinding cb = new ClassBinding(typeof(Microsoft.Samples.BizTalk.BusinessRulesHelloWorld2.HelloWorld2Library.HelloWorld2LibraryObject));

            // Member Bindings to bind to the properties and members in the MySampleBusinessObject class that need to be used in rule definition
            ClassMemberBinding myValue = new ClassMemberBinding("MyValue", cb);

            ArgumentCollection argList = new ArgumentCollection();

            argList.Add(new Constant(5));
            ClassMemberBinding method1 = new ClassMemberBinding("MySampleMethod", cb, argList);


            // create IF part
            LogicalExpression condition = new NotEqual(new UserFunction(myValue), new UserFunction(xfb1));

            // create then part
            ActionCollection actions = new ActionCollection();

            actions.Add(new UserFunction(method1));

            // create the rule
            Rule rule1 = new Rule("rule1", 0, condition, actions);

            //create the verion information and ruleset description

            DateTime    time  = new DateTime(System.DateTime.Now.Year, System.DateTime.Now.Month, System.DateTime.Now.Day);
            VersionInfo vinf1 = new VersionInfo("Sample RuleSet to demonstrate the use of the Policy object", time, "BizRules", 1, 0);

            // create the ruleset
            RuleSet rs1 = new RuleSet(rulesetName, vinf1);

            rs1.Rules.Add(rule1);
            return(rs1);
        }
Example #10
0
        /// <summary>
        /// Get the Smalltalk class with the given name.
        /// </summary>
        /// <param name="name">Class name.</param>
        /// <returns>The Smalltalk class with the given name or null if none found.</returns>
        public SmalltalkClass GetClass(string name)
        {
            ClassBinding binding = this.GlobalScope.GetClassBinding(name);

            if (binding != null)
            {
                return(binding.Value);
            }
            else
            {
                return(null);
            }
        }
Example #11
0
 /// <summary>
 /// Internal! This is used by the Installer to create new classes.
 /// </summary>
 /// <param name="runtime">Smalltalk runtime this class is part of.</param>
 /// <param name="name">Name of the class.</param>
 /// <param name="superclass">Optional binding to the class' superclass.</param>
 /// <param name="instanceState">State of the class' instances (named, object-indexable, byte-indexable).</param>
 /// <param name="instanceVariables">Instance variables bindings. Those are initially not initialized.</param>
 /// <param name="classVariables">Class variable binding.</param>
 /// <param name="classInstanceVariables">Class-instance variables bindings. Those are initially not initialized.</param>
 /// <param name="importedPools">Collection of pools that are imported by the class.</param>
 /// <param name="instanceMethods">Collection with the methods defining the instance behaviors.</param>
 /// <param name="classMethods">Collection with the methods defining the class behaviors.</param>
 public SmalltalkClass(SmalltalkRuntime runtime, Symbol name, ClassBinding superclass, InstanceStateEnum instanceState,
                       BindingDictionary <InstanceVariableBinding> instanceVariables, DiscreteBindingDictionary <ClassVariableBinding> classVariables,
                       BindingDictionary <ClassInstanceVariableBinding> classInstanceVariables, DiscreteBindingDictionary <PoolBinding> importedPools,
                       InstanceMethodDictionary instanceMethods, ClassMethodDictionary classMethods)
 {
     if (runtime == null)
     {
         throw new ArgumentNullException("runtime");
     }
     if ((name == null) || (name.Value.Length == 0))
     {
         throw new ArgumentNullException("name");
     }
     if (!SmalltalkClass.ValidateIdentifiers <InstanceVariableBinding>(instanceVariables))
     {
         throw new ArgumentException("Invalid or duplicate instance variable name found", "instanceVariables");
     }
     if (!SmalltalkClass.ValidateIdentifiers <ClassVariableBinding>(classVariables))
     {
         throw new ArgumentException("Invalid or duplicate class variable name found", "classVariables");
     }
     if (!SmalltalkClass.ValidateIdentifiers <ClassInstanceVariableBinding>(classInstanceVariables))
     {
         throw new ArgumentException("Invalid or duplicate class instance variable name found", "classInstanceVariables");
     }
     if (!SmalltalkClass.ValidateIdentifiers <PoolBinding>(importedPools))
     {
         throw new ArgumentException("Invalid or duplicate imported pool name found", "importedPools");
     }
     if (!SmalltalkClass.CheckDuplicates <InstanceVariableBinding, ClassVariableBinding>(instanceVariables, classVariables))
     {
         throw new ArgumentException("Duplicate instance or class variable name. Instance and class variable names must be unique.");
     }
     if (!SmalltalkClass.CheckDuplicates <ClassInstanceVariableBinding, ClassVariableBinding>(classInstanceVariables, classVariables))
     {
         throw new ArgumentException("Duplicate class-instance or class variable name. Class-instance and class variable names must be unique.");
     }
     this.Runtime = runtime;
     this.ClassInstanceVariableBindings = classInstanceVariables ?? new BindingDictionary <ClassInstanceVariableBinding>(this.Runtime, 1);
     this.ClassBehavior            = classMethods ?? new ClassMethodDictionary(this.Runtime);
     this.ClassVariableBindings    = classVariables ?? new DiscreteBindingDictionary <ClassVariableBinding>(this.Runtime, 1);
     this.ImportedPoolBindings     = importedPools ?? new DiscreteBindingDictionary <PoolBinding>(this.Runtime, 1);
     this.InstanceBehavior         = instanceMethods ?? new InstanceMethodDictionary(this.Runtime);
     this.InstanceState            = instanceState;
     this.InstanceVariableBindings = instanceVariables ?? new BindingDictionary <InstanceVariableBinding>(this.Runtime, 1);
     this.Name = name;
     this.SuperclassBinding      = superclass; // Null is OK .... Object has null
     this.InstanceSize           = 0;
     this.ClassInstanceSize      = 0;
     this.ClassInstanceVariables = new object[0];
 }
Example #12
0
        public MvClassData(AstFrame frame, int id, string name)
        {
            ClassId      = id;
            ClassName    = name;
            Frame        = frame;
            ClassBinding = GMacMultivectorBinding.Create(frame.FrameMultivector);

            if (id < 1)
            {
                return;
            }

            foreach (var grade in ClassGrades)
            {
                ClassBinding.BindKVectorToVariables(grade);
            }
        }
Example #13
0
        public static ClassBinding AddClassBinding(SmalltalkRuntime runtime, SmalltalkNameScope scope, string name)
        {
            if (runtime == null)
            {
                throw new ArgumentNullException("runtime");
            }
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            Symbol       symbol  = runtime.GetSymbol(name);
            ClassBinding binding = new ClassBinding(symbol);

            scope.Classes.Add(binding);
            return(binding);
        }
Example #14
0
        public CompiledInitializer CreateInitializer(InitializerDefinition definition, IDefinitionInstallerContext installer)
        {
            GlobalVariableOrConstantBinding globalBinding = installer.GetGlobalVariableOrConstantBinding(this.GlobalName);
            ClassBinding classBinding = installer.GetClassBinding(this.GlobalName);

            // 3. Check that such a binding exists ... but not both
            if (!((globalBinding == null) ^ (classBinding == null)))
            {
                return(null);
            }

            if (classBinding != null)
            {
                return(new RuntimeGlobalInitializer(this.ParseTree, new DebugInfoService(this.SourceCodeService), classBinding));
            }
            if (globalBinding != null)
            {
                return(new RuntimeGlobalInitializer(this.ParseTree, new DebugInfoService(this.SourceCodeService), globalBinding));
            }
            return(null);
        }
Example #15
0
        private static IEnumerable <Term> TranslateMessageContextPropertyTerm(MemberExpression expression)
        {
            if (!expression.Type.IsSubclassOfOpenGenericType(typeof(MessageContextProperty <,>)))
            {
                throw new InvalidOperationException(
                          string.Format(
                              "Cannot translate MemberExpression \"{0}\" of type {1}; only expressions of type MessageContextProperty<,> are expected at this stage.",
                              expression,
                              expression.Type));
            }

            // handle MessageContextProperty<TP, TV>
            var member        = expression.Member;
            var reflectedType = member.ReflectedType;

            if (expression.Expression != null)
            {
                var property = Expression.Lambda(expression).Compile().DynamicInvoke() as IMessageContextProperty;
                if (property == null)
                {
                    throw new NotSupportedException(
                              string.Format(
                                  "Cannot translate MemberExpression \"{0}\" because {1} is not null: MessageContextProperty<,> properties are static and a call site is not expected.",
                                  expression,
                                  expression.Expression));
                }
                return(new Term[] { new Constant(property.Name), new Constant(property.Namespace) });
            }

            // qnameGetter is just a way to get 'QName' property's name in a refactoring-safe way should its name change;
            // besides, performance is irrelevant as this code is never executed at runtime but only during deployment.
            Expression <Func <IMessageContextProperty, XmlQualifiedName> > qnameGetter = c => c.QName;
            var classBinding       = new ClassBinding(reflectedType);
            var classMemberBinding = new ClassMemberBinding(member.Name, classBinding);

            return(new Term[] { new UserFunction(new ClassMemberBinding(((MemberExpression)qnameGetter.Body).Member.Name, classMemberBinding)) });
        }
        private string WriteTerm(Term term)
        {
            string             displayString = "";
            ArgumentCollection args          = null;

            if (term is Constant)
            {
                if (((Constant)term).Value != null)
                {
                    if (((Constant)term).Value.ToString() == string.Empty)
                    {
                        displayString = "&lt;empty string&gt;";
                    }
                    else
                    {
                        displayString = ((Constant)term).Value.ToString();
                    }
                }
                else
                {
                    displayString = "&lt;null&gt;";
                }
            }

            else if (term is UserFunction || term is ObjectReference)
            {
                Binding termBinding = null;

                if (term is UserFunction)
                {
                    termBinding = ((UserFunction)term).Binding;
                }
                else
                {
                    termBinding = ((ObjectReference)term).Binding;
                }

                if (termBinding is XMLDocumentBinding)
                {
                    XMLDocumentBinding binding = termBinding as XMLDocumentBinding;
                    displayString = binding.DocumentType;
                }
                else if (termBinding is DatabaseBinding)
                {
                    DatabaseBinding binding = termBinding as DatabaseBinding;
                    displayString = binding.DatasetName;
                }
                else if (termBinding is ClassBinding)
                {
                    ClassBinding binding = termBinding as ClassBinding;
                    displayString = binding.TypeName;
                }
                else if (termBinding is XMLDocumentFieldBinding)
                {
                    XMLDocumentFieldBinding binding = termBinding as XMLDocumentFieldBinding;
                    displayString = binding.DocumentBinding.DocumentType + ":" + binding.DocumentBinding.Selector.Alias + "/" + binding.Field.Alias;

                    if (binding.Argument != null)
                    {
                        if (binding.MemberName.ToLower() == "setstring")
                        {
                            displayString += " = {0}";
                        }

                        args = new ArgumentCollection();
                        args.Add(binding.Argument);
                    }
                }
                else if (termBinding is DatabaseColumnBinding)
                {
                    DatabaseColumnBinding binding = termBinding as DatabaseColumnBinding;
                    displayString = binding.DatabaseBinding.DatasetName + "." + binding.DatabaseBinding.TableName + "." + binding.ColumnName;

                    if (binding.Argument != null)
                    {
                        args = new ArgumentCollection();
                        args.Add(binding.Argument);
                    }
                }
                else if (termBinding is DataRowBinding)
                {
                    DataRowBinding binding = termBinding as DataRowBinding;
                    displayString = binding.DisplayName;
                }
                else if (termBinding is ClassMemberBinding)
                {
                    ClassMemberBinding binding = termBinding as ClassMemberBinding;
                    displayString = binding.ClassBinding.ImplementingType.FullName + "." + binding.MemberName;
                    args          = binding.Arguments;
                }
            }
            else if (term is ArithmeticFunction)
            {
                ArithmeticFunction f = term as ArithmeticFunction;
                args = new ArgumentCollection();
                args.Add(f.LeftArgument);
                args.Add(f.RightArgument);
            }
            else if (term is Assert)
            {
                args = new ArgumentCollection();
                args.Add(((Assert)term).Facts);
            }
            else if (term is Retract)
            {
                args = new ArgumentCollection();
                args.Add(((Retract)term).Facts);
            }
            else if (term is Update)
            {
                args = new ArgumentCollection();
                args.Add(((Update)term).Facts);
            }
            else if (term is Halt)
            {
                args = new ArgumentCollection();
                args.Add(((Halt)term).ClearAgenda);
            }

            ArrayList argsToDisplay = new ArrayList();

            if (args != null)
            {
                foreach (Term t in args)
                {
                    argsToDisplay.Add(WriteTerm(t));
                }
            }

            string format = "";

            if (term.VocabularyLink != null)
            {
                VocabularyDefinition vd = vdefs[term.VocabularyLink.DefinitionId] as VocabularyDefinition;
                format = vd.GetFormatString().Format;

                // Added to fix halt documentation CD 20140328
                if (format == "halt choices")
                {
                    format = "{0}";
                    if (displayString == "True")
                    {
                        argsToDisplay.Add("clear all rules firings");
                    }
                    else
                    {
                        argsToDisplay.Add("do not clear");
                    }
                }
            }
            else
            {
                format = displayString;
            }

            displayString = TryStringFormat(format, argsToDisplay.ToArray());

            return("<span class='TableData'>" + displayString + "</span>");
        }
Example #17
0
        /// <summary>
        /// Create the class object (and sets the value of the binding).
        /// </summary>
        /// <param name="installer">Context within which the class is to be created.</param>
        /// <returns>Returns true if successful, otherwise false.</returns>
        protected internal override bool CreateGlobalObject(IDefinitionInstallerContext installer)
        {
            if (installer == null)
            {
                throw new ArgumentNullException();
            }
            // 1. Get the binding to the global
            Symbol       name    = installer.Runtime.GetSymbol(this.Name.Value);
            ClassBinding binding = installer.GetLocalClassBinding(name);

            // 2. Check consistency that we didn't mess up in the implementation.
            if (binding == null)
            {
                throw new InvalidOperationException("Should have found a binding, because CreateGlobalBinding() created it!");
            }
            if (binding.Value != null)
            {
                throw new InvalidOperationException("Should be an empty binding, because CreateGlobalBinding() complained if one already existed!");
            }

            // 3. Prepare stuff ....
            SmalltalkClass.InstanceStateEnum instanceState = this.InstanceState.Value;
            ClassBinding superclass;

            if (this.SuperclassName.Value.Length == 0)
            {
                superclass = null; // Object has no superclass
            }
            else
            {
                superclass = installer.GetClassBinding(this.SuperclassName.Value);
                if (superclass == null)
                {
                    return(installer.ReportError(this.SuperclassName, InstallerErrors.ClassInvalidSuperclass));
                }
            }

            // Create the collection of class, class-instance, instance variables and imported pools
            BindingDictionary <InstanceVariableBinding>      instVars      = new BindingDictionary <InstanceVariableBinding>(installer.Runtime);
            DiscreteBindingDictionary <ClassVariableBinding> classVars     = new DiscreteBindingDictionary <ClassVariableBinding>(installer.Runtime, this.ClassVariableNames.Count());
            BindingDictionary <ClassInstanceVariableBinding> classInstVars = new BindingDictionary <ClassInstanceVariableBinding>(installer.Runtime);
            DiscreteBindingDictionary <PoolBinding>          pools         = new DiscreteBindingDictionary <PoolBinding>(installer.Runtime);

            // Validate class variable names ...
            foreach (SourceReference <string> identifier in this.ClassVariableNames)
            {
                Symbol varName = installer.Runtime.GetSymbol(identifier.Value);
                if (!IronSmalltalk.Common.Utilities.ValidateIdentifier(identifier.Value))
                {
                    return(installer.ReportError(identifier, InstallerErrors.ClassClassVariableNotIdentifier));
                }
                if (classVars.Any <ClassVariableBinding>(varBinding => varBinding.Name == varName))
                {
                    return(installer.ReportError(identifier, InstallerErrors.ClassClassVariableNotUnique));
                }
                classVars.Add(new ClassVariableBinding(varName));
            }
            // Validate instance variable names ...
            foreach (SourceReference <string> identifier in this.InstanceVariableNames)
            {
                Symbol varName = installer.Runtime.GetSymbol(identifier.Value);
                if (!IronSmalltalk.Common.Utilities.ValidateIdentifier(identifier.Value))
                {
                    return(installer.ReportError(identifier, InstallerErrors.ClassInstanceVariableNotIdentifier));
                }
                if (((IEnumerable <InstanceVariableBinding>)instVars).Any(varBinding => varBinding.Name == varName))
                {
                    return(installer.ReportError(identifier, InstallerErrors.ClassInstanceVariableNotUnique));
                }
                if (classVars.Any <ClassVariableBinding>(varBinding => varBinding.Name == varName))
                {
                    return(installer.ReportError(identifier, InstallerErrors.ClassInstanceOrClassVariableNotUnique));
                }
                instVars.Add(new InstanceVariableBinding(varName));
            }
            // Validate class instance variable names ...
            foreach (SourceReference <string> identifier in this.ClassInstanceVariableNames)
            {
                Symbol varName = installer.Runtime.GetSymbol(identifier.Value);
                if (!IronSmalltalk.Common.Utilities.ValidateIdentifier(identifier.Value))
                {
                    return(installer.ReportError(identifier, InstallerErrors.ClassClassInstanceVariableNotIdentifier));
                }
                if (classInstVars.Any <ClassInstanceVariableBinding>(varBinding => varBinding.Name == varName))
                {
                    return(installer.ReportError(identifier, InstallerErrors.ClassClassInstanceVariableNotUnique));
                }
                if (classVars.Any <ClassVariableBinding>(varBinding => varBinding.Name == varName))
                {
                    return(installer.ReportError(identifier, InstallerErrors.ClassClassInstanceOrClassVariableNotUnique));
                }
                classInstVars.Add(new ClassInstanceVariableBinding(varName));
            }
            // Validate imported pool names ...
            foreach (SourceReference <string> identifier in this.ImportedPoolNames)
            {
                Symbol varName = installer.Runtime.GetSymbol(identifier.Value);
                if (!IronSmalltalk.Common.Utilities.ValidateIdentifier(identifier.Value))
                {
                    return(installer.ReportError(identifier, InstallerErrors.ClassImportedPoolNotIdentifier));
                }
                if (pools.Any <PoolBinding>(varBinding => varBinding.Name == varName))
                {
                    return(installer.ReportError(identifier, InstallerErrors.ClassImportedPoolNotUnique));
                }
                PoolBinding pool = installer.GetPoolBinding(varName);
                if (pool == null)
                {
                    return(installer.ReportError(identifier, InstallerErrors.ClassImportedPoolNotDefined));
                }
                pools.Add(pool);
            }

            // 4. Finally, create the behavior object
            binding.SetValue(new SmalltalkClass(
                                 installer.Runtime, binding.Name, superclass, instanceState, instVars, classVars, classInstVars, pools));
            return(true);
        }
Example #18
0
        /// <summary>
        /// Validate that the definition of the class object does not break any rules set by the Smalltalk standard.
        /// </summary>
        /// <param name="installer">Context within which the validation is to be performed.</param>
        /// <returns>Returns true if successful, otherwise false.</returns>
        protected internal override bool ValidateObject(IDefinitionInstallerContext installer)
        {
            if (installer == null)
            {
                throw new ArgumentNullException();
            }
            // 1. Get the binding to the global
            Symbol       name    = installer.Runtime.GetSymbol(this.Name.Value);
            ClassBinding binding = installer.GetLocalClassBinding(name);

            // 2. Check consistency that we didn't mess up in the implementation.
            if (binding == null)
            {
                throw new InvalidOperationException("Should have found a binding, because CreateGlobalBinding() created it!");
            }
            if (binding.Value == null)
            {
                throw new InvalidOperationException("Should not be an empty binding, because CreateGlobalObject() just created it!");
            }
            // 3. Get the class object.
            SmalltalkClass cls = binding.Value;
            // 4. Validate that superclass is correct
            List <Symbol> classes = new List <Symbol>();

            classes.Add(cls.Name);
            SmalltalkClass tmp = cls.Superclass;

            while (tmp != null)
            {
                if (classes.IndexOf(tmp.Name) != -1)
                {
                    return(installer.ReportError(this.SuperclassName, String.Format(
                                                     InstallerErrors.ClassCircularReference, this.SuperclassName.Value, this.Name.Value)));
                }
                classes.Add(tmp.Name);
                tmp = tmp.Superclass;
            }

            if (cls.InstanceState != SmalltalkClass.InstanceStateEnum.ByteIndexable)
            {
                tmp = cls;
                while (tmp != null)
                {
                    if (tmp.InstanceState == SmalltalkClass.InstanceStateEnum.ByteIndexable)
                    {
                        return(installer.ReportError(this.InstanceState, InstallerErrors.ClassCannotChangeInstanceState));
                    }
                    tmp = tmp.Superclass;
                }
            }

            foreach (PoolBinding pool in cls.ImportedPoolBindings)
            {
                if (pool.Value == null)
                {
                    SourceReference <string> src = this.ImportedPoolNames.SingleOrDefault(sr => sr.Value == pool.Name.Value);
                    if (src == null)
                    {
                        throw new InvalidOperationException("Should not be null, cause we just added this pool in CreateGlobalObject().");
                    }
                    return(installer.ReportError(src, InstallerErrors.ClassMissingPoolDefinition));
                }
            }

            // NB: We must give some source reference, but since we don't have for the whole class, we use the name.
            installer.RegisterNewClass(cls, this.Name);

            return(true); // OK
        }
Example #19
0
        /// <summary>
        /// Sets values from one class object to another one of a different type. Allows a mapping profile for different class types of same Property or Field data types.
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="anonymousObject"></param>
        /// <param name="anonymouseObjectToBind"></param>
        /// <param name="BindingMap"></param>
        /// <param name="IgnoreCase"></param>
        /// <param name="WhichBinding"></param>
        /// <returns></returns>
        public static TResult ToType <TSource, TResult>(this TSource anonymousObject, TResult anonymouseObjectToBind, ClassBindingMap BindingMap, ClassBinding WhichBinding = ClassBinding.All, bool IgnoreCase = true)
        {
            if (anonymousObject == null)
            {
                throw new ArgumentNullException("TSource object is null");
            }
            if (anonymouseObjectToBind == null)
            {
                throw new ArgumentNullException("TBind object is null");
            }
            if (BindingMap == null)
            {
                throw new ArgumentNullException("Class binding map is null");
            }

            switch (WhichBinding)
            {
            case ClassBinding.Properties:
                anonymouseObjectToBind = CopyProperties(anonymousObject, anonymouseObjectToBind, BindingMap.PropertiesMapping, IgnoreCase).ToTypeCast <TResult>();
                break;

            case ClassBinding.Fields:
                anonymouseObjectToBind = CopyFields(anonymousObject, anonymouseObjectToBind, BindingMap.VariableMapping, IgnoreCase).ToTypeCast <TResult>();
                break;

            case ClassBinding.Both:
ClassBindingBoth:
                anonymouseObjectToBind = CopyProperties(anonymousObject, anonymouseObjectToBind, BindingMap.PropertiesMapping, IgnoreCase).ToTypeCast <TResult>();
                anonymouseObjectToBind = CopyFields(anonymousObject, anonymouseObjectToBind, BindingMap.VariableMapping, IgnoreCase).ToTypeCast <TResult>();
                break;

            case ClassBinding.FieldsToProperties:
                anonymouseObjectToBind = CopyFieldsToProperties(anonymousObject, anonymouseObjectToBind, BindingMap.PropertiesMapping, IgnoreCase).ToTypeCast <TResult>();
                break;

            case ClassBinding.PropertiesToFields:
                anonymouseObjectToBind = CopyPropertiesToFields(anonymousObject, anonymouseObjectToBind, BindingMap.VariableMapping, IgnoreCase).ToTypeCast <TResult>();
                break;

            case ClassBinding.All:
                anonymouseObjectToBind = CopyPropertiesToFields(anonymousObject, anonymouseObjectToBind, BindingMap.PropertiesMapping, IgnoreCase).ToTypeCast <TResult>();
                anonymouseObjectToBind = CopyFieldsToProperties(anonymousObject, anonymouseObjectToBind, BindingMap.VariableMapping, IgnoreCase).ToTypeCast <TResult>();
                goto ClassBindingBoth;
            }

            return(anonymouseObjectToBind);
        }
Example #20
0
        /// <summary>
        /// Sets values from one class object to another one of a different type. Only with the same Class "Properties" or "Fields" names.
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="anonymousObject"></param>
        /// <param name="anonymouseObjectToBind"></param>
        /// <param name="IgnoreCase"></param>
        /// <param name="WhichBinding"></param>
        /// <returns></returns>
        public static TResult ToType <TSource, TResult>(this TSource anonymousObject, TResult anonymouseObjectToBind, bool IgnoreCase = true, ClassBinding WhichBinding = ClassBinding.Both) where TSource : class where TResult : class
        {
            if (anonymousObject == null)
            {
                throw new ArgumentNullException("TSource object is null");
            }
            if (anonymouseObjectToBind == null)
            {
                throw new ArgumentNullException("TResult object is null");
            }

            switch (WhichBinding)
            {
            case ClassBinding.Properties:
                anonymouseObjectToBind = CopyProperties(anonymousObject, anonymouseObjectToBind).ToTypeCast <TResult>();
                break;

            case ClassBinding.Fields:
                anonymouseObjectToBind = CopyFields(anonymousObject, anonymouseObjectToBind).ToTypeCast <TResult>();
                break;

            case ClassBinding.Both:
CopyALL:
                anonymouseObjectToBind = CopyProperties(anonymousObject, anonymouseObjectToBind).ToTypeCast <TResult>();
                anonymouseObjectToBind = CopyFields(anonymousObject, anonymouseObjectToBind).ToTypeCast <TResult>();
                break;

            case ClassBinding.PropertiesToFields:
                anonymouseObjectToBind = CopyPropertiesToFields(anonymousObject, anonymouseObjectToBind).ToTypeCast <TResult>();
                break;

            case ClassBinding.FieldsToProperties:
                anonymouseObjectToBind = CopyFieldsToProperties(anonymousObject, anonymouseObjectToBind).ToTypeCast <TResult>();
                break;

            case ClassBinding.All:
                anonymouseObjectToBind = CopyPropertiesToFields(anonymousObject, anonymouseObjectToBind).ToTypeCast <TResult>();
                anonymouseObjectToBind = CopyFieldsToProperties(anonymousObject, anonymouseObjectToBind).ToTypeCast <TResult>();
                goto CopyALL;

            default:
                anonymouseObjectToBind = CopyProperties(anonymousObject, anonymouseObjectToBind).ToTypeCast <TResult>();
                anonymouseObjectToBind = CopyFields(anonymousObject, anonymouseObjectToBind).ToTypeCast <TResult>();
                break;
            }

            return(anonymouseObjectToBind);
        }
 void IDefinitionInstallerContext.AddClassBinding(ClassBinding binding)
 {
     this.NameScope.Classes.Add(binding);
 }
Example #22
0
        public static void CreateClass(SmalltalkRuntime runtime, SmalltalkNameScope scope, ClassBinding binding, string superclassName,
                                       SmalltalkClass.InstanceStateEnum instanceState, string[] classVarNames, string[] instVarNames, string[] classInstVarNames, string[] importedPools,
                                       Func <SmalltalkClass, Dictionary <Symbol, CompiledMethod> > classMethodDicInitializer, Func <SmalltalkClass, Dictionary <Symbol, CompiledMethod> > instanceMethodDicInitializer)
        {
            if (runtime == null)
            {
                throw new ArgumentNullException("runtime");
            }
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }
            if (binding == null)
            {
                throw new ArgumentNullException("binding");
            }
            if (classMethodDicInitializer == null)
            {
                throw new ArgumentNullException("classMethodDicInitializer");
            }
            if (instanceMethodDicInitializer == null)
            {
                throw new ArgumentNullException("instanceMethodDicInitializer");
            }
            // 3. Prepare stuff ....
            ClassBinding superclass;

            if (String.IsNullOrWhiteSpace(superclassName))
            {
                superclass = null; // Object has no superclass
            }
            else
            {
                superclass = scope.GetClassBinding(superclassName);
                if (superclass == null)
                {
                    throw new InvalidOperationException("Should have found a binding for the superclass");
                }
            }

            // Create the collection of class, class-instance, instance variables and imported pools
            BindingDictionary <InstanceVariableBinding>      instVars      = new BindingDictionary <InstanceVariableBinding>(runtime);
            DiscreteBindingDictionary <ClassVariableBinding> classVars     = new DiscreteBindingDictionary <ClassVariableBinding>(runtime, ((classVarNames == null) ? 0 : classVarNames.Length));
            BindingDictionary <ClassInstanceVariableBinding> classInstVars = new BindingDictionary <ClassInstanceVariableBinding>(runtime);
            DiscreteBindingDictionary <PoolBinding>          pools         = new DiscreteBindingDictionary <PoolBinding>(runtime);

            // Add class variable names ...
            if (classVarNames != null)
            {
                foreach (string identifier in classVarNames)
                {
                    Symbol varName = runtime.GetSymbol(identifier);
                    classVars.Add(new ClassVariableBinding(varName));
                }
            }
            // Add instance variable names ...
            if (instVarNames != null)
            {
                foreach (string identifier in instVarNames)
                {
                    Symbol varName = runtime.GetSymbol(identifier);
                    instVars.Add(new InstanceVariableBinding(varName));
                }
            }
            // Add class instance variable names ...
            if (classInstVarNames != null)
            {
                foreach (string identifier in classInstVarNames)
                {
                    Symbol varName = runtime.GetSymbol(identifier);
                    classInstVars.Add(new ClassInstanceVariableBinding(varName));
                }
            }
            // Add imported pool names ...
            if (importedPools != null)
            {
                foreach (string identifier in importedPools)
                {
                    Symbol      varName = runtime.GetSymbol(identifier);
                    PoolBinding pool    = scope.GetPoolBinding(varName);
                    if (pool == null)
                    {
                        throw new InvalidOperationException(String.Format("Should have found a binding for pool {0}", identifier));
                    }
                    pools.Add(pool);
                }
            }
            // Create method dictionaries
            MethodDictionaryInitializer clsMthInitializer  = new MethodDictionaryInitializer(classMethodDicInitializer);
            MethodDictionaryInitializer instMthInitializer = new MethodDictionaryInitializer(instanceMethodDicInitializer);
            ClassMethodDictionary       classMethods       = new ClassMethodDictionary(runtime, clsMthInitializer.Initialize);
            InstanceMethodDictionary    instanceMethods    = new InstanceMethodDictionary(runtime, instMthInitializer.Initialize);

            // 4. Finally, create the behavior object
            SmalltalkClass cls = new SmalltalkClass(runtime, binding.Name, superclass, instanceState, instVars, classVars, classInstVars, pools, instanceMethods, classMethods);

            clsMthInitializer.Class  = cls;
            instMthInitializer.Class = cls;
            binding.SetValue(cls);
        }
Example #23
0
 /// <summary>
 /// Internal! This is used by the Installer to create new classes.
 /// </summary>
 /// <param name="runtime">Smalltalk runtime this class is part of.</param>
 /// <param name="name">Name of the class.</param>
 /// <param name="superclass">Optional binding to the class' superclass.</param>
 /// <param name="instanceState">State of the class' instances (named, object-indexable, byte-indexable).</param>
 /// <param name="instanceVariables">Instance variables bindings. Those are initially not initialized.</param>
 /// <param name="classVariables">Class variable binding.</param>
 /// <param name="classInstanceVariables">Class-instance variables bindings. Those are initially not initialized.</param>
 /// <param name="importedPools">Collection of pools that are imported by the class.</param>
 public SmalltalkClass(SmalltalkRuntime runtime, Symbol name, ClassBinding superclass, InstanceStateEnum instanceState,
                       BindingDictionary <InstanceVariableBinding> instanceVariables, DiscreteBindingDictionary <ClassVariableBinding> classVariables,
                       BindingDictionary <ClassInstanceVariableBinding> classInstanceVariables, DiscreteBindingDictionary <PoolBinding> importedPools)
     : this(runtime, name, superclass, instanceState, instanceVariables, classVariables, classInstanceVariables, importedPools, null, null)
 {
 }
Example #24
0
 void ISmalltalkNameScopeVisitor.Visit(ClassBinding binding)
 {
     this.Generators.Add(new ClassGenerator(this.Compiler, binding));
 }
Example #25
0
 void IInstallerContext.AddClassBinding(ClassBinding binding)
 {
     this.NameScope.Classes.Add(binding);
 }
        // Method to create the rule-set or policy
        public void CreateRuleSet()
        {
            //Creating XML document bindings on the Medical claims XSD schema

            //Document Binding that binds to the schema name and specifies the selector
            XMLDocumentBinding xmlClaim = new XMLDocumentBinding("MedicalClaims", "/*[local-name()='Root' and namespace-uri()='http://BizTalk_Server_Project1.MedicalClaims']");

            //DocumentField Bindings that bind to the fields in the schema that need to be used in rule defintion

            XMLDocumentFieldBinding xmlClaim_Name   = new XMLDocumentFieldBinding(Type.GetType("System.String"), "/*[local-name()='Root' and namespace-uri()='http://BizTalk_Server_Project1.MedicalClaims']/*[local-name()='Name']", xmlClaim);
            XMLDocumentFieldBinding xmlClaim_ID     = new XMLDocumentFieldBinding(Type.GetType("System.String"), "/*[local-name()='Root' and namespace-uri()='http://BizTalk_Server_Project1.MedicalClaims']/*[local-name()='ID']", xmlClaim);
            XMLDocumentFieldBinding xmlClaim_Amount = new XMLDocumentFieldBinding(Type.GetType("System.Double"), "/*[local-name()='Root' and namespace-uri()='http://BizTalk_Server_Project1.MedicalClaims']/*[local-name()='Amount']", xmlClaim);
            XMLDocumentFieldBinding xmlClaim_Nights = new XMLDocumentFieldBinding(Type.GetType("System.Int32"), "/*[local-name()='Root' and namespace-uri()='http://BizTalk_Server_Project1.MedicalClaims']/*[local-name()='Nights']", xmlClaim);
            XMLDocumentFieldBinding xmlClaim_Date   = new XMLDocumentFieldBinding(Type.GetType("System.DateTime"), "/*[local-name()='Root' and namespace-uri()='http://BizTalk_Server_Project1.MedicalClaims']/*[local-name()='Date']", xmlClaim);

            //Creating DB bindings on the NorthWind DB -> PolicyValidity table

            // DataRow Binding to bind to the Data Table, and provide the Data Set name (defaulting here to the DB name)

            DataConnectionBinding policyvalidityTable = new DataConnectionBinding("PolicyValidity", "Northwind");

            // Column bindings to bind to the columns in the Data Table that need to be used in rule definition

            DatabaseColumnBinding policyvalidityTable_IDColumn           = new DatabaseColumnBinding(Type.GetType("System.String"), "ID", policyvalidityTable);
            DatabaseColumnBinding policyvalidityTable_PolicyStatusColumn = new DatabaseColumnBinding(Type.GetType("System.String"), "PolicyStatus", policyvalidityTable);

            //Creating .NET class (property and member) bindings

            // Class Bindings to bind to the class defintions whose properties and members will be used in rule definition

            ClassBinding dateClass    = new ClassBinding(typeof(TimeStamp));
            ClassBinding resultsClass = new ClassBinding(new Microsoft.Samples.BizTalk.MedicalClaimsProcessingandTestingPolicies.Claims.ClaimResults().GetType());


            // Member Bindings to bind to the properties and members in the TimeStamp class that need to be used in rule definition

            ClassMemberBinding today = new ClassMemberBinding("Value", dateClass);

            // Member bindings for ClaimResults.Status and ClaimResults.Reason properties

            ClassMemberBinding reason = new ClassMemberBinding("Reason", resultsClass);
            ClassMemberBinding status = new ClassMemberBinding("Status", resultsClass);


            // Member bindings for ClaimResults.Status and ClaimResults.Reason properties with different arguments

            // Creation of constant strings that are required as arguments for rule actions

            Constant           c1  = new Constant(" REJECTED!");
            ArgumentCollection al1 = new ArgumentCollection();

            al1.Add(c1);

            Constant           c2  = new Constant("Amount of claim has exceeded Policy limit");
            ArgumentCollection al2 = new ArgumentCollection();

            al2.Add(c2);

            Constant           c3  = new Constant(" Claim Accepted!");
            ArgumentCollection al3 = new ArgumentCollection();

            al3.Add(c3);

            Constant           c4  = new Constant(" Amount of Nights has exceeded Policy limit");
            ArgumentCollection al4 = new ArgumentCollection();

            al4.Add(c4);

            Constant           c5  = new Constant(" Cannot submit claims for future dates!");
            ArgumentCollection al5 = new ArgumentCollection();

            al5.Add(c5);

            Constant           c6  = new Constant("Policy ID is invalid");
            ArgumentCollection al6 = new ArgumentCollection();

            al6.Add(c6);

            ClassMemberBinding status_Rejected      = new ClassMemberBinding("Status", resultsClass, al1);
            ClassMemberBinding reason_invalidAmount = new ClassMemberBinding("Reason", resultsClass, al2);
            ClassMemberBinding status_Accepted      = new ClassMemberBinding("Status", resultsClass, al3);
            ClassMemberBinding reason_invalidNights = new ClassMemberBinding("Reason", resultsClass, al4);
            ClassMemberBinding reason_invalidDate   = new ClassMemberBinding("Reason", resultsClass, al5);
            ClassMemberBinding reason_invalidID     = new ClassMemberBinding("Reason", resultsClass, al6);


            // MemberBinding for the SendLead method in the ClaimResults class with the name and ID from the incoming XML document as arguments

            Term arg1 = new UserFunction(xmlClaim_Name);
            Term arg2 = new UserFunction(xmlClaim_ID);
            ArgumentCollection args1 = new ArgumentCollection();

            args1.Add(arg1);
            args1.Add(arg2);
            ClassMemberBinding sendLead = new ClassMemberBinding("SendLead", resultsClass, args1);

            // Object reference binding to the ClaimResults object that is to be asserted back in to the initial fact base as part of the rule actions

            ObjectReference resultsObject = new ObjectReference(resultsClass);


            // Wrapping the XML bindings as User Functions

            UserFunction uf_xmlName   = new UserFunction(xmlClaim_Name);
            UserFunction uf_xmlID     = new UserFunction(xmlClaim_ID);
            UserFunction uf_xmlAmount = new UserFunction(xmlClaim_Amount);
            UserFunction uf_xmlNights = new UserFunction(xmlClaim_Nights);
            UserFunction uf_xmlDate   = new UserFunction(xmlClaim_Date);

            // Wrapping the DB bindings as User Functions

            UserFunction uf_IDColumn           = new UserFunction(policyvalidityTable_IDColumn);
            UserFunction uf_PolicyStatusColumn = new UserFunction(policyvalidityTable_PolicyStatusColumn);


            // Wrapping the .NET bindings as User Functions

            UserFunction uf_today         = new UserFunction(today);
            UserFunction uf_reason        = new UserFunction(reason);
            UserFunction uf_status        = new UserFunction(status);
            UserFunction uf_rejected      = new UserFunction(status_Rejected);
            UserFunction uf_invalidAmount = new UserFunction(reason_invalidAmount);
            UserFunction uf_accepted      = new UserFunction(status_Accepted);
            UserFunction uf_invalidNights = new UserFunction(reason_invalidNights);
            UserFunction uf_invalidDate   = new UserFunction(reason_invalidDate);
            UserFunction uf_invalidID     = new UserFunction(reason_invalidID);
            UserFunction uf_sendLead      = new UserFunction(sendLead);


            // Rule 1: Amount Check (check to see if claim amount has exceeded the allowable limit)

            // Condition 1: IF the Amount in the XML document element is > 1000 AND IF the Claims.ClaimResults object has not been modified i.e if STATUS = null

            GreaterThan ge1 = new GreaterThan(uf_xmlAmount, new Constant(1000));
            Equal       eq1 = new Equal(uf_status, new Constant(uf_status.Type, null as string));

            LogicalExpressionCollection conditionAnd1 = new LogicalExpressionCollection();

            conditionAnd1.Add(ge1);
            conditionAnd1.Add(eq1);

            LogicalAnd la1 = new LogicalAnd(conditionAnd1);

            //Action 1 - THEN Claims.ClaimResults.Status = "REJECTED" and Claims.ClaimResults.Reason = "Amount of claim has exceeded limit" && Assert this object back into working memory

            ActionCollection actionList1 = new ActionCollection();

            actionList1.Add(uf_rejected);
            actionList1.Add(uf_invalidAmount);
            actionList1.Add(new Assert(resultsObject));

            // Amount Check Rule defintion
            Microsoft.RuleEngine.Rule r1 = new Microsoft.RuleEngine.Rule("Amount Check", la1, actionList1);

            // Rule 2: Nights Spent (check to see if no of nights has exceeded the allowable limit)

            // Condition 2: IF the number of nights in the XML document element is > 10 AND IF the Claims.ClaimResults object has not been modified i.e if STATUS = null

            GreaterThan ge2 = new GreaterThan(uf_xmlNights, new Constant(10));

            Equal eq2 = new Equal(uf_status, new Constant(uf_status.Type, null as string));

            LogicalExpressionCollection conditionAnd2 = new LogicalExpressionCollection();

            conditionAnd2.Add(ge2);
            conditionAnd2.Add(eq2);

            LogicalAnd la2 = new LogicalAnd(conditionAnd2);

            //Action 2 - THEN Claims.ClaimResults.Status = "REJECTED" and Claims.ClaimResults.Reason = "No of Nights has exceeded limit" && Assert this object back into working memory

            ActionCollection actionList2 = new ActionCollection();

            actionList2.Add(uf_rejected);
            actionList2.Add(uf_invalidNights);
            actionList2.Add(new Assert(resultsObject));

            //Nights Spent Rule Definition
            Microsoft.RuleEngine.Rule r2 = new Microsoft.RuleEngine.Rule("Nights Spent", la2, actionList2);

            // Rule 3: Date Validity (check to see if the date on the claim is greater than today's date)

            // Condition 3: IF date on the incoming XML claim is greater than Today than reject the claim AND IF the Claims.ClaimResults object has not been modified i.e if RESULT = null

            GreaterThan ge3 = new GreaterThan(uf_xmlDate, uf_today);

            Equal eq3 = new Equal(uf_status, new Constant(uf_status.Type, null as string));

            LogicalExpressionCollection conditionAnd3 = new LogicalExpressionCollection();

            conditionAnd3.Add(ge3);
            conditionAnd3.Add(eq3);

            LogicalAnd la3 = new LogicalAnd(conditionAnd3);

            //Action 3 - THEN Claims.ClaimResults.Status = "REJECTED" and Claims.ClaimResults.Reason = "Cannot submit claims in the future!" && Assert this object back into working memory

            ActionCollection actionList3 = new ActionCollection();

            actionList3.Add(uf_rejected);
            actionList3.Add(uf_invalidDate);
            actionList3.Add(new Assert(resultsObject));

            // Date Validity Rule defintion

            Microsoft.RuleEngine.Rule r3 = new Microsoft.RuleEngine.Rule("Date Validity Check", la3, actionList3);

            // Rule 4: Policy Validity (check to see if the policy ID is valid by inspecting the database)

            // Condition 4: IF the Policy is Invalid for the ID in the XML claim (where the validity record is stored in the DB) AND IF the Claims.ClaimResults object has not been modified i.e if RESULT = null

            Equal    ceq1           = new Equal(uf_IDColumn, uf_xmlID);
            Constant invalid_string = new Constant("INVALID");
            Equal    ceq2           = new Equal(uf_PolicyStatusColumn, invalid_string);

            LogicalExpressionCollection andList1 = new LogicalExpressionCollection();

            andList1.Add(ceq1);
            andList1.Add(ceq2);
            LogicalAnd cla1 = new LogicalAnd(andList1);

            Equal eq4 = new Equal(uf_status, new Constant(uf_status.Type, null as string));

            LogicalExpressionCollection conditionAnd4 = new LogicalExpressionCollection();

            conditionAnd4.Add(cla1);
            conditionAnd4.Add(eq4);

            LogicalAnd la4 = new LogicalAnd(conditionAnd4);


            //Action 4 - THEN Claims.ClaimResults.Status = "REJECTED" and Claims.ClaimResults.Reason = "Policy Invalid" && Assert this object back into working memory

            ActionCollection actionList4 = new ActionCollection();

            actionList4.Add(uf_rejected);
            actionList4.Add(uf_invalidID);
            actionList4.Add(new Assert(resultsObject));

            // Policy Validity Rule defintion

            Microsoft.RuleEngine.Rule r4 = new Microsoft.RuleEngine.Rule("Policy Validity Check", la4, actionList4);

            // Rule 5: (Send a Lead To Policy Department (by executing the SendLead Method) if the user's policy has expired and is invalid)

            // Condition 5: IF Claim.ClaimResults.Reason = "Policy invalid"

            Constant Reason_String = new Constant("Policy ID is invalid");
            Equal    eq5           = new Equal(uf_reason, Reason_String);

            //Action 5 - THEN Send a Lead to the Policy Department by invoking the function Claim.ClaimResults.SendLead wirh customer ID and Name

            ActionCollection actionList5 = new ActionCollection();

            actionList5.Add(uf_sendLead);

            Microsoft.RuleEngine.Rule r5 = new Microsoft.RuleEngine.Rule("Send Lead", eq5, actionList5);

            // Rule 6:  Set the Claim Status to be Valid if it the Status has not been set to Invalid

            // Condition 6: IF Claim.ClaimResults.Status = null

            Equal eq6 = new Equal(uf_status, new Constant(uf_status.Type, null as string));

            //Action 6 - THEN Send a Set the Claim status to be Valid

            ActionCollection actionList6 = new ActionCollection();

            actionList6.Add(uf_accepted);

            //Claim Accepted Rule definition

            Microsoft.RuleEngine.Rule r6 = new Microsoft.RuleEngine.Rule("Claim Accepted", eq6, actionList6);

            // Since initially the condition is TRUE (the claim has not been rejected or accepted),
            // we need to make this rule a lower priority so that the rejection rules run first.
            // That way, if the claim is rejected, this rule will not execute.
            r6.Priority = -1;

            // Creation of the rule-set (policy) and saving it into the file rulestore

            // Creating configuration information (date, version, description, creator, policy name, and fact retriever used to retrieve the required datasets at runtime)

            DateTime    time  = new DateTime(System.DateTime.Now.Year, System.DateTime.Now.Month, System.DateTime.Now.Day);
            VersionInfo vinf1 = new VersionInfo("Rules to Process medical Insurance Claims", time, "BizRules", 0, 0);
            RuleSet     rs1   = new RuleSet("MedicalInsurancePolicy", vinf1);
            RuleSetExecutionConfiguration    rec1  = new RuleSetExecutionConfiguration();
            RuleEngineComponentConfiguration recc1 = new RuleEngineComponentConfiguration("FactRetrieverForClaimsProcessing", "Microsoft.Samples.BizTalk.MedicalClaimsProcessingandTestingPolicies.FactRetrieverForClaimsProcessing.DbFactRetriever");

            rec1.FactRetriever         = recc1;
            rs1.ExecutionConfiguration = rec1;

            // Adding rules to the rule-set

            rs1.Rules.Add(r1);
            rs1.Rules.Add(r2);
            rs1.Rules.Add(r3);
            rs1.Rules.Add(r4);
            rs1.Rules.Add(r5);
            rs1.Rules.Add(r6);

            // Saving the rule-set (policy) to an XML file in the current directory

            FileRuleStore frs1 = new FileRuleStore("MedicalInsurancePolicy.xml");

            frs1.Add(rs1);
        }
 public RuntimeGlobalInitializer(InitializerNode parseTree, IDebugInfoService debugInfoService, ClassBinding binding)
     : base(InitializerType.ClassInitializer, binding, parseTree, debugInfoService)
 {
 }