Ejemplo n.º 1
0
        private MemberInfo[] GetRelationMembers <T>(T entity)
        {
            if (entity == null)
            {
                // No need to go further if the entity passed is null.
                return(new MemberInfo[] { });
            }

            // Get all fields and properties of entity passed.
            Type entityType = entity.GetType();
            IList <MemberInfo> relationMembers = new List <MemberInfo>();

            MemberInfo[] members = entityType.GetFields().Cast <MemberInfo>().Concat(entityType.GetProperties()).ToArray();

            // Populate list with members that correspond to relationship between entities.
            foreach (MemberInfo member in members)
            {
                Type type = GetMemberType(member);

                if (DbContextUtils.IsEntity(currentContext, type))
                {
                    // If it's an entity type, it's a relationship member.
                    relationMembers.Add(member);
                }
            }
            return(relationMembers.ToArray());
        }
Ejemplo n.º 2
0
        public async Task OnGet()
        {
            var client = _factory.CreateClient();

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Test");
            var pollPage = await client.GetAsync("/Poll/1");

            var pollHtml = await pollPage.Content.ReadAsStringAsync();

            var cookieToken = AntiForgeryUtils.ExtractCookieToken(pollPage.Headers);
            var formToken   = AntiForgeryUtils.ExtractFormToken(pollHtml, "test_csrf_field");

            var request = new HttpRequestMessage(HttpMethod.Post, "/Poll/1");

            request.Content = new FormUrlEncodedContent(new[] {
                new KeyValuePair <string, string>("counterId", "1"),
                new KeyValuePair <string, string>("test_csrf_field", formToken)
            });
            request.Headers.Add("Cookie", $"test_csrf_cookie={cookieToken}");
            var response = await client.SendAsync(request);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            DbContextUtils.ActionDatabase(_factory.Services, ctx =>
            {
                BaseVotingTests.AssertVotedForCounter(ctx, "*****@*****.**", 1);
            });
        }
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            base.ConfigureWebHost(builder);
            builder.ConfigureServices(services =>
            {
                services.AddAuthentication("Test")
                .AddScheme <AuthenticationSchemeOptions, AuthMock>("Test", _ => { });

                services.AddAntiforgery(setup =>
                {
                    setup.Cookie.Name   = "test_csrf_cookie";
                    setup.FormFieldName = "test_csrf_field";
                });

                DbContextUtils.ActionDatabase(services.BuildServiceProvider(), ctx =>
                {
                    ctx.VotingPolls.Add(new VotingPoll
                    {
                        Title       = "title",
                        Description = "desc",
                        Counters    = new List <Counter> {
                            new Counter {
                                Name = "One"
                            },
                            new Counter {
                                Name = "Two"
                            }
                        }
                    });
                    ctx.SaveChanges();
                });
            });
        }
Ejemplo n.º 4
0
        private bool AreTheseEntitiesTheSame <T1, T2>(T1 entityStateManager, T2 entityCache)
        {
            // If any or both of the entities passed are null,
            if (entityStateManager == null || entityCache == null)
            {
                // Return false to indicate they are not equal.
                return(false);
            }

            // Get the values of primary keys of both the entities.
            object pkValEntStateManager = DbContextUtils.GetPrimaryKeyValue(currentContext, entityStateManager);
            object pkValEntCache        = DbContextUtils.GetPrimaryKeyValue(currentContext, entityCache);

            // If successfully got the values for primary keys of both the entities,
            if (pkValEntStateManager != null && pkValEntCache != null)
            {
                // Return their value comparison.
                return(pkValEntStateManager.Equals(pkValEntCache));
            }

            /*
             * Otherwise, compare both entities via reflection.
             */
            if (!FieldCompare(entityStateManager, entityCache))
            {
                /*
                 * Satisfaction of this if-condition could mean any of
                 * the following,
                 *
                 *      01. 'entityCache's values for fields were not
                 *          the same as that of 'entityStateManager'.
                 *
                 *      02. 'entityCache' was not the same as
                 *          'entityStateManager'.
                 */
                return(false);
            }
            if (!PropertyCompare(entityStateManager, entityCache))
            {
                /*
                 * Satisfaction of this if-condition could mean any of
                 * the following,
                 *
                 *      01. 'entityCache's values for properties were not
                 *          the same as that of 'entityStateManager'.
                 *
                 *      02. 'entityCache' was not the same as
                 *          'entityStateManager'.
                 */
                return(false);
            }

            // Reaching here means both the entities are the same.
            return(true);
        }
Ejemplo n.º 5
0
 public void Dispose()
 {
     foreach (string contextName in _contextNames)
     {
         var options = DbContextUtils.GetContextOptions(contextName);
         using (var context = new BAUDbContext(options))
         {
             context.Database.EnsureDeleted();
         }
     }
 }
