public void reading_big_text_with_execute_scalar_fails_limit_is_2033_characters()
        {
            using( var ctx = new SqlStandardCallContext( TestHelper.Monitor ) )
            {
                var c = ctx[TestHelper.MasterConnectionString];

                string read;

                SqlCommand cFailXml = new SqlCommand( "select * from sys.objects for xml path" );
                read = (string)c.ExecuteScalar( cFailXml );
                read.Should().HaveLength( 2033, "2033 is the upper limit for ExecuteScalar." );

                SqlCommand cFailJson = new SqlCommand( "select * from sys.objects for json auto" );
                read = (string)c.ExecuteScalar( cFailJson );
                read.Should().HaveLength( 2033, "2033 is the upper limit for ExecuteScalar." );

                // Using convert works for Json and Xml.
                SqlCommand cConvJson = new SqlCommand( "select convert( nvarchar(max), (select * from sys.objects for json auto))" );
                string readJsonConvert = (string)c.ExecuteScalar( cConvJson );
                readJsonConvert.Length.Should().BeGreaterThan( 20 * 1024 );

                SqlCommand cConvXml = new SqlCommand( "select convert( nvarchar(max), (select * from sys.objects for xml path))" );
                string readXmlConvert = (string)c.ExecuteScalar( cConvXml );
                readXmlConvert.Length.Should().BeGreaterThan( 20 * 1024 );

                // Using the SqlDataReader works for Json and Xml.
                SqlCommand cReaderJson = new SqlCommand( "select 1, Json = (select * from sys.objects for json auto)" );
                string readJsonViaReader = c.ExecuteSingleRow( cReaderJson, r => r.GetString( 1 ) );
                readJsonViaReader.Length.Should().BeGreaterThan( 20 * 1024 );

                Assert.That( readJsonViaReader, Is.EqualTo( readJsonConvert ) );

                SqlCommand cReaderXml = new SqlCommand( "select Xml = (select * from sys.objects for xml path)" );
                string readXmlViaReader = c.ExecuteSingleRow( cReaderXml, r => r.GetString( 0 ) );
                readXmlViaReader.Length.Should().BeGreaterThan( 20 * 1024 );

                readXmlViaReader.Should().Be( readXmlConvert );
            }
        }
        public async Task a_user_Unfav_a_project()
        {
            var projectStudent = TestHelper.StObjMap.StObjs.Obtain <ProjectStudentTable>();
            var userTable      = TestHelper.StObjMap.StObjs.Obtain <UserTable>();
            var userFavTable   = TestHelper.StObjMap.StObjs.Obtain <UserFavProjectTable>();
            var sqlDatabase    = TestHelper.StObjMap.StObjs.Obtain <SqlDefaultDatabase>();

            using (var ctx = new SqlStandardCallContext())
            {
                ProjectQueries projectQueries = new ProjectQueries(ctx, sqlDatabase);
                var            ProjectCreate  = await projectStudent.CreateProjectStudent(ctx, 1, 2, "name", 1, "a;b;c", "aaa", "okok", "wwww", 1, "I");

                var userCreate = await userTable.CreateUserAsync(ctx, 1, Guid.NewGuid().ToString());

                await userFavTable.FavOrUnfavProject(ctx, userCreate, ProjectCreate.ProjectStudentId);

                await userFavTable.FavOrUnfavProject(ctx, userCreate, ProjectCreate.ProjectStudentId);

                //UserFavProjectData userFavProjectData = await projectQueries.GetSPecificFavOfUser( userCreate, ProjectCreate.ProjectStudentId );
                // Assert.That( userFavProjectData == null );
            }
        }
        public async Task UpdateStatement_withChangedData_shouldNotThrowException_and_shouldUpdateForesaidStatement()
        {
            using (var ctx = new SqlStandardCallContext())
            {
                var sTable = CK.Core.StObjModelExtension.Obtain <StatementTable>(TestHelper.StObjMap.StObjs);

                // #1. Creates the Statement object that is next going to be inserted in database.
                var sId = await sTable.CreateStatementAsync(ctx, systemId, Level.Info, 0, 0, string.Empty);

                // #2. Updating the foresaid Statement object should not present issues.
                var         newStatus = 312; var newText = "TEST";
                Func <Task> act = async() => await sTable.UpdateStatementAsync(ctx, systemId, sId, newText, 312);

                act.Should().NotThrow <SqlDetailedException>();

                // #3. Asserts that update process has been successful.
                var stObj = await ctx[sTable].Connection.QueryFirstOrDefaultAsync <StdStatementInfo>
                                ("select * from SES.tStatement where StatementId = @id;", new { id = sId });
                Assert.That(stObj.Text, Is.EqualTo(newText));
                Assert.That(stObj.Status, Is.EqualTo(newStatus));
            }
        }
        public async Task <IEnumerable <AllProjectInfoData> > GetProjectsEvaluate(int idSchool)
        {
            SqlDefaultDatabase db = _stObjMap.StObjs.Obtain <SqlDefaultDatabase>();
            int userId            = _authenticationInfo.ActualUser.UserId;

            using (var ctx = new SqlStandardCallContext())
            {
                ProjectQueries     projectQueries     = new ProjectQueries(ctx, db);
                TimedPeriodQueries timedPeriodQueries = new TimedPeriodQueries(ctx, db);
                TimedUserQueries   timedUserQueries   = new TimedUserQueries(ctx, db);
                UserQueries        userQueries        = new UserQueries(ctx, db);
                GroupQueries       groupQueries       = new GroupQueries(ctx, db);

                PeriodData periodData = await timedPeriodQueries.GetLastPeriodBySchool(idSchool);

                //Implementer check date period

                IEnumerable <AllProjectInfoData> projectData = await projectQueries.GetAllProjectTimedByJuryId(userId, periodData.ChildId);

                return(projectData);
            }
        }
