Example #1
0
        public void StartSession_ShouldCreateNewSessionSuccessfully()
        {
            // get list of sessions
            var sessions = _sessionManager.GetFieldValue <List <ISession> >("_sessions");

            // create fake session
            var fakeSession = A.Fake <ISession>();

            A.CallTo(() => fakeSession.AccountId).Returns(2);

            // add fake session
            sessions.Add(fakeSession);

            var accountManager = A.Fake <IAccountManager>();

            A.CallTo(() => _accountManagerProvider.GetManagerForAccount(1)).Returns(accountManager);

            var session = A.Fake <ISession>();

            A.CallTo(() => session.Id).Returns(Guid.NewGuid());
            A.CallTo(() => _sessionFactory.CreateSession(1, accountManager)).Returns(session);

            // create action to start session
            var sessionId = _sessionManager.StartSession(1);

            // ensure accout manager was created for account
            A.CallTo(() => _accountManagerProvider.GetManagerForAccount(1)).MustHaveHappened();

            // ensure session was created with account manager
            A.CallTo(() => _sessionFactory.CreateSession(1, accountManager)).MustHaveHappened();

            sessionId.Should().Be(session.Id);
            sessions.Should().Contain(new[] { session });
            sessions.Should().HaveCount(2);
        }
 public UnaryServerMethod <TRequest, TResponse> GetUnaryHandler()
 {
     return(async(request, context) =>
     {
         var connection = _sessionFactory.CreateSession(context.Method, MethodType.Unary);
         return await connection.Execute(request, context);
     });
 }
Example #3
0
        public void Handle(CreateBugCommand cmd)
        {
            cmd.Bug.Events.Add(new BugCreatedEvent(cmd.Bug, cmd.CreatedBy, DateTime.Now));

            // TODO: store in repo.

            var session = ruleFactory.CreateSession();

            session.Insert(cmd.Bug);
            session.Fire();
        }
        public void Test1()
        {
            var session = _factory.CreateSession();

            _engine.load(session, 1000);

            _watch = Stopwatch.StartNew();
            Console.WriteLine($"Firing rules at {DateTime.Now}");
            var result = session.Fire();

            _watch.Stop();
            Console.WriteLine($"Rules completed in {_watch.ElapsedMilliseconds} milliseconds");
            Assert.Pass();
        }
Example #5
0
        public ISession CreateSession(Guid Id, string userName)
        {
            bool writerGranted = false;

            try
            {
                writerGranted = _sessionDictionaryLock.TryEnterWriteLock(_lockAcquireTimout);

                if (writerGranted)
                {
                    var session = _sessionFactory.CreateSession(Id, userName);
                    _sessionDictionary[session.Id] = session;

                    return(session);
                }
                else
                {
                    //To do, we should throw an error here after we implement exception handling
                    return(null);
                }
            }
            finally
            {
                if (writerGranted)
                {
                    _sessionDictionaryLock.ExitWriteLock();
                }
            }
        }
Example #6
0
 public static ISession CreateSession(
     this ISessionFactory factory,
     RepoInfo repoInfo,
     string appName = null)
 {
     return(factory.CreateSession(repoInfo.AsSessionParameter(appName)));
 }
Example #7
0
        private static void Main(string[] args)
        {
            var repository = new CustomRuleRepository();

            repository.LoadRules();

            Console.WriteLine("Loaded rules:");
            foreach (var rule in repository.GetRules())
            {
                Console.WriteLine(rule.Name);
            }
            Console.WriteLine();

            ISessionFactory factory = repository.Compile();
            ISession        session = factory.CreateSession();

            var customer1 = new Customer("John Do");
            var customer2 = new Customer("Jean Do")
            {
                IsPreferred = true
            };

            session.Insert(customer1);
            session.Insert(customer2);
            session.Insert(new Order(1, customer1, 2, 90.00));
            session.Insert(new Order(2, customer1, 1, 110.00));
            session.Insert(new Order(3, customer1, 1, 1000.00));
            session.Insert(new Order(4, customer2, 1, 120.00));
            session.Insert(new Order(5, customer2, 1, 10.00));
            session.Insert(new Order(6, customer2, 1, 12.50));
            session.Insert(new Order(7, customer2, 1, 400.00));

            Console.WriteLine("Running rules:");
            session.Fire();
        }
