示例#1
0
        public void Test_MaxCols_Returns_Grouped_Columns()
        {
            using (new SecurityBypassContext())
            {
                var report = Entity.GetByName <Report>("Temperature").First(r => r.InSolution != null && r.InSolution.Name == "Foster University");

                ReportSettings settings = new ReportSettings
                {
                    ColumnCount         = 3,
                    RequireFullMetadata = true
                };

                var          reportInterface = new ReportingInterface();
                ReportResult result          = reportInterface.RunReport(report.Id, settings);

                Assert.That(result, Is.Not.Null);
                Assert.That(result.GridData, Has.Count.GreaterThan(0));
                Assert.That(result.GridData[0].Values, Has.Count.EqualTo(4));
                Assert.That(result.Metadata.ReportColumns, Has.Count.EqualTo(4));
                Assert.That(result.AggregateMetadata.Groups, Has.Count.EqualTo(1));
                Assert.That(result.AggregateMetadata.Groups[0], Has.Count.EqualTo(1));
                long groupColumnId = result.AggregateMetadata.Groups[0].Keys.First();
                Assert.IsTrue(result.Metadata.ReportColumns.ContainsKey(groupColumnId.ToString(CultureInfo.InvariantCulture)));
            }
        }
示例#2
0
        public void FixCoreRules(string accessRuleName, string reportName, string newAccessRuleName, string newAlias, bool markAsNonReport)
        {
            // Note: you'll need to manually disable .ReadOnly checks (eg in code)

            AccessRule rule;
            //if ( accessRuleName == null )
            //{
            Report report = Entity.GetByName <Report>(reportName).Where(r => r.ReportForAccessRule != null && (r.ReportForAccessRule.Name == accessRuleName || r.ReportForAccessRule.Name == newAccessRuleName)).Single( );

            rule = report.ReportForAccessRule.AsWritable <AccessRule>();
            //}
            //else
            //{
            //    rule = Entity.GetByName<AccessRule>( accessRuleName ).SingleOrDefault( );
            //    if ( rule == null )
            //        throw new Exception( "Rule not found" );
            //}

            rule.Name = newAccessRuleName;
            if (newAlias != null)
            {
                rule.Alias = newAlias;
            }
            if (markAsNonReport)
            {
                rule.AccessRuleIgnoreForReports = true;
                Assert.That(rule.AccessRuleIgnoreForReports, Is.True);
            }
            long id = rule.Id;

            rule.Save( );
        }
示例#3
0
        public void TestReportWithWriteOnlyField(bool isFieldWriteOnly)
        {
            try
            {
                var field = Entity.Get <Field>("test:afString", true);
                field.IsFieldWriteOnly = isFieldWriteOnly;
                field.Save();

                IEnumerable <IEntity> reports = Entity.GetByName("AF_String");

                var          reportInterface = new ReportingInterface();
                ReportResult result          = reportInterface.RunReport(reports.First().Id, null);

                if (isFieldWriteOnly)
                {
                    Assert.IsTrue(result.GridData.All(d => string.IsNullOrEmpty(d.Values[1].Value)), "We should not have any values");
                }
                else
                {
                    Assert.IsTrue(result.GridData.Any(d => !string.IsNullOrEmpty(d.Values[1].Value)), "We should have at least 1 value");
                }
            }
            finally
            {
                CacheManager.ClearCaches();
            }
        }
示例#4
0
        public void TestReport_AF_String( )
        {
            long reportId = Entity.GetByName("AF_String").First( ).Id;

            var          reportInterface = new ReportingInterface( );
            ReportResult result          = reportInterface.RunReport(reportId, null);

            Assert.That(result, Is.Not.Null);
            Assert.That(result.GridData, Has.Count.GreaterThan(0));
        }