示例#5
0
        public async Task token_expiration_and_ExtraData_set()
        {
            var tokenStoreTable = TestHelper.StObjMap.StObjs.Obtain <TokenStoreTable>();

            using (var ctx = new SqlStandardCallContext())
            {
                var info   = tokenStoreTable.GenerateTestInvitationInfo();
                var result = await tokenStoreTable.CreateAsync(ctx, 1, info);

                var expiration = DateTime.UtcNow + TimeSpan.FromMinutes(15);
                result.Success.Should().BeTrue();
                await tokenStoreTable.ActivateAsync(ctx, 1, result.TokenId, null, expiration);

                var startInfo = await tokenStoreTable.CheckAsync(ctx, 1, result.Token);

                startInfo.ExpirationDateUtc.Should().BeCloseTo(expiration, TimeSpan.FromMilliseconds(500));

                await tokenStoreTable.SetExtraDataAsync(ctx, 1, result.TokenId, new byte[] { 0, 1, 2 });

                info = await tokenStoreTable.CheckAsync(ctx, 1, result.Token);

                info.Should().BeEquivalentTo(startInfo, o => o.Excluding(i => i.ExtraData)
                                             .Excluding(i => i.LastCheckedDate)
                                             .Excluding(i => i.ValidCheckedCount));
                info.ExtraData.Should().BeEquivalentTo(new byte[] { 0, 1, 2 }, o => o.WithStrictOrdering());
                info.ValidCheckedCount.Should().Be(startInfo.ValidCheckedCount + 1);
                info.LastCheckedDate.Should().BeOnOrAfter(startInfo.LastCheckedDate);

                await tokenStoreTable.SetExtraDataAsync(ctx, 1, result.TokenId, null);

                info = await tokenStoreTable.CheckAsync(ctx, 1, result.Token);

                info.Should().BeEquivalentTo(startInfo, o => o.Excluding(i => i.LastCheckedDate)
                                             .Excluding(i => i.ValidCheckedCount));
                info.ExtraData.Should().BeNull();
                info.ValidCheckedCount.Should().Be(startInfo.ValidCheckedCount + 2);
                info.LastCheckedDate.Should().BeOnOrAfter(startInfo.LastCheckedDate);
            }
        }
示例#6
0
        public async Task ForumNumberParser(IStObjMap stObjMap, List <ProjectNumbers> projectNumbers, IAuthenticationInfo authenticationInfo)
        {
            using (var ctx = new SqlStandardCallContext())
            {
                var             sqlDatabase     = stObjMap.StObjs.Obtain <SqlDefaultDatabase>();
                GroupQueries    projectQueries  = new GroupQueries(ctx, sqlDatabase);
                ForumInfosTable forumInfosTable = stObjMap.StObjs.Obtain <ForumInfosTable>();
                int             userId          = authenticationInfo.ActualUser.UserId;
                GroupData       groupData       = await projectQueries.GetIdSchoolByConnectUser(userId);

                foreach (ProjectNumbers projectNumber in projectNumbers)
                {
                    int projectId = await projectQueries.GetSpecificIdGroupByZoneIdAndGroupName(groupData.ZoneId, projectNumber.ProjectName);

                    if (projectId == 0)
                    {
                        Console.WriteLine("-----" + projectNumber.ProjectName);
                    }
                    await forumInfosTable.CreateForumInfo(ctx, projectId, "", -1, -1, 4, 3, projectNumber.ProjectNumber);
                }
            }
        }
        public void vUserAuthProvider_reflects_the_user_GitHub_authentication()
        {
            var u    = TestHelper.StObjMap.StObjs.Obtain <UserGitHubTable>();
            var user = TestHelper.StObjMap.StObjs.Obtain <UserTable>();

            using (var ctx = new SqlStandardCallContext())
            {
                string userName        = "******" + Guid.NewGuid().ToString();
                var    googleAccountId = Guid.NewGuid().ToString("N");
                var    idU             = user.CreateUser(ctx, 1, userName);
                u.Database.ExecuteReader($"select * from CK.vUserAuthProvider where UserId={idU} and Scheme='GitHub'")
                .Rows.Should().BeEmpty();
                var info = u.CreateUserInfo <IUserGitHubInfo>();
                info.GitHubAccountId = googleAccountId;
                u.CreateOrUpdateGitHubUser(ctx, 1, idU, info);
                u.Database.ExecuteScalar($"select count(*) from CK.vUserAuthProvider where UserId={idU} and Scheme='GitHub'")
                .Should().Be(1);
                u.DestroyGitHubUser(ctx, 1, idU);
                u.Database.ExecuteReader($"select * from CK.vUserAuthProvider where UserId={idU} and Scheme='GitHub'")
                .Rows.Should().BeEmpty();
            }
        }