Example #8
0
        public void Setup()
        {
            mail           = Substitute.For <IMailService>();
            session        = factory.CreateSession();
            createBug      = container.GetInstance <IHandle <CreateBugCommand> >();
            changeEstimate = container.GetInstance <IHandle <ChangeEstimateCommand> >();

            dev = new User {
                Email = "dev@company"
            };
            manager = new User {
                Email = "manager@company"
            };
            bug = new Bug
            {
                Resources =
                {
                    new Resource {
                        User = dev, Type = ResourceType.Developer
                    },
                    new Resource {
                        User = manager, Type = ResourceType.Manager
                    },
                    new Resource {
                        User = manager, Type = ResourceType.Creator
                    },
                }
            };
        }
Example #9
0
        static void Main(string[] args)
        {
            //Create Repository
            var repository = new CustomRuleRepository();

            //Load rules
            repository.LoadRules();
            //Compile rules
            ISessionFactory factory = repository.Compile();
            //Create session for rule
            ISession session = factory.CreateSession();

            var customer = new Customer("John Do");
            var product1 = new Product("Pencil", 0, 1);
            var product2 = new Product("Pen", 5, 1);

            session.Insert(customer);
            session.Insert(product1);
            session.Insert(product2);
            session.Insert(new Order(customer)
            {
                Details = new List <Product> {
                    product1, product2
                }
            });

            session.Fire();

            Console.ReadKey();
        }
        /// <summary>
        /// Load and execute engine rules
        /// </summary>
        public void EngineRulesExecution(OSUSR_UUK_BAGMSGS bag, OSUSR_UUK_BAGINTEG bagIntegraty, OSUSR_UUK_FLT_INFO flightInfoI, OSUSR_UUK_FLT_INFO flightInfoF, String hub, ISessionFactory factory)
        {
            BagTMLog.LogDebug("BagTM Engine Rules Execution Start", this);

            ISession session = factory.CreateSession();

            try
            {
                bagIntegraty.IATD = (flightInfoI != null && flightInfoI.ATD != null) ? flightInfoI.ATD :
                                    (flightInfoI != null && flightInfoI.ETD != null) ? flightInfoI.ETD :
                                    (flightInfoI != null && flightInfoI.STD != null) ? flightInfoI.STD : null;
                bagIntegraty.FATD = (flightInfoF != null && flightInfoF.ATD != null) ? flightInfoF.ATD :
                                    (flightInfoF != null && flightInfoF.ETD != null) ? flightInfoF.ETD :
                                    (flightInfoF != null && flightInfoF.STD != null) ? flightInfoF.STD : null;

                session.Insert(hub);

                //Insert facts into rules engine's memory
                session.Insert(bag);
                session.Insert(bagIntegraty);

                //Start match/resolve/act cycle
                session.Fire();
            }
            catch (Exception e)
            {
                BagTMLog.LogError("BagTM Engine Error Processing Rules", this, e);

                throw e;
            }

            BagTMLog.LogDebug("BagTM Engine Rules Execution Ending", this);
        }
Example #11
0
 public static ISession CreateSession(
     this ISessionFactory factory,
     RepoInfo repoInfo,
     IObjectFactory objectFactory = null,
     IAuthenticationProvider authenticationProvider = null,
     ICache cache   = null,
     string appName = null)
 {
     return(factory.CreateSession(repoInfo.AsSessionParameter(appName), objectFactory, authenticationProvider, cache));
 }