示例#5
0
        public void TestReport_ReportToQueryConverter_Cached( )
        {
            long reportId = Entity.GetByName("AF_String").First( ).Id;

            // Mock IReportToQueryConverter and run again
            Mock <IReportToQueryConverter> mockNonCached = new Mock <IReportToQueryConverter>(MockBehavior.Strict);
            Mock <IReportToQueryConverter> mockCached    = new Mock <IReportToQueryConverter>(MockBehavior.Strict);

            using (var scope = Factory.Current.BeginLifetimeScope(builder => {
                builder.Register(ctx => mockNonCached.Object).Keyed <IReportToQueryConverter>(Factory.NonCachedKey);
                builder.Register(ctx => mockCached.Object).As <IReportToQueryConverter>( );
            }))
                using (Factory.SetCurrentScope(scope))
                {
                    var reportInterface = new ReportingInterface( );

                    IReportToQueryConverter realNonCached = new ReportToQueryConverter( );
                    IReportToQueryConverter realCached    = new CachingReportToQueryConverter(mockNonCached.Object);

                    // Setup
                    mockNonCached
                    .Setup(r2q => r2q.Convert(It.IsAny <Report>( ), It.IsAny <ReportToQueryConverterSettings>( )))
                    .Returns((Report r, ReportToQueryConverterSettings s) => realNonCached.Convert(r, s));

                    mockCached
                    .Setup(r2q => r2q.Convert(It.IsAny <Report>( ), It.IsAny <ReportToQueryConverterSettings>( )))
                    .Returns((Report r, ReportToQueryConverterSettings s) => realCached.Convert(r, s));

                    // First run
                    ReportResult result = reportInterface.RunReport(reportId, null);
                    Assert.That(result, Is.Not.Null);

                    // Second run
                    result = reportInterface.RunReport(reportId, null);
                    Assert.That(result, Is.Not.Null);

                    // Verify
                    mockNonCached
                    .Verify(r2q => r2q.Convert(It.IsAny <Report>( ), It.IsAny <ReportToQueryConverterSettings>( )), Times.Exactly(1));

                    mockCached
                    .Verify(r2q => r2q.Convert(It.IsAny <Report>( ), It.IsAny <ReportToQueryConverterSettings>( )), Times.Exactly(2));
                }
        }
示例#6
0
        public void TestReport_BU_Test( )
        {
            (( CachingQuerySqlBuilder )Factory.QuerySqlBuilder).Clear( );
            (( CachingQueryRunner )Factory.QueryRunner).Clear( );

            long reportId = Entity.GetByName("Business Unit Risks Copy 1").First( ).Id;

            Action action = () =>
            {
                using (new SecurityBypassContext( ))
                {
                    var          reportInterface = new ReportingInterface( );
                    ReportResult result          = reportInterface.RunReport(reportId, null);
                }
            };
            Task task1 = Task.Factory.StartNew(action);

            Task task2 = Task.Factory.StartNew(() => { Thread.Sleep(50); action( ); });

            Task.WaitAll(task1, task2);
        }
示例#7
0
        public void SecurityCheckTest()
        {
            UserAccount userAccount;

            const long testEntityId = 21660;

            userAccount = Entity.GetByName <UserAccount>("Erica.Mcknight").First();
            Assert.That(userAccount, Is.Not.Null, "User not found");

            using (new SetUser(Entity.GetByName <UserAccount>("Erica.Mcknight").First()))
                using (new ForceSecurityTraceContext(testEntityId))
                {
                    IEnumerable <IEntity> entities = Entity.GetInstancesOfType(new EntityRef(testEntityId)).ToList();
                    foreach (IEntity entity in entities)
                    {
                        Console.Out.WriteLine("{0} ({1})", entity.GetField("core:name"), entity.Id);
                    }

                    //new EntityAccessControlFactory().Service.Check(
                    //    new EntityRef(testEntityId),
                    //    new [] { Permissions.Delete });
                }
        }