示例#8
0
        public void fallbaks_between_french_and_english_cultures()
        {
            var p = TestHelper.StObjMap.Default.Obtain <Package>();

            using (var ctx = new SqlStandardCallContext())
            {
                int noValuesId, enId, frId, bothId;
                AssumeFallbackTestEnglishAndFrenchResources(p, ctx, out noValuesId, out enId, out frId, out bothId);

                CheckString(p, noValuesId, 9, DBNull.Value, DBNull.Value);
                CheckString(p, noValuesId, 12, DBNull.Value, DBNull.Value);

                CheckString(p, enId, 9, "Only in English.", 9);
                CheckString(p, enId, 12, "Only in English.", 9);

                CheckString(p, frId, 9, "Seulement en Français.", 12);
                CheckString(p, frId, 12, "Seulement en Français.", 12);

                CheckString(p, bothId, 9, "English (and French).", 9);
                CheckString(p, bothId, 12, "Français (et Anglais).", 12);
            }
        }
示例#9
0
        public void fallbaks_between_french_and_english_and_german_cultures()
        {
            var p = TestHelper.StObjMap.Default.Obtain <Package>();

            using (var ctx = new SqlStandardCallContext())
            {
                int noValuesId, enId, frId, bothId;
                AssumeFallbackTestEnglishAndFrenchResources(p, ctx, out noValuesId, out enId, out frId, out bothId);
                int deId  = p.ResTable.Create(ctx);
                int allId = p.ResTable.Create(ctx);

                Culture.Tests.ExtendedCultureTests.RegisterGerman(p.Culture, ctx);

                p.MCResStringTable.SetString(ctx, deId, 7, "Nur in deutscher Sprache.");
                p.MCResStringTable.SetString(ctx, allId, 12, "Français (et Anglais et Allemand).");
                p.MCResStringTable.SetString(ctx, allId, 9, "English (and French and German).");
                p.MCResStringTable.SetString(ctx, allId, 7, "Deutsch (und Englisch und Französisch).");

                CheckString(p, noValuesId, 9, DBNull.Value, DBNull.Value);
                CheckString(p, noValuesId, 12, DBNull.Value, DBNull.Value);
                CheckString(p, noValuesId, 7, DBNull.Value, DBNull.Value);

                CheckString(p, enId, 9, "Only in English.", 9);
                CheckString(p, enId, 12, "Only in English.", 9);
                CheckString(p, enId, 7, "Only in English.", 9);

                CheckString(p, frId, 9, "Seulement en Français.", 12);
                CheckString(p, frId, 12, "Seulement en Français.", 12);
                CheckString(p, frId, 7, "Seulement en Français.", 12);

                CheckString(p, bothId, 9, "English (and French).", 9);
                CheckString(p, bothId, 12, "Français (et Anglais).", 12);
                CheckString(p, bothId, 7, "English (and French).", 9);

                CheckString(p, allId, 9, "English (and French and German).", 9);
                CheckString(p, allId, 12, "Français (et Anglais et Allemand).", 12);
                CheckString(p, allId, 7, "Deutsch (und Englisch und Französisch).", 7);
            }
        }
示例#10
0
        public async Task <IActionResult> GetProjectsFav()
        {
            int userId      = _authenticationInfo.ActualUser.UserId;
            var sqlDataBase = _stObjMap.StObjs.Obtain <SqlDefaultDatabase>();


            using (var ctx = new SqlStandardCallContext())
            {
                UserQueries userQueries = new UserQueries(ctx, sqlDataBase);

                List <ProjectUserFavData> userFavProjects = await userQueries.GetProjectsFavUser(userId);


                //UserFavProjectData test = userFavProjects[0];

                //userFavProjects.Add( test );
                //userFavProjects.Add( test );
                //userFavProjects.Add( test );

                return(Ok(userFavProjects));
            }
        }
        public void InfoMessage_are_monitored_when_SqlHelper_LogSqlServerInfoMessage_is_set_to_true()
        {
            SqlHelper.LogSqlServerInfoMessage = true;
            IReadOnlyList <ActivityMonitorSimpleCollector.Entry> entries = null;
            var m = new ActivityMonitor(false);

            // The messages are Traced but the monitor level is temporarily set to LogFilter.Trace:
            // Even if the monitor should not catch them, info messages traces will be emitted.
            m.MinimalFilter = LogFilter.Release;
            using (m.CollectEntries(logs => entries = logs, LogLevelFilter.Debug))
                using (m.Output.CreateBridgeTo(TestHelper.Monitor.Output.BridgeTarget))
                    using (var ctx = new SqlStandardCallContext(m))
                    {
                        ISqlConnectionController c = ctx[TestHelper.GetConnectionString()];
                        c.ExplicitOpen();
                        var cmd = c.Connection.CreateCommand();
                        cmd.CommandText = "print 'Here I am: a print.';";
                        cmd.ExecuteNonQuery();
                    }
            entries.Any(e => e.Text.Contains("Here I am: a print.")).Should().BeTrue();
            SqlHelper.LogSqlServerInfoMessage = false;
        }
