/// <summary>
        /// Processes the supplied <see cref="Rule"/> object and produces the <see cref="MyGeotabAPIAdapter.Database.Models.DbRule"/> and <see cref="DbCondition"/> objects contained within it.
        /// </summary>
        /// <param name="rule">A <see cref="Rule"/> object</param>
        /// <param name="entityStatus">The <see cref="Database.Common.DatabaseRecordStatus"/> to be applied to the <see cref="MyGeotabAPIAdapter.Database.Models.DbRule"/>.</param>
        /// <param name="recordLastChanged">The timestamp to be applied to the <see cref="MyGeotabAPIAdapter.Database.Models.DbRule"/>.</param>
        /// <param name="operationType">The <see cref="Database.Common.DatabaseWriteOperationType"/> to be applied to the <see cref="MyGeotabAPIAdapter.Database.Models.DbRule"/>.</param>
        /// <returns>A correctly formatted <see cref="DbRuleObject"/></returns>
        public void BuildRuleObject(Rule rule, int entityStatus,
                                    DateTime recordLastChanged, DatabaseWriteOperationType operationType)
        {
            MethodBase methodBase = MethodBase.GetCurrentMethod();

            logger.Trace($"Begin {methodBase.ReflectedType.Name}.{methodBase.Name}");

            DbRule dbRule = new DbRule
            {
                GeotabId                   = rule.Id.ToString(),
                Name                       = rule.Name.ToString(),
                BaseType                   = rule.BaseType.ToString(),
                ActiveFrom                 = rule.ActiveFrom,
                ActiveTo                   = rule.ActiveTo,
                Comment                    = rule.Comment,
                Version                    = rule.Version,
                EntityStatus               = entityStatus,
                RecordLastChangedUtc       = recordLastChanged,
                DatabaseWriteOperationType = operationType
            };

            if (rule.Condition == null)
            {
                logger.Debug($"Rule '{rule.Id}' has no conditions.");
            }
            else
            {
                ProcessConditionHierarchy(rule.Condition, entityStatus, recordLastChanged, operationType);
            }
            this.DbRule = dbRule;

            logger.Trace($"End {methodBase.ReflectedType.Name}.{methodBase.Name}");
        }
示例#2
0
        public async Task <DbRule> EditRuleAsync(DbRule rule)
        {
            var oldRule = await _context.Rules
                          .Where(r => r.Id == rule.Id)
                          .SingleOrDefaultAsync();

            if (oldRule.Name != rule.Name)
            {
                oldRule.Name = rule.Name;
            }
            if (oldRule.Explanation != rule.Explanation)
            {
                oldRule.Explanation = rule.Explanation;
            }
            if (oldRule.TranslatedExplanation != rule.TranslatedExplanation)
            {
                oldRule.TranslatedExplanation = rule.TranslatedExplanation;
            }

            try
            {
                _context.Rules.Update(oldRule);
                await _context.SaveChangesAsync();
            }
            catch (Exception)
            {
                return(null);
            }

            return(rule);
        }
示例#3
0
        /// <summary>
        /// Converts the supplied list of <see cref="Rule"/> objects into a list of <see cref="DbRule"/> objects.
        /// </summary>
        /// <param name="rules">The list of <see cref="Rule"/> objects to be converted.</param>
        /// <returns></returns>
        public static List <DbRule> GetDbRules(IList <Rule> rules)
        {
            var dbRules = new List <DbRule>();

            foreach (var rule in rules)
            {
                DbRule dbRule = GetDbRule(rule);
                dbRules.Add(dbRule);
            }
            return(dbRules);
        }
        /// <summary>
        /// Build the <see cref="DbRuleObject"/> by using the <see cref="MyGeotabAPIAdapter.Database.Models.DbRule"/> and <see cref="DbCondition"/> list objects.
        /// </summary>
        /// <param name="dbRule"></param>
        /// <param name="dbConditions"></param>
        public void BuildFromDatabaseObjects(DbRule dbRule, IList <DbCondition> dbConditions)
        {
            MethodBase methodBase = MethodBase.GetCurrentMethod();

            logger.Trace($"Begin {methodBase.ReflectedType.Name}.{methodBase.Name}");

            this.DbRule       = dbRule;
            this.DbConditions = dbConditions;

            logger.Trace($"End {methodBase.ReflectedType.Name}.{methodBase.Name}");
        }