示例#8
0
        private static void CreateUsersAndSecurity(ref GrandDesign testObject)
        {
            //
            // Users
            //
            var administratorUser = Entity.Get <UserAccount>(new EntityRef("core:administratorUserAccount"), true);

            testObject.Accounts.Add("administrator", administratorUser);

            //
            // Access Rules
            //
            new AccessRuleFactory().AddAllowByQuery(administratorUser.As <Subject>(),
                                                    testObject.Types["unit"].As <SecurableEntity>(),
                                                    new[] { "core:read", "core:modify", "core:delete", "core:create" }.Select(p => new EntityRef(p)),
                                                    TestQueries.Entities(testObject.Types["unit"]).ToReport());

            //
            // Read
            //
            var reader = Entity.Create <Person>();

            reader.FirstName = "Robbie";
            reader.LastName  = "Reader";

            var readerAccount = Entity.Create <UserAccount>();

            readerAccount.Name          = "reader";
            readerAccount.AccountHolder = reader;
            readerAccount.Save();
            testObject.Accounts.Add("reader", readerAccount);

            new AccessRuleFactory().AddAllowByQuery(readerAccount.As <Subject>(),
                                                    testObject.Types["unit"].As <SecurableEntity>(),
                                                    new[] { "core:read" }.Select(p => new EntityRef(p)),
                                                    TestQueries.Entities(testObject.Types["unit"]).ToReport());

            //
            // Read + Modify
            //
            var modifier = Entity.Create <Person>();

            modifier.FirstName = "Margie";
            modifier.LastName  = "Modifier";

            var modifierAccount = Entity.Create <UserAccount>();

            modifierAccount.Name          = "modifier";
            modifierAccount.AccountHolder = modifier;
            modifierAccount.Save();
            testObject.Accounts.Add("modifier", modifierAccount);

            new AccessRuleFactory().AddAllowByQuery(modifierAccount.As <Subject>(),
                                                    testObject.Types["unit"].As <SecurableEntity>(),
                                                    new[] { "core:read", "core:modify" }.Select(p => new EntityRef(p)),
                                                    TestQueries.Entities(testObject.Types["unit"]).ToReport());

            //
            // Read, Modify + Create
            //
            var creator = Entity.Create <Person>();

            creator.FirstName = "Connie";
            creator.LastName  = "Creator";

            var creatorAccount = Entity.Create <UserAccount>();

            creatorAccount.Name          = "creator";
            creatorAccount.AccountHolder = creator;
            creatorAccount.Save();
            testObject.Accounts.Add("creator", creatorAccount);

            new AccessRuleFactory().AddAllowByQuery(creatorAccount.As <Subject>(),
                                                    testObject.Types["unit"].As <SecurableEntity>(),
                                                    new[] { "core:read", "core:modify", "core:create" }.Select(p => new EntityRef(p)),
                                                    TestQueries.Entities(testObject.Types["unit"]).ToReport());

            //
            // Read, Modify + Delete
            //
            var deleter = Entity.Create <Person>();

            deleter.FirstName = "Donnie";
            deleter.LastName  = "Deleter";

            var deleterAccount = Entity.Create <UserAccount>();

            deleterAccount.Name          = "deleter";
            deleterAccount.AccountHolder = deleter;
            deleterAccount.Save();
            testObject.Accounts.Add("deleter", deleterAccount);

            new AccessRuleFactory().AddAllowByQuery(deleterAccount.As <Subject>(),
                                                    testObject.Types["unit"].As <SecurableEntity>(),
                                                    new[] { "core:read", "core:modify", "core:delete" }.Select(p => new EntityRef(p)),
                                                    TestQueries.Entities(testObject.Types["unit"]).ToReport());

            //
            // Folder
            //
            var folder = Entity.Create <Folder>();

            folder.Name = "Get Actions";
            folder.ResourceInFolder.Add(Entity.GetByName <NavSection>("Test Solution").First().As <NavContainer>());
            folder.Save();
            testObject.WorkingFolder = folder;

            //
            // All these accounts should see...
            //
            foreach (var account in testObject.Accounts.Values)
            {
                //
                // ...workflows
                //
                new AccessRuleFactory().AddAllowByQuery(account.As <Subject>(),
                                                        Workflow.Workflow_Type.As <SecurableEntity>(),
                                                        new EntityRef("core:read").ToEnumerable(),
                                                        TestQueries.Entities(new EntityRef("core:workflow")).ToReport());

                //
                // ... report templates
                //
                new AccessRuleFactory().AddAllowByQuery(account.As <Subject>(),
                                                        ReportTemplate.ReportTemplate_Type.As <SecurableEntity>(),
                                                        new EntityRef("core:read").ToEnumerable(),
                                                        TestQueries.Entities(new EntityRef("core:reportTemplate")).ToReport());
            }
        }