示例#12
0
        public void setting_culture_fallbacks()
        {
            var p = TestHelper.StObjMap.Default.Obtain <Package>();

            using (var ctx = new SqlStandardCallContext())
            {
                CultureTests.RestoreDatabaseToEnglishAndFrenchOnly(p);
                RegisterSpanish(p, ctx);
                RegisterArabic(p, ctx);
                p.GetExtendedCulture(ctx, 10).Fallbacks.Select(c => c.LCID)
                .Should().BeEquivalentTo(new[] { 10, 9, 12, 1 }, o => o.WithStrictOrdering());
                p.SetLCIDFallbaks(ctx, 10, new[] { 10, 12 });
                p.GetExtendedCulture(ctx, 10).Fallbacks.Select(c => c.LCID)
                .Should().BeEquivalentTo(new[] { 10, 12, 9, 1 }, o => o.WithStrictOrdering());
                p.SetLCIDFallbaks(ctx, 10, new[] { 10, 1 });
                p.GetExtendedCulture(ctx, 10).Fallbacks.Select(c => c.LCID)
                .Should().BeEquivalentTo(new[] { 10, 1, 12, 9 }, o => o.WithStrictOrdering());
                p.SetLCIDFallbaks(ctx, 10, new[] { 10, 9, 1, 12 });
                p.GetExtendedCulture(ctx, 10).Fallbacks.Select(c => c.LCID)
                .Should().BeEquivalentTo(new[] { 10, 9, 1, 12 }, o => o.WithStrictOrdering());
            }
        }
示例#13
0
        public async Task password_migration_is_supported_by_user_id_and_user_name_async()
        {
            var p    = TestHelper.StObjMap.Default.Obtain <Package>();
            var u    = TestHelper.StObjMap.Default.Obtain <UserPasswordTable>();
            var user = TestHelper.StObjMap.Default.Obtain <UserTable>();

            using (var ctx = new SqlStandardCallContext())
            {
                // By identifier
                {
                    string userName = Guid.NewGuid().ToString();
                    var    idU      = await user.CreateUserAsync(ctx, 1, userName);

                    p.PasswordMigrator = new MigrationSupport(idU, "toto");
                    (await u.LoginUserAsync(ctx, idU, "failed")).UserId.Should().Be(0);
                    p.Database.ExecuteReader($"select 1 from CK.tUserPassword where UserId={idU}")
                    .Rows.Should().BeEmpty();
                    (await u.LoginUserAsync(ctx, idU, "toto")).UserId.Should().Be(idU);
                    p.Database.ExecuteScalar($"select 1 from CK.tUserPassword where UserId={idU}")
                    .Should().Be(1);
                    (await u.LoginUserAsync(ctx, idU, "toto")).UserId.Should().Be(idU);
                }
                // By user name
                {
                    string userName = Guid.NewGuid().ToString();
                    var    idU      = await user.CreateUserAsync(ctx, 1, userName);

                    p.PasswordMigrator = new MigrationSupport(idU, "toto");
                    (await u.LoginUserAsync(ctx, userName, "failed")).UserId.Should().Be(0);
                    p.Database.ExecuteReader($"select 1 from CK.tUserPassword where UserId={idU}")
                    .Rows.Should().BeEmpty();
                    (await u.LoginUserAsync(ctx, userName, "toto")).UserId.Should().Be(idU);
                    p.Database.ExecuteScalar($"select 1 from CK.tUserPassword where UserId={idU}")
                    .Should().Be(1);
                    (await u.LoginUserAsync(ctx, userName, "toto")).UserId.Should().Be(idU);
                }
            }
        }
示例#14
0
        public void Google_provider_ignores_AuthProvider_IsEnabled_flag_as_required()
        {
            var provider = TestHelper.StObjMap.Default.Obtain <AuthProviderTable>();
            var u        = TestHelper.StObjMap.Default.Obtain <UserGoogleTable>();
            var user     = TestHelper.StObjMap.Default.Obtain <UserTable>();

            using (var ctx = new SqlStandardCallContext())
            {
                string userName        = "******" + Guid.NewGuid().ToString();
                var    googleAccountId = Guid.NewGuid().ToString("N");
                var    idU             = user.CreateUser(ctx, 1, userName);

                provider.EnableProvider(ctx, 1, "Google", false);
                var info = u.CreateUserInfo <IUserGoogleInfo>();
                info.GoogleAccountId = googleAccountId;
                var created = u.CreateOrUpdateGoogleUser(ctx, 1, idU, info);
                Assert.That(created, Is.EqualTo(CreateOrUpdateResult.Created));
                var loggedId = u.LoginUser(ctx, info, true);
                Assert.That(loggedId, Is.EqualTo(idU));

                provider.EnableProvider(ctx, 1, "Google");
            }
        }
        public async Task <IActionResult> GetIdSchoolOfUser()
        {
            int userId      = _authenticationInfo.ActualUser.UserId;
            var sqlDatabase = _stObjMap.StObjs.Obtain <SqlDefaultDatabase>();

            using (var ctx = new SqlStandardCallContext())
            {
                SchoolQueries    schoolQueries    = new SchoolQueries(ctx, sqlDatabase);
                TimedUserQueries timedUserQueries = new TimedUserQueries(ctx, sqlDatabase);
                GroupQueries     groupQueries     = new GroupQueries(ctx, sqlDatabase);

                GroupData groupData = await groupQueries.GetIdSchoolByConnectUser(userId);

                if (groupData == null || groupData.ParentZoneId == 0)
                {
                    //if user not in school default by school id In'TECH
                    // int idSchool = await groupQueries.GetIdSchoolByName( "IN'TECH" );
                    return(Ok(groupData.ZoneId));
                }

                return(Ok(groupData.ParentZoneId));
            }
        }