Ejemplo n.º 6
0
        public void FindEngineersAvailableOn_WEEK_SCAN_PERIOD_Error()
        {
            string contextName = "FindEngineersAvailableOn_WEEK_SCAN_PERIOD_Error";

            _contextNames.Add(contextName);
            DbContextOptions <BAUDbContext> options = DbContextUtils.GetContextOptions(contextName);

            using (var context = new BAUDbContext(options))
            {
                try
                {
                    new ShiftRepository(context, ConfigurationTestBuilder.GetConfiguration("WEEK_SCAN_PERIOD"));
                }
                catch (ArgumentNullException ex)
                {
                    Assert.Equal("App:WEEK_SCAN_PERIOD", ex.ParamName);
                }
            }
        }
Ejemplo n.º 7
0
        public void FindEngineersAvailableOn_MAX_SHIFT_SUM_HOURS_DURATION_Error()
        {
            string contextName = "FindEngineersAvailableOn_MAX_SHIFT_SUM_HOURS_DURATION_Error";

            _contextNames.Add(contextName);
            DbContextOptions <BAUDbContext> options = DbContextUtils.GetContextOptions(contextName);

            using (var context = new BAUDbContext(options))
            {
                try
                {
                    new ShiftRepository(context, ConfigurationTestBuilder.GetConfiguration("MAX_SHIFT_SUM_HOURS_DURATION"));
                }
                catch (ArgumentNullException ex)
                {
                    Assert.Equal("App:MAX_SHIFT_SUM_HOURS_DURATION", ex.ParamName);
                }
            }
        }
Ejemplo n.º 8
0
        private bool PropertyCompare <T1, T2>(T1 first, T2 second)
        {
            // If any or both of the objects passed are null,
            if (first == null || second == null)
            {
                // Return false to indicate they are not equal.
                return(false);
            }

            Type         typeFirst    = first.GetType();
            Type         typeSecond   = second.GetType();
            BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

            /*
             * Confirming first's properties with second's only.
             */
            foreach (PropertyInfo propertyFirst in typeFirst.GetProperties())
            {
                PropertyInfo propertySecond = typeSecond.GetProperty(propertyFirst.Name, bindingFlags);

                if (propertySecond == null)
                {
                    // Satisfaction of this if-condition means that 'entityCache' did not contain
                    // the field under study.
                    return(false);
                }
                if (DbContextUtils.IsEntity(currentContext, propertyFirst.DeclaringType) || propertyFirst.DeclaringType == typeof(HashSet <>))
                {
                    // Ignore checking if the property under question is an entity or a hashset (one-to-many relationship).
                    continue;
                }
                if (!propertyFirst.GetValue(first).Equals(propertySecond.GetValue(second)))
                {
                    // Return false upon first mismatch of any property.
                    return(false);
                }
            }
            return(true);
        }
Ejemplo n.º 9
0
        //---------------------------------------------------------------------------------------------------------------------------------------------------

        internal bool EntityComparer <T1, T2>(T1 entityStateManager, T2 entityCache)
        {
            /*  -----------------------------------------------------------------------
             *  NOTE: Returning 'false' means the two entities are not equal (or same).
             *  -----------------------------------------------------------------------
             */
            if (entityStateManager == null || entityCache == null)
            {
                // If one of them or both are null, they are not equal.
                // (They're same if they're both null though but still)
                return(false);
            }
            if (entityStateManager.GetType() != entityCache.GetType())
            {
                // If their types do not match, they're not the same entites.
                return(false);
            }
            if (Convert.GetTypeCode(entityStateManager) != TypeCode.Object)
            {
                // If entity is not an object, it means it's not an entity but
                // a value of some property. Return the comparison of the two then.
                return(entityStateManager.Equals(entityCache));
            }
            if (!DbContextUtils.IsEntity(currentContext, entityStateManager) || !DbContextUtils.IsEntity(currentContext, entityCache))
            {
                // If any or both the objects passed are not entities, don't go further.
                return(false);
            }
            if (AreTheseEntitiesTheSame(entityStateManager, entityCache))
            {
                // Handle relations here
                UpdateOneToManyRelations(entityStateManager, entityCache);
                UpdateOneToOneRelations(entityStateManager, entityCache);
                return(true);
            }
            return(false);
        }