示例#9
0
        public void Test_GetActions_Security_ReadModifyDelete(string permissionAliases)
        {
            ActionRequestExtended actionRequest;
            ActionResponse        response;
            Report                     peopleReport;
            UserAccount                userAccount;
            Person                     person;
            ActionMenuItem             viewActionMenuItem;
            ActionMenuItem             editActionMenuItem;
            ActionMenuItem             deleteActionMenuItem;
            IList <ActionMenuItemInfo> flattenedResults;

            string[] splitPermissionAliases;

            splitPermissionAliases = permissionAliases.Split(',');

            userAccount = Entity.Create <UserAccount>();
            userAccount.Save();

            person = Entity.Create <Person>();
            person.Save();

            viewActionMenuItem = Entity.Get <ActionMenuItem>("console:viewResourceAction");
            Assert.That(viewActionMenuItem, Is.Not.Null, "No view menu item");
            editActionMenuItem = Entity.Get <ActionMenuItem>("console:editResourceAction");
            Assert.That(editActionMenuItem, Is.Not.Null, "No edit menu item");
            deleteActionMenuItem = Entity.Get <ActionMenuItem>("console:deleteResourceAction");
            Assert.That(deleteActionMenuItem, Is.Not.Null, "No delete menu item");

            if (!string.IsNullOrWhiteSpace(permissionAliases))
            {
                new AccessRuleFactory().AddAllowByQuery(
                    userAccount.As <Subject>(),
                    Entity.Get <SecurableEntity>(Entity.Get <EntityType>("core:person")),
                    splitPermissionAliases.Select(pa => new EntityRef(pa)),
                    TestQueries.Entities().ToReport());
            }

            peopleReport = Entity.GetByName <Report>("People").FirstOrDefault();
            Assert.That(peopleReport, Is.Not.Null, "No People report");

            actionRequest = new ActionRequestExtended
            {
                SelectedResourceIds    = new[] { person.Id },
                LastSelectedResourceId = person.Id,
                CellSelectedResourceId = -1,
                ReportId             = peopleReport.Id,
                HostResourceIds      = new long[0],
                HostTypeIds          = new List <long>(),
                AdditionalData       = new Dictionary <string, object>(),
                ActionDisplayContext = ActionContext.ActionsMenu
            };

            using (new SetUser(userAccount))
            {
                response = new ActionService().GetActions(actionRequest);
            }

            flattenedResults = response.Actions.SelectMany(Flatten).ToList();

            Assert.That(flattenedResults,
                        Has.Exactly(splitPermissionAliases.Contains("read") ? 1 : 0).Property("Id").EqualTo(viewActionMenuItem.Id),
                        "View menu incorrect");
            Assert.That(flattenedResults,
                        Has.Exactly(splitPermissionAliases.Contains("read") && splitPermissionAliases.Contains("modify") ? 1 : 0).Property("Id").EqualTo(editActionMenuItem.Id),
                        "Edit menu incorrect");
            Assert.That(flattenedResults,
                        Has.Exactly(splitPermissionAliases.Contains("read") && splitPermissionAliases.Contains("delete") ? 1 : 0).Property("Id").EqualTo(deleteActionMenuItem.Id),
                        "Delete menu incorrect");
        }