Example #12
0
        public ISession CreateSession(Action <ISession> initializationAction)
        {
            ExecuterRepository repository = _executerRepository as ExecuterRepository;

            repository.LoadAssemblys();
            ISessionFactory factory = repository.Compile();
            ISession        session = factory.CreateSession();

            initializationAction?.Invoke(session);
            return(session);
        }
 public void InitializeWebDriver()
 {
     if (reuseSession)
     {
         if (singletonSessionInstance == null)
         {
             singletonSessionInstance = sessionFactory.CreateSession(scenarioContext.ScenarioInfo.Title);
         }
         else
         {
             singletonSessionInstance.Reset(scenarioContext.ScenarioInfo.Title);
         }
         objectContainer.RegisterInstanceAs <ISession>(singletonSessionInstance);
     }
     else
     {
         sessionInstance = sessionFactory.CreateSession(scenarioContext.ScenarioInfo.Title);
         objectContainer.RegisterInstanceAs <ISession>(sessionInstance);
     }
 }
        //----------------------------------------------------------------//

        public async Task LoadMovieWithEntities(int movieId, IDbConnection connection)
        {
            using (ISession session = _sessionFactory.CreateSession(connection))
            {
                FeedManager feedManager = new FeedManager(session, _serviceProvider);
                await feedManager.FeedMovieWithSubEntities(movieId);

                Logger.Log.Info($"Entities for movie with id {movieId} was loaded");
                session.SaveChanges();
            }
        }
        public void Execute(AddressValueObject address)
        {
            RuleRepository repository = new RuleRepository();

            repository.Load(x => x.From(typeof(AddressRule).Assembly));
            ISessionFactory factory = repository.Compile();
            ISession        session = factory.CreateSession();

            session.Insert(address);
            session.Fire();
        }
Example #16
0
        public ISession InjectToProcess(int processId, DimInstanceContext instanceContext)
        {
            logger.Info("Injecting to process " + processId);

            var session = sessionFactory.CreateSession(processId, instanceContext);

            processInjectionService.InjectToProcess(processId, injectedModuleServiceConfiguration.GetInjectedDllPath());
            sessionsByProcessId.AddOrUpdate(processId, session, (a, b) => session);
            session.Ended += HandleSessionEnded;
            return(session);
        }
Example #17
0
        public void Execute(CustomerEntity customer)
        {
            RuleRepository repository = new RuleRepository();

            repository.Load(x => x.From(typeof(CustomerRule).Assembly));
            ISessionFactory factory = repository.Compile();
            ISession        session = factory.CreateSession();

            session.Insert(customer);
            session.Fire();
        }
Example #18
0
        private static void Main(string[] args)
        {
            var dwelling = new Dwelling {
                Address = "1 Main Street, New York, NY", Type = DwellingTypes.SingleHouse
            };
            var dwelling2 = new Dwelling {
                Address = "2 Main Street, New York, NY", Type = DwellingTypes.SingleHouse
            };
            var policy1 = new Policy {
                Name = "Silver", PolicyType = PolicyTypes.Home, Price = 1200, Dwelling = dwelling
            };
            var policy2 = new Policy {
                Name = "Gold", PolicyType = PolicyTypes.Home, Price = 2300, Dwelling = dwelling2
            };
            var customer1 = new Customer {
                Name = "John Do", Age = 22, Sex = SexTypes.Male, Policy = policy1
            };
            var customer2 = new Customer {
                Name = "Emily Brown", Age = 32, Sex = SexTypes.Female, Policy = policy2
            };

            var repository = new RuleRepository();

            repository.Load("Test", x => x.From(typeof(Program).Assembly));
            var ruleSets = repository.GetRuleSets();

            IRuleCompiler   compiler = new RuleCompiler();
            ISessionFactory factory  = compiler.Compile(ruleSets);
            ISession        session  = factory.CreateSession();

            session.Insert(policy1);
            session.Insert(policy2);
            session.Insert(customer1);
            session.Insert(customer2);
            session.Insert(dwelling);
            session.Insert(dwelling2);

            customer1.Age = 10;
            session.Update(customer1);

            session.Retract(customer2);

            session.Fire();

            session.Insert(customer2);

            session.Fire();

            customer1.Age = 30;
            session.Update(customer1);

            session.Fire();
        }
Example #19
0
        private void setupRuleEngine()
        {
            var ruleRepo = new RuleRepository();

            ruleRepo.Load(x => x.From(typeof(PeriodicRuleEngine).Assembly));
            // rules are (should be ?) in the same assembly as PeriodicRuleEngine

            ISessionFactory factory = ruleRepo.Compile();

            engineSession = factory.CreateSession();
            engineSession.DependencyResolver =
                new AspNetCoreDepResolver(serviceProvider);
        }