示例#5
0
        /// <summary>
        /// Converts the supplied list of <see cref="Rule"/> objects into a list of <see cref="DbRule"/> objects.
        /// </summary>
        /// <param name="rules">The list of <see cref="Rule"/> objects to be converted.</param>
        /// <param name="entityStatus">The <see cref="Database.Common.DatabaseRecordStatus"/> to be applied to the <see cref="DbRule"/> objects.</param>
        /// <param name="recordLastChanged">The timestamp to be applied to the <see cref="DbRule"/> objects.</param>
        /// <param name="operationType">The <see cref="Database.Common.DatabaseWriteOperationType"/> to be applied to the <see cref="DbRule"/> objects.</param>
        /// <returns></returns>
        public static List <DbRule> GetDbRules(IList <Rule> rules, int entityStatus,
                                               DateTime recordLastChanged, DatabaseWriteOperationType operationType)
        {
            var dbRules = new List <DbRule>();

            foreach (var rule in rules)
            {
                DbRule dbRule = GetDbRule(rule, entityStatus, recordLastChanged, operationType);
                dbRules.Add(dbRule);
            }
            return(dbRules);
        }
示例#6
0
        public async Task <DbRule> CreateRuleAsync(DbRule rule)
        {
            if (rule == null || rule.Id != 0)
            {
                return(null);
            }

            _context.Rules.Add(rule);
            await _context.SaveChangesAsync();

            return(rule);
        }
示例#7
0
        /// <summary>
        /// Converts the supplied <see cref="Rule"/> into a <see cref="DbRule"/>.
        /// </summary>
        /// <param name="rule">The <see cref="Rule"/> to be converted.</param>
        /// <returns></returns>
        public static DbRule GetDbRule(Rule rule)
        {
            DbRule dbRule = new DbRule
            {
                GeotabId   = rule.Id.ToString(),
                Name       = rule.Name.ToString(),
                BaseType   = rule.BaseType.ToString(),
                ActiveFrom = rule.ActiveFrom,
                ActiveTo   = rule.ActiveTo,
                Comment    = rule.Comment,
                Version    = rule.Version
            };

            return(dbRule);
        }
示例#8
0
        public void BuildRuleObject_Test()
        {
            //arrange
            Rule         rule       = GetTestRule();
            DbRuleObject ruleObject = new DbRuleObject();

            //act
            ruleObject.BuildRuleObject(rule, (int)Common.DatabaseRecordStatus.Active, DateTime.UtcNow,
                                       Common.DatabaseWriteOperationType.Insert);
            DbRule dbrule = ruleObject.DbRule;
            IList <DbCondition> dbConditions = ruleObject.DbConditions;

            //assert
            Assert.True(dbrule.Name == "test");
            Assert.NotNull(dbConditions);
            Assert.True(dbConditions.Count == 7);
        }