Ejemplo n.º 10
0
        public PostgreContext()
            : base("PyroConnectionString")
        {
            //To obtain a new SQL migration script for a database upgrade follow these steps:
            //-----------------------------------------------------------------------------------
            //1. Set Pyro.ConsoleServer as the StartUp project
            //2. Set the 'GenerateMigration' boolean below to True
            //3. Open the Package Manager Console under the tools menu in Visual Studio
            //4. Set the 'Default Project' drop-down in the Package Manager Console to 'Pyro.DataLayer'
            //5. Run the following command to create a new Migration class:
            //     Add -Migration -Name [Migration Name] -ConfigurationTypeName ConfigurationPostgre
            //6. Run the following command generate the SQL script based on the Migration class:
            //     Update-Database -TargetMigration [Migration Name] -Script -ConfigurationTypeName ConfigurationPostgre
            //7. Copy the generated SQL script into a new file in the project Pyro.DbManager under the folder 'SqlScripts\PostgreSql,
            //   use the same file name as that generated Migration class, only changing the extension from .cs to .sql'
            //8. Set the Build Action of the new .sql file in the Pyro.DbManager project to 'Embedded Resource'
            //9. Set the 'GenerateMigration' boolean below back to False.
            //10. Run the Pyro.DbManager project to upgrade the database.
            //-----------------------------------------------------------------------------------

            bool GenerateMigration = false;

            if (GenerateMigration)
            {
                if (!System.Diagnostics.Debugger.IsAttached)
                {
                    throw new System.ApplicationException("Oh no, the developer has left a development only setting of 'GenerateMigration' for Microsoft SQL Server as True and this code appears to be running outside of the development environment. " +
                                                          "Unfortunately this is not allowed. Please contact your system administrator.");
                }
                DbContextUtils <PostgreContext> .SetInitializer(new MigrateDatabaseToLatestVersion <PostgreContext, MigrationsPostgre.ConfigurationPostgre>());
            }
            else
            {
                Database.SetInitializer <PostgreContext>(null);
            }
        }
Ejemplo n.º 11
0
 public PyroDbContext()
     : base("PyroConnectionString")
 {
     //Below is only commented out for LinqPad Debug testing
     DbContextUtils <PyroDbContext> .SetInitializer(new MigrateDatabaseToLatestVersion <PyroDbContext, Migrations.Configuration>());
 }
Ejemplo n.º 12
0
        public void FindEngineersAvailableOn_Check_Consecutive_Days(DateTime date, int nEngineers)
        {
            string contextName = $"FindEngineersAvailableOn_Check_Consecutive_Days";

            _contextNames.Add(contextName);
            DbContextOptions <BAUDbContext> options = DbContextUtils.GetContextOptions(contextName);
            IShiftRepository repository             = null;
            const int        shiftDuration          = 4;

            // fake data
            using (BAUDbContext context = new BAUDbContext(options))
            {
                var engineer1 = new Engineer {
                    Name = "1"
                };
                var engineer2 = new Engineer {
                    Name = "2"
                };
                var engineer3 = new Engineer {
                    Name = "3"
                };
                var engineer4 = new Engineer {
                    Name = "4"
                };
                var engineer5 = new Engineer {
                    Name = "5"
                };
                var engineer6 = new Engineer {
                    Name = "6"
                };
                var engineer7 = new Engineer {
                    Name = "7"
                };
                var engineer8 = new Engineer {
                    Name = "8"
                };
                var engineer9 = new Engineer {
                    Name = "9"
                };
                var engineer10 = new Engineer {
                    Name = "10"
                };
                var engineersList = new List <Engineer>
                {
                    engineer1, engineer2, engineer3, engineer4,
                    engineer5, engineer6, engineer7, engineer8,
                    engineer9, engineer10,
                };

                context.Engineers.AddRange(engineersList);

                var today  = new DateTime(2017, 12, 11);
                var shifts = new List <EngineerShift>
                {
                    //first week
                    new EngineerShift {
                        Date = today.Date, Duration = shiftDuration, Engineer = engineer1
                    },
                    new EngineerShift {
                        Date = today.Date, Duration = shiftDuration, Engineer = engineer2
                    },
                    new EngineerShift {
                        Date = today.Date.AddDays(1), Duration = shiftDuration, Engineer = engineer7
                    },
                    new EngineerShift {
                        Date = today.Date.AddDays(2), Duration = shiftDuration, Engineer = engineer3
                    },
                    new EngineerShift {
                        Date = today.Date.AddDays(2), Duration = shiftDuration, Engineer = engineer4
                    },
                    new EngineerShift {
                        Date = today.Date.AddDays(4), Duration = shiftDuration, Engineer = engineer5
                    },
                    new EngineerShift {
                        Date = today.Date.AddDays(4), Duration = shiftDuration, Engineer = engineer6
                    },
                };

                context.EngineersShifts.AddRange(shifts);
                context.SaveChanges();
            }

            // test
            using (var context = new BAUDbContext(options))
            {
                repository = new ShiftRepository(context, ConfigurationTestBuilder.GetConfiguration());
                IList <Engineer> availableEngineers = repository.FindEngineersAvailableOn(date);
                Assert.Equal(nEngineers, availableEngineers.Count);
            }
        }
Ejemplo n.º 13
0
 public LicenseContext() : base("BGLicenseContext")
 {
     //Использовать автоматическую миграцию не совсем целесообразно при первой инициализации БД, т.к. она зависит от назначения БД (разработка, тестирование, продакшен)
     //Database.SetInitializer(new CronInitializer());
     DbContextUtils <LicenseContext> .SetInitializer(new ContextInitializer());
 }
 private static CommerceDbContext CreateCommerceDbContext(string connStr) => DbContextUtils.Create <CommerceDbContext>(connStr, o => new CommerceDbContext(o));