Example #20
0
        static void Main(string[] args)
        {
            //Load the rules
            var repository = new DomainRuleRepository();

            repository.LoadRules();
            Console.WriteLine("Loaded rules:");
            Console.WriteLine("=============");
            foreach (var rule in repository.GetRules())
            {
                Console.WriteLine(rule.Name);
            }
            Console.WriteLine();

            ISessionFactory factory = repository.Compile();
            //Create a working session
            ISession session = factory.CreateSession();

            //Load model
            var passenger1 = new Passenger("Rajkumar", Gender.Male, 39)
            {
                IsSeniorCitizen = true
            };
            var passenger2 = new Passenger("Selvakumar", Gender.Male, 61);
            var passenger3 = new Passenger("Nancy", Gender.Female, 62);
            var passenger4 = new Passenger("Jenifer", Gender.Female, 4);

            // To insert the fact into rule engine memory
            session.Insert(passenger1);
            session.Insert(passenger2);
            session.Insert(passenger3);
            session.Insert(passenger4);

            //Start rule validation
            Console.WriteLine("Running rules:");
            session.Fire();
            var errorList = session.Query <string>().ToList();

            if (errorList.Count > 0)
            {
                Console.WriteLine("=============");
            }

            foreach (var item in errorList)
            {
                Console.WriteLine(item);
            }

            Console.Read();//To show the validation message in console
        }
        public IExecuterSession CreateSession(IExecuterRepository executerRepository, Action <IExecuterSession> initializationAction)
        {
            var repository = executerRepository as ExecuterRepository;

            repository.LoadAssemblys();
            ISessionFactory factory = repository.Compile();
            var             session = new NulesExecuterSession(factory.CreateSession());

            if (initializationAction != null)
            {
                initializationAction(session);
            }
            return(session);
        }
Example #22
0
        private static void Main(string[] args)
        {
            var repository = new RuleRepository();

            repository.Load(x => x.From(Assembly.GetExecutingAssembly()));

            ISessionFactory factory = repository.Compile();
            ISession        session = factory.CreateSession();

            session.Insert(new Fact1 {
                TestProperty = "Valid Value"
            });

            VisualizerHost.Visualize(session);
        }
Example #23
0
        static void Main(string[] args)
        {
            var repository = new CustomRuleRepository();

            repository.LoadRules();
            ISessionFactory factory = repository.Compile();

            ISession session  = factory.CreateSession();
            var      customer = new Customer("John Do");

            session.Insert(customer);
            session.Insert(new Order(customer, 90.00m));
            session.Insert(new Order(customer, 110.00m));

            session.Fire();
        }
Example #24
0
        public void SetUp()
        {
            _notifiers = new Dictionary <Type, Mock <INotifier> >();
            _rules     = new List <BaseRule>();
            SetUpRules();

            var repository = new RuleRepository {
                Activator = new InstanceActivator(_rules)
            };

            repository.Load("Test", x => x.From(_rules.Select(r => r.GetType()).ToArray()));

            ISessionFactory factory = repository.Compile();

            Session = factory.CreateSession();
        }
Example #25
0
        protected BaseRuleTestFixture()
        {
            _firedRulesMap = new Dictionary <string, List <AgendaEventArgs> >();
            _ruleMap       = new Dictionary <Type, IRuleMetadata>();

            Repository = new RuleRepository {
                Activator = new InstanceActivator()
            };

            SetUpRules();

            ISessionFactory factory = Compile();

            Session = factory.CreateSession();
            Session.Events.RuleFiredEvent += (sender, args) => _firedRulesMap[args.Rule.Name].Add(args);
        }