示例#9
0
        /// <summary>
        /// Converts the supplied <see cref="Rule"/> into a <see cref="DbRule"/>.
        /// </summary>
        /// <param name="rule">The <see cref="Rule"/> to be converted.</param>
        /// <param name="entityStatus">The <see cref="Database.Common.DatabaseRecordStatus"/> to be applied to the <see cref="DbRule"/>.</param>
        /// <param name="recordLastChanged">The timestamp to be applied to the <see cref="DbRule"/>.</param>
        /// <param name="operationType">The <see cref="Database.Common.DatabaseWriteOperationType"/> to be applied to the <see cref="DbRule"/>.</param>
        /// <returns></returns>
        public static DbRule GetDbRule(Rule rule, int entityStatus,
                                       DateTime recordLastChanged, DatabaseWriteOperationType operationType)
        {
            DbRule dbRule = new DbRule
            {
                GeotabId                   = rule.Id.ToString(),
                Name                       = rule.Name.ToString(),
                BaseType                   = rule.BaseType.ToString(),
                ActiveFrom                 = rule.ActiveFrom,
                ActiveTo                   = rule.ActiveTo,
                Comment                    = rule.Comment,
                Version                    = rule.Version,
                EntityStatus               = entityStatus,
                RecordLastChangedUtc       = recordLastChanged,
                DatabaseWriteOperationType = operationType
            };

            return(dbRule);
        }