示例#16
0
        public async Task <string> Register([FromBody] RegisterModel model)
        {
            var userTable  = _stObjMap.StObjs.Obtain <CustomUserTable>();
            var actorEmail = _stObjMap.StObjs.Obtain <ActorEMailTable>();
            var basic      = _stObjMap.StObjs.Obtain <IBasicAuthenticationProvider>();

            using (var ctx = new SqlStandardCallContext())
            {
                var loginId = Guid.NewGuid().ToString();
                var userId  = await userTable.CreateUserAsync(ctx, 1,
                                                              loginId, model.FirstName, model.LastName);

                if (userId != 0 && userId != 1)
                {
                    await basic.CreateOrUpdatePasswordUserAsync(ctx, 1, userId, model.Password);

                    await actorEmail.AddEMailAsync(ctx, 1, userId, model.Email, true, false);

                    return(loginId);
                }
                return(null);
            }
        }
示例#17
0
        public async Task create_and_destroy_async()
        {
            var tokenStoreTable = TestHelper.StObjMap.StObjs.Obtain <TokenStoreTable>();

            using (var ctx = new SqlStandardCallContext(TestHelper.Monitor))
            {
                var info         = tokenStoreTable.GenerateTestInvitationInfo();
                var createResult = await tokenStoreTable.CreateAsync(ctx, 1, info);

                createResult.Success.Should().BeTrue();
                createResult.TokenId.Should().BeGreaterThan(0);
                createResult.Token.Should().NotBeEmpty();

                var checkResult = await tokenStoreTable.CheckAsync(ctx, 1, createResult.Token);

                checkResult.IsValid().Should().BeTrue();
                checkResult.TokenId.Should().Be(createResult.TokenId);
                checkResult.LastCheckedDate.Should().BeCloseTo(DateTime.UtcNow, TimeSpan.FromMilliseconds(500));
                checkResult.ValidCheckedCount.Should().Be(1);

                await tokenStoreTable.DestroyAsync(ctx, 1, createResult.TokenId);
            }
        }
示例#18
0
        public void when_removing_the_primary_email_the_most_recently_validated_is_elected()
        {
            var user  = TestHelper.StObjMap.Default.Obtain <UserTable>();
            var mails = TestHelper.StObjMap.Default.Obtain <ActorEMailTable>();

            using (var ctx = new SqlStandardCallContext())
            {
                var uId = user.CreateUser(ctx, 1, Guid.NewGuid().ToString());
                for (int i = 0; i < 10; i++)
                {
                    mails.AddEMail(ctx, 1, uId, $"fill{i}@a.com", false, true);
                }
                mails.AddEMail(ctx, 1, uId, "*****@*****.**", false);
                mails.AddEMail(ctx, 1, uId, "*****@*****.**", true);
                System.Threading.Thread.Sleep(100);
                mails.AddEMail(ctx, 1, uId, "*****@*****.**", false, true);
                mails.AddEMail(ctx, 1, uId, "*****@*****.**", false);
                mails.Database.ExecuteScalar($"select PrimaryEMail from CK.vUser where UserId={uId}");
                mails.RemoveEMail(ctx, 1, uId, "*****@*****.**");
                mails.Database.ExecuteScalar($"select PrimaryEMail from CK.vUser where UserId={uId}");
                user.DestroyUser(ctx, 1, uId);
            }
        }
        public async Task CreateStatementLevel_whenAlreadyExistingStatementLevelCode_shouldThrowSqlDetailedException()
        {
            using (var ctx = new SqlStandardCallContext())
            {
                var sLTable = CK.Core.StObjModelExtension.Obtain <StatementLevelTable>(TestHelper.StObjMap.StObjs);

                // #1. Prepares the function that is going to throw the SQLDetailedException.
                Func <Task> act = async() => await sLTable.CreateStatementLevelAsync(ctx, systemId, 0);

                // #2. Retrieves a supposed already-existing Statement Level object.
                // If does NOT exist, creates & insert a new one in database to next throw an
                // Exception by trying to re-insert it. ELSE, just tries to insert it in db.
                var stObj = await ctx[sLTable].Connection.QueryFirstOrDefaultAsync <StdStatementLevelInfo>
                                ("select * from SES.tStatementLevel where [Level] = 0;");
                if (stObj == null)
                {
                    await sLTable.CreateStatementLevelAsync(ctx, systemId, 0);
                }

                // #3. Inserting the foresaid Statement Level Object should throw an SQLDetailedException.
                act.Should().Throw <SqlDetailedException>();
            }
        }
 void AsyncCallCatch <TException>(string cmd, string connectionString = null)
 {
     using (IDisposableSqlCallContext c = new SqlStandardCallContext(TestHelper.Monitor))
         using (var command = new SqlCommand(cmd))
         {
             ISqlConnectionController con = c[connectionString ?? TestHelper.GetConnectionString()];
             try
             {
                 // If the asynchronous process is lost (if the exception is not correctly managed),
                 // this test will fail with a task Cancelled exception after:
                 // - 30 second when testing for connection string.... because when trying to resolve a bad server name it takes a loooooooong time.
                 // - 1 second in other cases.
                 CancellationTokenSource source = new CancellationTokenSource();
                 source.CancelAfter(connectionString == null ? 1000 : 30 * 1000);
                 con.ExecuteNonQueryAsync(command, source.Token)
                 .Wait();
             }
             catch (AggregateException ex)
             {
                 Assert.That(ex.GetBaseException(), Is.InstanceOf <TException>());
             }
         }
 }
        public async Task <IActionResult> ChangeDateOfPeriod([FromBody] PeriodChangeDateModel periodChangeDateModel)
        {
            int userId      = _authenticationInfo.ActualUser.UserId;
            var sqlDataBase = _stObjMap.StObjs.Obtain <SqlDefaultDatabase>();
            var group       = _stObjMap.StObjs.Obtain <CustomGroupTable>();

            using (var ctx = new SqlStandardCallContext())
            {
                TimedPeriodQueries timedPeriod = new TimedPeriodQueries(ctx, sqlDataBase);

                PeriodData period = await timedPeriod.GetPeriodById(periodChangeDateModel.idPeriod);

                await timedPeriod.UpdatePeriodDate(periodChangeDateModel.idPeriod, periodChangeDateModel.begDate, periodChangeDateModel.endDate);

                if (periodChangeDateModel.begDate.Year > period.BegDate.Year || periodChangeDateModel.begDate.Year < period.BegDate.Year)
                {
                    string groupName = periodChangeDateModel.begDate.Year + "-0" + periodChangeDateModel.begDate.Month;

                    await group.Naming.GroupRenameAsync(ctx, userId, periodChangeDateModel.idPeriod, groupName);
                }
                return(Ok());
            }
        }