Example #26
0
        public void InjectToProcessCreatesSessionAndDelegatesToProcess()
        {
            const int    processId     = 193;
            const string dllPath       = "H:/erp/Derp";
            var          configuration = CreateMock <DimInstanceContext>();
            var          session       = CreateMock <ISession>();

            When(sessionFactory.CreateSession(processId, configuration)).ThenReturn(session);
            When(injectedModuleServiceConfiguration.GetInjectedDllPath()).ThenReturn(dllPath);
            When(processInjectionService.InjectToProcess(Eq(processId), Any <string>())).ThenReturn(true);

            testObj.InjectToProcess(processId, configuration);

            Verify(sessionFactory).CreateSession(processId, configuration);
            Verify(injectedModuleServiceConfiguration).GetInjectedDllPath();
            Verify(processInjectionService).InjectToProcess(processId, dllPath);
            ClearInteractions(session, 1); // Event subscription
            VerifyNoMoreInteractions();
        }
Example #27
0
        public IDataEntity ExecuteSession(IDataEntity globalEntity)
        {
            var sessionInstance = _sessionFactory.CreateSession();

            var session = _sessionBuilder.ProcessOPASession(sessionInstance, globalEntity);

            // XDS PRE
            if (ProduceXDS)
            {
                if (!XDSDirectorySetup)
                {
                    XDSFilePath = XDSFolder + session.GetRulebase().GetBaseFileName();
                    Directory.CreateDirectory(XDSFilePath);
                    XDSDirectorySetup = true;
                }

                // Format : XDSFolder\RulebaseName\file.xds
                var xdsFile =
                    XDSFilePath
                    + "\\PRE_"
                    + globalEntity.Children
                    .Where(c => c.EntityName == "Learner")
                    .Select(g => g.Attributes.Single(k => k.Key == LearnRefNumberAttribute).Value.Value.ToString())
                    .SingleOrDefault()
                    + ".xds";

                using (FileWriter fileWriter = new FileWriter(xdsFile))
                {
                    SessionUtils.ExportSession(session, fileWriter);
                }
            }

            session.Think();

            var outputGlobalInstance = session.GetGlobalEntityInstance();
            var outputEntity         = _dataEntityBuilder.CreateOPADataEntity(outputGlobalInstance, null);

            return(outputEntity);
        }
Example #28
0
        static void Main(string[] args)
        {
            //Create Repository
            var repository = new CustomRuleRepository();

            //Load rules
            repository.LoadRules();
            //Compile rules
            ISessionFactory factory = repository.Compile();
            //Create session for rule
            ISession session = factory.CreateSession();

            var customer = new Customer("John Do");

            session.Insert(customer);
            session.Insert(new Order(customer, 90.00m));
            session.Insert(new Order(customer, 110.00m));

            session.Fire();

            Console.ReadKey();
        }
Example #29
0
        public void Add(string url, string clientCert, string clientKey)
        {
            try
            {
                _log.LogInformation("Creating session: {0}", url);
                //connections[key: url] = new OpcUAConnection(url, clientCert, clientKey);
                X509Certificate2      certificate           = new X509Certificate2(Encoding.ASCII.GetBytes(clientCert));
                X509Certificate2      certWithKey           = CertificateFactory.CreateCertificateWithPEMPrivateKey(certificate, Encoding.ASCII.GetBytes(clientKey));
                CertificateIdentifier certificateIdentifier = new CertificateIdentifier(certWithKey);

                var userIdentity = new UserIdentity(certWithKey);


                var appConfig = _applicationConfiguration();
                appConfig.SecurityConfiguration.ApplicationCertificate = certificateIdentifier;
                var session = _sessionFactory.CreateSession(url, "Grafana Session", userIdentity, true, appConfig);
                CreateConnection(url, session);
            }
            catch (Exception ex)
            {
                _log.LogError("Error while adding endpoint {0}: {1}", url, ex);
            }
        }
Example #30
0
        /// <summary>
        /// Starts a session
        /// </summary>
        /// <returns></returns>
        public Guid StartSession(int accountId)
        {
            lock (_sessionLock)
            {
                // check if account already has an open session
                if (_sessions.Any(s => s.AccountId == accountId))
                {
                    throw new ExistingSessionException(accountId);
                }

                // get the account manager
                var accountManager = _accountManagerProvider.GetManagerForAccount(accountId);

                // create session
                var session = _sessionFactory.CreateSession(accountId, accountManager);

                // add the new session
                _sessions.Add(session);

                // return the id of the new session
                return(session.Id);
            }
        }