示例#10
0
        [TestCase("API Endpoints", "API Resource Endpoint,API Spreadsheet Endpoint", true)] //#27489
        public void Test_GetActions_Security_Create(string reportName, string typeNames, bool admin)
        {
            ActionRequestExtended actionRequest;
            ActionResponse        response;
            Report      report;
            UserAccount userAccount;
            IList <ActionMenuItemInfo> flattenedResults;

            string[]        splitTypeNames;
            SecurableEntity securableEntity;

            splitTypeNames = typeNames.Split(',');

            userAccount      = Entity.Create <UserAccount>();
            userAccount.Name = "Action service test " + Guid.NewGuid( ).ToString( );
            userAccount.Save();

            new AccessRuleFactory( ).AddAllowReadQuery(
                userAccount.As <Subject>( ),
                Entity.Get <SecurableEntity>(Entity.Get <EntityType>("core:report")),
                TestQueries.Entities(new EntityRef("core:report")).ToReport( ));

            if (!string.IsNullOrWhiteSpace(typeNames))
            {
                foreach (string typeName in splitTypeNames)
                {
                    securableEntity = Entity.GetByName <SecurableEntity>(typeName).FirstOrDefault();
                    Assert.That(securableEntity, Is.Not.Null,
                                string.Format("{0} is not a type", typeName));

                    new AccessRuleFactory().AddAllowCreate(
                        userAccount.As <Subject>(),
                        securableEntity);
                }
            }

            report = Entity.GetByName <Report>(reportName).FirstOrDefault();
            Assert.That(report, Is.Not.Null, string.Format("{0} is not a report", reportName));

            actionRequest = new ActionRequestExtended
            {
                SelectedResourceIds    = new long[0],
                LastSelectedResourceId = 0,
                CellSelectedResourceId = -1,
                ReportId             = report.Id,
                HostResourceIds      = new long[0],
                HostTypeIds          = new List <long>(),
                AdditionalData       = new Dictionary <string, object>(),
                ActionDisplayContext = ActionContext.ActionsMenu
            };

            if (admin)
            {
                response = new ActionService( ).GetActions(actionRequest);
            }
            else
            {
                using (new SetUser(userAccount))
                {
                    response = new ActionService( ).GetActions(actionRequest);
                }
            }

            flattenedResults = response.Actions.SelectMany(Flatten).ToList();

            if (!string.IsNullOrWhiteSpace(typeNames))
            {
                foreach (string typeName in splitTypeNames)
                {
                    string expectState = typeName == "API Resource Endpoint" ? "resourceEndpointNew" : ActionService.CreateMenuItemActionState;

                    Assert.That(flattenedResults,
                                Has.Exactly(1).Property("HtmlActionState").EqualTo(expectState)
                                .And.Property("Name").EqualTo(typeName));
                }
            }
            else
            {
                Assert.That(flattenedResults,
                            Has.Exactly(0).Property("HtmlActionState").EqualTo(ActionService.CreateMenuItemActionState));
            }
        }
示例#11
0
        public void TestReportConditionForCalculatedFieldUnknownType_Bug25079()
        {
            using (new SecurityBypassContext())
            {
                // Get the report root type
                EntityType dogBreedsType = Entity.GetByName <EntityType>("AA_DogBreeds").FirstOrDefault();

                // Build the query and report
                var re = new ResourceEntity(dogBreedsType);

                var structuredQuery = new StructuredQuery
                {
                    RootEntity = re
                };

                // Build id column
                var idColumn = new SelectColumn
                {
                    Expression = new IdExpression
                    {
                        NodeId = re.NodeId
                    },
                    IsHidden    = true,
                    DisplayName = "_id"
                };

                // Build calculated column
                var calcColumn = new SelectColumn
                {
                    Expression = new ReadiNow.Metadata.Query.Structured.ScriptExpression
                    {
                        NodeId     = re.NodeId,
                        Script     = @"iif(iif([Group] = 'Herding', 1, iif([Group] = 'Non-sporting', 2, iif([Group] = 'Scenthound', 3, iif([Group] = 'Terrier', 4, iif([Group] = 'toy', 5, iif([Group] = 'Working', 5, 0)))))) > 4, 'Requires attention', 'On track')",
                        ResultType = new StringType()
                    },
                    DisplayName = "Calc"
                };

                // Add columns to query
                structuredQuery.SelectColumns.Add(idColumn);
                structuredQuery.SelectColumns.Add(calcColumn);

                // Build condition on calc column
                var calcCondition = new QueryCondition
                {
                    Expression = new ColumnReference
                    {
                        ColumnId = calcColumn.ColumnId
                    },
                    Operator = ConditionType.Unspecified,
                    Argument = new TypedValue
                    {
                        Type = new UnknownType()
                    }
                };

                // Add condition to query
                structuredQuery.Conditions.Add(calcCondition);

                // Convert to report and save
                ReadiNow.Model.Report report = structuredQuery.ToReport();
                report.Name = "Test Calc Report " + Guid.NewGuid();
                report.Save();

                // Get strcutured query back so that we have entity ids
                // for structured query elements
                structuredQuery = ReportToQueryConverter.Instance.Convert(report);

                // Add the ad-hoc condition and run the report
                var settings = new ReportSettings
                {
                    ReportParameters = new ReportParameters
                    {
                        AnalyserConditions = new List <SelectedColumnCondition>()
                    },
                    InitialRow = 0,
                    PageSize   = 100
                };

                settings.ReportParameters.AnalyserConditions.Add(new SelectedColumnCondition
                {
                    Operator     = ConditionType.Contains,
                    Value        = "Requires attention",
                    ExpressionId = structuredQuery.Conditions[0].EntityId.ToString(CultureInfo.InvariantCulture),
                    Type         = new StringType()
                });

                var          reportInterface = new ReportingInterface();
                ReportResult result          = reportInterface.RunReport(report, settings);

                // Verify that correct rows are returned
                Assert.IsTrue(result.GridData.All(r => r.Values[0].Value.ToLowerInvariant().Contains(settings.ReportParameters.AnalyserConditions[0].Value.ToLowerInvariant())));
            }
        }