示例#22
0
        public void destroying_a_user_removes_it_from_all_the_groups_it_belongs_to()
        {
            var map = TestHelper.StObjMap;
            var g   = map.Default.Obtain <GroupTable>();
            var u   = map.Default.Obtain <UserTable>();

            using (var ctx = new SqlStandardCallContext())
            {
                int groupId1 = g.CreateGroup(ctx, 1);
                int groupId2 = g.CreateGroup(ctx, 1);
                int userId   = u.CreateUser(ctx, 1, Guid.NewGuid().ToString());

                g.AddUser(ctx, 1, groupId1, userId);
                g.AddUser(ctx, 1, groupId2, userId);

                u.DestroyUser(ctx, 1, userId);
                g.Database.AssertEmptyReader("select * from CK.tActorProfile where ActorId = @0", userId)
                .AssertEmptyReader("select * from CK.tUser where UserId = @0", userId);

                g.DestroyGroup(ctx, 1, groupId1);
                g.DestroyGroup(ctx, 1, groupId2);
            }
        }
示例#23
0
        public void a_group_can_be_renamed()
        {
            var map = TestHelper.StObjMap;
            var g   = map.Default.Obtain <GroupTable>();
            var gN  = map.Default.Obtain <SimpleNaming.Package>();

            using (var ctx = new SqlStandardCallContext())
            {
                string uniquifierName = Guid.NewGuid().ToString();
                int    groupId        = g.CreateGroup(ctx, 1);
                string name           = gN.GroupRename(ctx, 1, groupId, uniquifierName + "Group");
                name.Should().Be(uniquifierName + "Group");
                g.Database.ExecuteScalar("select GroupName from CK.tGroup where GroupId = @0", groupId)
                .Should().Be(name);
                name = gN.GroupRename(ctx, 1, groupId, uniquifierName + "Another Group");
                name.Should().Be(uniquifierName + "Another Group");
                g.Database.ExecuteScalar("select GroupName from CK.tGroup where GroupId = @0", groupId)
                .Should().Be(name);
                g.DestroyGroup(ctx, 1, groupId);
                g.Database.ExecuteReader("select * from CK.tGroup where GroupId = @0", groupId)
                .Rows.Should().BeEmpty();
            }
        }
示例#24
0
        public void reading_CultureData()
        {
            var p = TestHelper.StObjMap.Default.Obtain <Package>();

            using (var ctx = new SqlStandardCallContext())
            {
                RegisterSampleCultures(p, ctx);
                {
                    var c = p.GetCulture(ctx, 10);
                    c.LCID.Should().Be(10);
                    c.Name.Should().Be("es");
                    c.EnglishName.Should().Be("Spanish");
                    c.NativeName.Should().Be("español");
                }
                {
                    var c = p.GetCulture(ctx, 1);
                    c.LCID.Should().Be(1);
                    c.Name.Should().Be("ar");
                    c.EnglishName.Should().Be("Arabic");
                    c.NativeName.Should().Be("العربية");
                }
            }
        }