示例#10
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before @Override public void setup() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public override void Setup()
        {
            base.Setup();
            LdapServerRule.LdapServer.ConfidentialityRequired = _confidentialityRequired;

            EnterpriseAuthAndUserManager authManager = DbRule.resolveDependency(typeof(EnterpriseAuthAndUserManager));
            EnterpriseUserManager        userManager = authManager.UserManager;

            if (userManager != null)
            {
                userManager.NewUser(NONE_USER, _password.GetBytes(), false);
                userManager.NewUser(PROC_USER, _password.GetBytes(), false);
                userManager.NewUser(READ_USER, _password.GetBytes(), false);
                userManager.NewUser(WRITE_USER, _password.GetBytes(), false);
                userManager.AddRoleToUser(PredefinedRoles.READER, READ_USER);
                userManager.AddRoleToUser(PredefinedRoles.PUBLISHER, WRITE_USER);
                userManager.NewRole("role1", PROC_USER);
            }
        }
        public static void Run()
        {
            //Get element type
            int           hash = DbElementTypeInstance.EQUIPMENT.GetHashCode();
            DbElementType type = DbElementType.GetElementType(hash);

            // Get system attributes
            DbAttribute[] atts = DbElementTypeInstance.EQUIPMENT.SystemAttributes();
            int           size = atts.Length;

            //Construct equi1
            DbElement equi1 = DbElement.GetElement("/ExampleEqui");

            //Create equi2 after equi1
            DbElement equi2 = equi1.CreateAfter(DbElementTypeInstance.EQUIPMENT);

            //Copy equi1 to equi2
            equi2.Copy(equi1);

            //Copy hierarchy
            DbCopyOption options = new DbCopyOption();

            options.FromName = "ExampleEqui";
            options.ToName   = "equi2";
            options.Rename   = true;
            equi2.CopyHierarchy(equi1, options);
            DbElement first = equi2.FirstMember();

            //Copy after last
            equi1.InsertAfterLast(Example.Instance.mZone);

            //Branch to head tube
            DbElement headTube     = Example.Instance.mBran.FirstMember();
            string    headTubeName = headTube.GetString(DbAttributeInstance.NAME);

            //Next Prev
            DbElement nextElement = headTube.Next();
            DbElement prevElement = nextElement.Previous;

            //First Member of given type
            DbElement nozz1 = Example.Instance.mEqui.FirstMember(DbElementTypeInstance.NOZZLE);

            //Next element of given type
            DbElement nozz2 = nozz1.Next(DbElementTypeInstance.NOZZLE);

            //Get Members
            DbElement[] members = Example.Instance.mBran.Members();

            //Get Members of given type
            DbElement[] nozzles = Example.Instance.mEqui.Members(DbElementTypeInstance.NOZZLE);

            //Get nth Member
            DbElement mem = Example.Instance.mEqui.Member(2);

            //Expressions
            DbElement[] eles;
            eles  = Example.Instance.mEqui.GetElementArray(DbAttribute.GetDbAttribute("MEMB"), DbElementType.GetElementType("NOZZ"));
            nozz1 = eles[1];
            DbExpression    expr1 = DbExpression.Parse("HEIGHT OF PREV * 2");
            string          val   = expr1.ToString();
            double          dval;
            DbAttributeUnit units = DbAttributeUnit.DIST;

            dval = nozz1.EvaluateDouble(expr1, units);
            DbExpression expr2 = DbExpression.Parse("12");

            dval = nozz1.EvaluateDouble(expr2, units);

            //Rules
            DbExpression     expr   = DbExpression.Parse("HEIGHT * 2.0");
            DbRuleStatus     status = DbRuleStatus.DYNAMIC;
            DbExpressionType etype  = DbExpressionType.REAL;
            DbRule           rule   = DbRule.CreateDbRule(expr, status, etype);

            Example.Instance.mCyli.SetRule(DbAttribute.GetDbAttribute("DIAM"), rule);
            DbRule rule1 = Example.Instance.mCyli.GetRule(DbAttribute.GetDbAttribute("DIAM"));
            string text  = rule1.ToString();

            //Delete/Exists Rule
            Example.Instance.mCyli.DeleteRule(DbAttribute.GetDbAttribute("DIAM"));
            bool exists = Example.Instance.mCyli.ExistRule(DbAttribute.GetDbAttribute("DIAM"));

            Example.Instance.mCyli.SetRule(DbAttribute.GetDbAttribute("DIAM"), rule1);
            exists = Example.Instance.mCyli.ExistRule(DbAttribute.GetDbAttribute("DIAM"));

            //Change attribute
            Example.Instance.mCyli.SetAttribute(DbAttribute.GetDbAttribute("DIAM"), 1000.0F);
            double diam = Example.Instance.mCyli.GetDouble(DbAttribute.GetDbAttribute("DIAM"));

            //verify rule
            bool diff = Example.Instance.mCyli.VerifyRule(DbAttribute.GetDbAttribute("DIAM"));

            //execute rule
            Example.Instance.mCyli.ExecuteRule(DbAttribute.GetDbAttribute("DIAM"));
            diam = Example.Instance.mCyli.GetDouble(DbAttribute.GetDbAttribute("DIAM"));

            //verify rule again
            diff = Example.Instance.mCyli.VerifyRule(DbAttribute.GetDbAttribute("DIAM"));

            //change some attributes
            Example.Instance.mCyli.SetAttribute(DbAttribute.GetDbAttribute("DIAM"), 1000.0F);
            diam = Example.Instance.mCyli.GetDouble(DbAttribute.GetDbAttribute("DIAM"));

            //Now execute all rules under equi
            Example.Instance.mEqui.ExecuteAllRules();
            diam = Example.Instance.mCyli.GetDouble(DbAttribute.GetDbAttribute("DIAM"));

            //Propagate rules
            Example.Instance.mCyli.SetAttribute(DbAttribute.GetDbAttribute("DIAM"), 1000.0F);
            Example.Instance.mCyli.PropagateRules(DbAttribute.GetDbAttribute("DIAM"));

            //Claim/Release
            Example.Instance.mEqui.Claim();
            bool claimed = Example.Instance.mEqui.GetBool(DbAttribute.GetDbAttribute("LCLM"));

            //release equi
            MDB.CurrentMDB.SaveWork("Save Example");
            Example.Instance.mEqui.Release();
            claimed = Example.Instance.mEqui.GetBool(DbAttribute.GetDbAttribute("LCLM"));

            //Claim hierarchy
            try
            {
                Example.Instance.mEqui.ClaimHierarchy();
            }
            catch (PdmsException ex)
            {
            }
            claimed = Example.Instance.mEqui.GetBool(DbAttribute.GetDbAttribute("LCLMH"));

            //release all equi
            Example.Instance.mEqui.ReleaseHierarchy();
            claimed = Example.Instance.mEqui.GetBool(DbAttribute.GetDbAttribute("LCLM"));

            //change type
            string stype = Example.Instance.mTee.GetElementType().ToString();

            Example.Instance.mTee.ChangeType(DbElementType.GetElementType("OLET"));
            stype = Example.Instance.mTee.GetElementType().ToString();

            //UDA at default
            string      special = "Test UDA";
            DbAttribute uda     = DbAttribute.GetDbAttribute(":SPECIAL");

            if (uda != null)
            {
                Example.Instance.mElbo.SetAttribute(uda, special);
                special = Example.Instance.mElbo.GetString(uda);
                bool dflt = Example.Instance.mElbo.AtDefault(uda);

                //is one element above another in the hierarchy
                bool result = Example.Instance.mSite.IsDescendant(Example.Instance.mZone);
                result = Example.Instance.mZone.IsDescendant(Example.Instance.mSite);

                //Set uda to default
                Example.Instance.mElbo.SetAttributeDefault(uda);
                special = Example.Instance.mElbo.GetString(uda);
                dflt    = Example.Instance.mElbo.AtDefault(uda);
            }
        }
        /// <summary>
        /// Gets the Rules and Conditions from the database and constructs the DbRuleObjects which are then returned as a list.
        /// </summary>
        /// <param name="cancellationTokenSource">The <see cref="CancellationTokenSource"/>.</param>
        /// <returns></returns>
        public static async Task <IList <DbRuleObject> > GetDatabaseRuleObjectsAsync(CancellationTokenSource cancellationTokenSource)
        {
            MethodBase methodBase = MethodBase.GetCurrentMethod();

            logger.Trace($"Begin {methodBase.ReflectedType.Name}.{methodBase.Name}");

            ConnectionInfo connectionInfo = new(Globals.ConfigurationManager.DatabaseConnectionString, Globals.ConfigurationManager.DatabaseProviderType);

            string sql = "SELECT * from \"vwRuleObject\" ORDER BY \"GeotabId\"";
            IEnumerable <DbVwRuleObject> dbVwRuleObjects;

            try
            {
                dbVwRuleObjects = await DbGeneralService.ExecDynamicTypeQueryAsync <DbVwRuleObject>(connectionInfo, sql, cancellationTokenSource, Globals.ConfigurationManager.TimeoutSecondsForDatabaseTasks);
            }
            catch (Exception)
            {
                cancellationTokenSource.Cancel();
                throw;
            }
            IList <DbRuleObject> dbRuleObjectList               = new List <DbRuleObject>();
            string              ruleId                          = "";
            int                 countOfDbVwRuleObjects          = dbVwRuleObjects.Count();
            int                 countOfProcessedDbVwRuleObjects = 0;
            DbRule              dbRule                          = new();
            DbCondition         dbCondition;
            IList <DbCondition> dbConditionList = new List <DbCondition>();

            // Loop through all database rows of vwRuleObject
            foreach (DbVwRuleObject dbVwRuleObject in dbVwRuleObjects)
            {
                string currentRuleId = dbVwRuleObject.GeotabId;
                logger.Debug($"{methodBase.ReflectedType.Name}.{methodBase.Name} - Current RuleId: {currentRuleId}");
                // If rule Id changes go in here
                if (currentRuleId != ruleId)
                {
                    // Add the previous data iteration to the dbRuleObjectList
                    if (ruleId.Length > 0)
                    {
                        // Build the DbRuleObject
                        DbRuleObject dbRuleObject = new();
                        dbRuleObject.BuildFromDatabaseObjects(dbRule, dbConditionList);
                        dbRuleObjectList.Add(dbRuleObject);
                    }
                    // Add the latest rule
                    ruleId = currentRuleId;
                    logger.Debug($"{methodBase.ReflectedType.Name}.{methodBase.Name} - Add rule with Id: {ruleId}");
                    dbRule = new DbRule
                    {
                        id                   = dbVwRuleObject.RuleAdapterId,
                        GeotabId             = dbVwRuleObject.GeotabId,
                        Name                 = dbVwRuleObject.Name,
                        BaseType             = dbVwRuleObject.BaseType,
                        ActiveFrom           = dbVwRuleObject.ActiveFrom,
                        ActiveTo             = dbVwRuleObject.ActiveTo,
                        Version              = dbVwRuleObject.Version,
                        EntityStatus         = dbVwRuleObject.EntityStatus,
                        RecordLastChangedUtc = dbVwRuleObject.RecordLastChangedUtc
                    };

                    // Instantiate the next condition list to add the conditions.
                    dbConditionList = new List <DbCondition>();
                }

                // Create the current DbCondition object
                string conditionId = dbVwRuleObject.Cond_Id;
                logger.Debug($"{methodBase.ReflectedType.Name}.{methodBase.Name} - Add condition with Id: {conditionId}");
                dbCondition = new DbCondition
                {
                    id                   = dbVwRuleObject.ConditionAdapterId,
                    GeotabId             = conditionId,
                    ParentId             = dbVwRuleObject.Cond_ParentId,
                    RuleId               = dbVwRuleObject.Cond_RuleId,
                    ConditionType        = dbVwRuleObject.Cond_ConditionType,
                    DeviceId             = dbVwRuleObject.Cond_DeviceId,
                    DiagnosticId         = dbVwRuleObject.Cond_DiagnosticId,
                    DriverId             = dbVwRuleObject.Cond_DriverId,
                    Value                = (double?)dbVwRuleObject.Cond_Value,
                    WorkTimeId           = dbVwRuleObject.Cond_WorkTimeId,
                    ZoneId               = dbVwRuleObject.Cond_ZoneId,
                    EntityStatus         = (int)dbVwRuleObject.Cond_EntityStatus,
                    RecordLastChangedUtc = dbVwRuleObject.Cond_RecordLastChangedUtc
                };

                // Add the current DbCondition object to the condition list.
                dbConditionList.Add(dbCondition);
                // Update count for interest.
                countOfProcessedDbVwRuleObjects++;

                // If this is the last DbVwRuleObject being pocessed, a corresponding DbRuleObject must be built and added to the list.
                if (countOfProcessedDbVwRuleObjects == countOfDbVwRuleObjects)
                {
                    DbRuleObject dbRuleObject = new();
                    dbRuleObject.BuildFromDatabaseObjects(dbRule, dbConditionList);
                    dbRuleObjectList.Add(dbRuleObject);
                }
            }
            logger.Info($"{methodBase.ReflectedType.Name}.{methodBase.Name} - DbVwRuleObjects processed: {countOfProcessedDbVwRuleObjects}");
            logger.Trace($"End {methodBase.ReflectedType.Name}.{methodBase.Name}");
            return(dbRuleObjectList);
        }