示例#12
0
        public void TestReport_ReportToQueryConverter_WithFauxRelationship_Cached( )
        {
            long reportId       = CodeNameResolver.GetInstance("Template", "Report").Id;
            var  type           = Entity.GetByName <EntityType>("AA_DogBreeds").First();
            long relationshipId = Factory.ScriptNameResolver.GetMemberOfType("AA_All Fields", type.Id, MemberType.Relationship).MemberId;
            long foreignId1     = CodeNameResolver.GetInstance("Test 01", "AA_All Fields").Id;
            long foreignId2     = CodeNameResolver.GetInstance("Test 02", "AA_All Fields").Id;

            ReportSettings settings = new ReportSettings
            {
                ReportRelationship = new ReportRelationshipSettings
                {
                    Direction      = ReportRelationshipSettings.ReportRelationshipDirection.Forward,
                    RelationshipId = relationshipId
                },
                ReportOnType = type.Id
            };

            // Mock IReportToQueryConverter and run again
            Mock <IReportToQueryConverter> mockNonCached = new Mock <IReportToQueryConverter>(MockBehavior.Strict);
            Mock <IReportToQueryConverter> mockCached    = new Mock <IReportToQueryConverter>(MockBehavior.Strict);

            using (var scope = Factory.Current.BeginLifetimeScope(builder =>
            {
                builder.Register(ctx => mockNonCached.Object).Keyed <IReportToQueryConverter>(Factory.NonCachedKey);
                builder.Register(ctx => mockCached.Object).As <IReportToQueryConverter>( );
            }))
                using (Factory.SetCurrentScope(scope))
                {
                    var reportInterface = new ReportingInterface( );

                    IReportToQueryConverter realNonCached = new ReportToQueryConverter( );
                    IReportToQueryConverter realCached    = new CachingReportToQueryConverter(mockNonCached.Object);

                    // Setup
                    mockNonCached
                    .Setup(r2q => r2q.Convert(It.IsAny <Report>( ), It.IsAny <ReportToQueryConverterSettings>( )))
                    .Returns((Report r, ReportToQueryConverterSettings s) => realNonCached.Convert(r, s));

                    mockCached
                    .Setup(r2q => r2q.Convert(It.IsAny <Report>( ), It.IsAny <ReportToQueryConverterSettings>( )))
                    .Returns((Report r, ReportToQueryConverterSettings s) => realCached.Convert(r, s));

                    // First run
                    settings.ReportRelationship.EntityId = foreignId1;
                    ReportResult result = reportInterface.RunReport(reportId, settings);
                    Assert.That(result, Is.Not.Null);
                    Assert.That(result.GridData [0].Values [0].Value, Is.EqualTo("Afghan Hound"));

                    // Second run
                    settings.ReportRelationship.EntityId = foreignId2;
                    result = reportInterface.RunReport(reportId, settings);
                    Assert.That(result, Is.Not.Null);
                    Assert.That(result.GridData [0].Values [0].Value, Is.EqualTo("Australian Cattle Dog"));

                    // Verify
                    mockNonCached
                    .Verify(r2q => r2q.Convert(It.IsAny <Report>( ), It.IsAny <ReportToQueryConverterSettings>( )), Times.Exactly(1));

                    mockCached
                    .Verify(r2q => r2q.Convert(It.IsAny <Report>( ), It.IsAny <ReportToQueryConverterSettings>( )), Times.Exactly(2));
                }
        }