示例#25
0
        public void destroying_culture_updates_all_cultures_fallbacks()
        {
            var p = TestHelper.StObjMap.Default.Obtain <Package>();

            using (var ctx = new SqlStandardCallContext())
            {
                CultureTests.RestoreDatabaseToEnglishAndFrenchOnly(p);
                RegisterSpanish(p, ctx);
                RegisterArabic(p, ctx);
                p.GetExtendedCulture(ctx, 12).Fallbacks.Select(c => c.LCID)
                .Should().BeEquivalentTo(new[] { 12, 9, 10, 1 }, o => o.WithStrictOrdering());

                int xlcid12 = p.AssumeXLCID(ctx, new[] { 12, 1, 9, 10 });
                p.GetExtendedCulture(ctx, xlcid12).Fallbacks.Select(c => c.LCID)
                .Should().BeEquivalentTo(new[] { 12, 1, 9, 10 }, o => o.WithStrictOrdering());

                p.DestroyCulture(ctx, 1);
                p.GetExtendedCulture(ctx, xlcid12).Fallbacks.Select(c => c.LCID)
                .Should().BeEquivalentTo(new[] { 12, 9, 10 }, o => o.WithStrictOrdering());
                p.GetExtendedCulture(ctx, 12).Fallbacks.Select(c => c.LCID)
                .Should().BeEquivalentTo(new[] { 12, 9, 10 }, o => o.WithStrictOrdering());
            }
        }
示例#26
0
        public void group_names_are_unique_and_clash_are_atomatically_handled()
        {
            var map = TestHelper.StObjMap;
            var g   = map.Default.Obtain <GroupTable>();
            var gN  = map.Default.Obtain <SimpleNaming.Package>();

            using (var ctx = new SqlStandardCallContext())
            {
                string[] names  = Enumerable.Range(0, 8).Select(i => Guid.NewGuid().ToString() + " - " + i).ToArray();
                int[]    groups = new int[names.Length];
                string   newName;
                for (int i = 0; i < names.Length; ++i)
                {
                    groups[i] = g.CreateGroup(ctx, 1);
                    newName   = gN.GroupRename(ctx, 1, groups[i], names[i]);
                    Assert.That(newName, Is.EqualTo(names[i]));
                }

                // Renaming all of them like the first one:
                for (int i = 1; i < names.Length; ++i)
                {
                    newName = gN.GroupRename(ctx, 1, groups[i], names[0]);
                    Assert.That(newName, Is.EqualTo(names[0] + " (" + i + ")"));
                }

                // Renaming the first one with no change:
                newName = gN.GroupRename(ctx, 1, groups[0], names[0]);
                Assert.That(newName, Is.EqualTo(names[0]));

                // Renaming all of them in the opposite order: no clash.
                for (int i = 0; i < names.Length; ++i)
                {
                    newName = gN.GroupRename(ctx, 1, groups[i], names[names.Length - i - 1]);
                    Assert.That(newName, Is.EqualTo(names[names.Length - i - 1]));
                }
            }
        }
        public void Direct_open_close_of_the_connection_is_possible()
        {
            void DoSomething(SqlConnection con)
            {
                bool wasClosed = con.State == ConnectionState.Closed;

                if (wasClosed)
                {
                    con.Open();
                }
                var cmd = con.CreateCommand();

                cmd.CommandText = "select 1;";
                cmd.ExecuteScalar().Should().Be(1);
                if (wasClosed)
                {
                    con.Close();
                }
            }

            using (var ctx = new SqlStandardCallContext(TestHelper.Monitor))
            {
                ISqlConnectionController c = ctx[TestHelper.GetConnectionString()];

                // Closed.
                DoSomething(c.Connection);
                c.Connection.State.Should().Be(ConnectionState.Closed);

                using (c.ExplicitOpen())
                {
                    c.Connection.State.Should().Be(ConnectionState.Open);
                    DoSomething(c.Connection);
                    c.Connection.State.Should().Be(ConnectionState.Open);
                }
                c.Connection.State.Should().Be(ConnectionState.Closed);
            }
        }
示例#28
0
        public void RefreshToken_and_LastRefreshTokenTime_are_managed()
        {
            var google = TestHelper.StObjMap.Default.Obtain <UserGoogleTable>();
            var user   = TestHelper.StObjMap.Default.Obtain <UserTable>();

            using (var ctx = new SqlStandardCallContext())
            {
                string userName        = "******" + Guid.NewGuid().ToString();
                var    googleAccountId = Guid.NewGuid().ToString("N");
                var    idU             = user.CreateUser(ctx, 1, userName);

                var info = google.CreateUserInfo <IUserGoogleInfo>();
                info.GoogleAccountId = googleAccountId;
                google.CreateOrUpdateGoogleUser(ctx, 1, idU, info);
                string rawSelect = $"select RefreshToken+'|'+cast(LastRefreshTokenTime as varchar) from CK.tUserGoogle where UserId={idU}";
                google.Database.ExecuteScalar(rawSelect)
                .Should().Be("|0001-01-01 00:00:00.00");

                info.RefreshToken = "a refresh token";
                google.CreateOrUpdateGoogleUser(ctx, 1, idU, info);
                rawSelect = $"select RefreshToken from CK.tUserGoogle where UserId={idU}";
                google.Database.ExecuteScalar(rawSelect)
                .Should().Be(info.RefreshToken);

                info = (IUserGoogleInfo)google.FindKnownUserInfo(ctx, googleAccountId).Info;
                info.LastRefreshTokenTime.Should().BeAfter(DateTime.UtcNow.AddMonths(-1));
                info.RefreshToken.Should().Be("a refresh token");

                var lastUpdate = info.LastRefreshTokenTime;
                Thread.Sleep(500);
                info.RefreshToken = null;
                google.CreateOrUpdateGoogleUser(ctx, 1, idU, info);
                info = (IUserGoogleInfo)google.FindKnownUserInfo(ctx, googleAccountId).Info;
                info.LastRefreshTokenTime.Should().Be(lastUpdate);
                info.RefreshToken.Should().Be("a refresh token");
            }
        }