示例#13
0
 /// <summary>
 /// Inserts a single <see cref="DbRule"/> entity into the database.
 /// </summary>
 /// <param name="connectionInfo">The database connection information.</param>
 /// <param name="dbRule">A <see cref="DbRule"/> entity to be inserted.</param>
 /// <param name="commandTimeout">The number of seconds before command execution timeout.</param>
 /// <returns></returns>
 public static async Task <long> InsertRuleAsync(ConnectionInfo connectionInfo, DbRule dbRule, int commandTimeout)
 {
     return(await new DbRuleRepository().InsertAsync(connectionInfo, dbRule, commandTimeout));
 }
示例#14
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldKeepAuthorizationForLifetimeOfTransactionWithProcedureAllowed() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldKeepAuthorizationForLifetimeOfTransactionWithProcedureAllowed()
        {
            RestartServerWithOverriddenSettings(SecuritySettings.ldap_authorization_group_to_role_mapping.name(), "503=admin;504=role1");
            DbRule.resolveDependency(typeof(Procedures)).registerProcedure(typeof(ProcedureInteractionTestBase.ClassWithProcedures));
            AssertKeepAuthorizationForLifetimeOfTransaction("smith", tx => assertThat(tx.run("CALL test.staticReadProcedure()").single().get(0).asString(), equalTo("static")));
        }