示例#29
0
        public void destroying_actors_suppress_any_related_configurations()
        {
            var map   = TestHelper.StObjMap;
            var acl   = map.Default.Obtain <AclTable>();
            var user  = map.Default.Obtain <UserTable>();
            var group = map.Default.Obtain <GroupTable>();

            using (var ctx = new SqlStandardCallContext())
            {
                int idAcl   = acl.CreateAcl(ctx, 1);
                int idUser  = user.CreateUser(ctx, 1, Guid.NewGuid().ToString());
                int idGroup = group.CreateGroup(ctx, 1);

                group.AddUser(ctx, 1, idGroup, idUser);
                acl.AclGrantSet(ctx, 1, idAcl, idUser, null, 92);
                acl.AclGrantSet(ctx, 1, idAcl, idGroup, null, 64);

                Assert.That(acl.GetGrantLevel(ctx, idUser, idAcl), Is.EqualTo(92));
                Assert.That(acl.GetGrantLevel(ctx, idGroup, idAcl), Is.EqualTo(64));

                acl.AclGrantSet(ctx, 1, idAcl, idGroup, null, 127);
                Assert.That(acl.GetGrantLevel(ctx, idUser, idAcl), Is.EqualTo(127));

                acl.Database.AssertScalarEquals(1, "select count(*) from CK.tAclConfig where AclId = @0 and ActorId=@1", idAcl, idGroup);
                group.DestroyGroup(ctx, 1, idGroup, true);
                acl.Database.AssertEmptyReader("select * from CK.tAclConfig where AclId = @0 and ActorId=@1", idAcl, idGroup);

                Assert.That(acl.GetGrantLevel(ctx, idUser, idAcl), Is.EqualTo(92));

                acl.Database.AssertScalarEquals(1, "select count(*) from CK.tAclConfig where AclId = @0 and ActorId=@1", idAcl, idUser);
                user.DestroyUser(ctx, 1, idUser);
                acl.Database.AssertEmptyReader("select * from CK.tAclConfig where AclId = @0 and ActorId=@1", idAcl, idUser);

                acl.DestroyAcl(ctx, 1, idAcl);
                acl.Database.AssertEmptyReader("select AclId from CK.tAcl where AclId = @0", idAcl);
            }
        }
示例#30
0
        public void removing_a_user_from_a_zone_removes_it_from_all_child_zones()
        {
            var map   = TestHelper.StObjMap;
            var zone  = map.Default.Obtain <ZoneTable>();
            var group = map.Default.Obtain <Zone.GroupTable>();
            var user  = map.Default.Obtain <UserTable>();

            using (var ctx = new SqlStandardCallContext())
            {
                int idUser1  = user.CreateUser(ctx, 1, Guid.NewGuid().ToString());
                int idUser2  = user.CreateUser(ctx, 1, Guid.NewGuid().ToString());
                var allZones = new List <int>();
                allZones.Add(zone.CreateZone(ctx, 1));
                allZones.Add(zone.CreateZone(ctx, 1, allZones[0]));
                allZones.Add(zone.CreateZone(ctx, 1, allZones[1]));
                allZones.Add(zone.CreateZone(ctx, 1, allZones[2]));
                int idGroup = group.CreateGroup(ctx, 1, allZones[3]);

                zone.AddUser(ctx, 1, allZones[3], idUser1, autoAddUserInParentZone: true);
                group.AddUser(ctx, 1, idGroup, idUser2, autoAddUserInZone: true);

                user.Database.AssertScalarEquals(4, "select count(*) from CK.tActorProfile where ActorId <> GroupId and ActorId = @0", idUser1);
                user.Database.AssertScalarEquals(5, "select count(*) from CK.tActorProfile where ActorId <> GroupId and ActorId = @0", idUser2);

                zone.RemoveUser(ctx, 1, allZones[2], idUser2);
                user.Database.AssertScalarEquals(2, "select count(*) from CK.tActorProfile where ActorId <> GroupId and ActorId = @0", idUser2);
                group.RemoveUser(ctx, 1, allZones[1], idUser2);
                user.Database.AssertScalarEquals(1, "select count(*) from CK.tActorProfile where ActorId <> GroupId and ActorId = @0", idUser2);
                group.RemoveUser(ctx, 1, allZones[0], idUser2);
                user.Database.AssertScalarEquals(0, "select count(*) from CK.tActorProfile where ActorId <> GroupId and ActorId = @0", idUser2);

                zone.RemoveUser(ctx, 1, allZones[0], idUser1);
                user.Database.AssertScalarEquals(0, "select count(*) from CK.tActorProfile where ActorId <> GroupId and ActorId = @0", idUser2);

                zone.DestroyZone(ctx, 1, allZones[0], forceDestroy: true);
            }
        }