private BanType Initialize()
        {
            DataAccess.BanType banType;
            using (var db = new CSSDataContext())
            {
                banType = db.BanTypes.FirstOrDefault(p => p.RocNumber == 1);

                if (_initialized)
                    return banType;

                if (db.Logins.FirstOrDefault(p => p.Username == "Admin") == null)
                {
                    //Create new user
                    CreateUser("Admin", "Test", "NA", 10);

                    var admin = Login.FindLoginByUsernameOrCallsign(db, "Admin");
                    admin.Login_Roles.Add(new Login_Role() { RoleId = (int)RoleType.Administrator });
                    admin.Login_Roles.Add(new Login_Role() { RoleId = (int)RoleType.SuperAdministrator });
                }

                db.Bans.DeleteAllOnSubmit(db.Bans);

                var banClass = new BanClass()
                {
                    Id = 1,
                    Name = "Minor"
                };

                db.BanClasses.DeleteAllOnSubmit(db.BanClasses);
                db.BanClasses.InsertOnSubmit(banClass);

                banType = new BanType()
                {
                    BanClassId = 1,
                    BaseTimeInMinutes = 30,
                    Description = "Harassment / Threats",
                    IsIncremental = true,
                    RocNumber = 1
                };

                db.BanTypes.DeleteAllOnSubmit(db.BanTypes);
                db.BanTypes.InsertOnSubmit(banType);

                db.SubmitChanges();
            }

            _initialized = true;

            return banType;
        }
        public void TestPermanentBanCalculations()
        {
            Initialize();

            DataAccess.BanClass banClass = new BanClass()
            {
                Id = (int)BanClassType.Major,
                Name = "Major"
            };

            DataAccess.BanType banType = new BanType()
            {
                BanClass = banClass,
                BanClassId = banClass.Id,
                BaseTimeInMinutes = 30,
                Description = "Permanent ban after one infraction.",
                IsIncremental = true,
                InfractionsBeforePermanentBan = 1,
                SrNumber = 13
            };

            DataAccess.Login testUser = CreateUser(Guid.NewGuid().ToString().Substring(0, 20), "Test", "NA", 10);
            DataAccess.Identity identity = testUser.Identity;

            // Test 1x Ban - 30 minutes
            TimeSpan? duration = Ban.CalculateDuration(identity, banType);
            Assert.AreEqual(30, duration.Value.TotalMinutes);

            // Test 2x Ban - Permanent.
            testUser.Bans.Add(CreateBan(testUser, banType));
            duration = Ban.CalculateDuration(identity, banType);
            Assert.AreEqual(TimeSpan.MaxValue, duration.Value);

            // Test permanent ban on first infraction
            banType = new BanType()
            {
                BanClass = banClass,
                BanClassId = banClass.Id,
                BaseTimeInMinutes = 30,
                Description = "Permanent ban on first infraction.",
                IsIncremental = true,
                InfractionsBeforePermanentBan = 0,
                SrNumber = 9
            };

            testUser = CreateUser(Guid.NewGuid().ToString().Substring(0, 20), "Test", "NA", 10);
            identity = testUser.Identity;

            // Test 1x Ban - Permanent.
            testUser.Bans.Add(CreateBan(testUser, banType));
            duration = Ban.CalculateDuration(identity, banType);
            Assert.AreEqual(TimeSpan.MaxValue, duration.Value);
        }
        private Ban CreateBan(Login user, BanType banType)
        {
            TimeSpan? duration = Ban.CalculateDuration(user.Identity, banType);
            DateTime expirationDate;

            if (duration == TimeSpan.MaxValue)
                expirationDate = SqlDateTime.MaxValue.Value;
            else
                expirationDate = DateTime.Now.Add(duration.Value);

            return new Ban()
            {
                BannedByLoginId = user.Id,
                BanType = banType,
                BanTypeId = banType.Id,
                DateCreated = DateTime.Now,
                DateExpires = expirationDate,
                InEffect = true,
                Login = user
            };
        }
        public void TestMajorBanDurationCalculations()
        {
            Initialize();

            DataAccess.BanClass banClass = new BanClass()
            {
                Id = (int)BanClassType.Major,
                Name = "Major"
            };

            DataAccess.BanType banType = new BanType()
            {
                BanClass = banClass,
                BanClassId = banClass.Id,
                BaseTimeInMinutes = 30,
                Description = "Major 30 minute ban.",
                IsIncremental = true,
                SrNumber = 4
            };

            DataAccess.Login testUser = CreateUser(Guid.NewGuid().ToString().Substring(0, 20), "Test", "NA", 10);
            DataAccess.Identity identity = testUser.Identity;

            // Test 1x Ban - 30 minutes
            TimeSpan? duration = Ban.CalculateDuration(identity, banType);
            Assert.AreEqual(30, duration.Value.TotalMinutes);

            // Test 2x Ban - 120 minutes
            testUser.Bans.Add(CreateBan(testUser, banType));
            duration = Ban.CalculateDuration(identity, banType);
            Assert.AreEqual(120, duration.Value.TotalMinutes);

            // Test 3x Ban - 600 minutes
            testUser.Bans.Add(CreateBan(testUser, banType));
            duration = Ban.CalculateDuration(identity, banType);
            Assert.AreEqual(600, duration.Value.TotalMinutes);

            // Test 4x Minor Ban - 30 days
            testUser.Bans.Add(CreateBan(testUser, banType));
            duration = Ban.CalculateDuration(identity, banType);
            Assert.AreEqual(1440 * 30, duration.Value.TotalMinutes);

            /* TODO: re-add when proper logic is in place.
            // Test 5x Ban - 60 days
            identity.Bans.Add(CreateBan(testUser, banType));
            duration = Ban.CalculateDuration(identity, banType);
            Assert.AreEqual(1440 * 60, duration.Value.TotalMinutes);

            // Test 6x Ban - Permanent
            identity.Bans.Add(CreateBan(testUser, banType));
            duration = Ban.CalculateDuration(identity, banType);
            Assert.AreEqual(1440 * 10, duration.Value.TotalMinutes);
            */

            // test rolling window for major bans.
            testUser.Bans.Clear();
            for (int i = 0; i < 3; i++)
                testUser.Bans.Add(CreateBan(testUser, banType));

            duration = Ban.CalculateDuration(identity, banType);
            Assert.AreEqual(1440 * 30, duration.Value.TotalMinutes);

            // Test rolling window -- 4 recent bans
            testUser.Bans[0].DateCreated = DateTime.Now.AddDays(-180);
            duration = Ban.CalculateDuration(identity, banType);
            Assert.AreEqual(600, duration.Value.TotalMinutes);

            // Test rolling window -- 3 recent bans
            testUser.Bans[1].DateCreated = DateTime.Now.AddDays(-180);
            duration = Ban.CalculateDuration(identity, banType);
            Assert.AreEqual(120, duration.Value.TotalMinutes);

            // Test rolling window -- 2 recent bans
            testUser.Bans[2].DateCreated = DateTime.Now.AddDays(-180);
            duration = Ban.CalculateDuration(identity, banType);
            Assert.AreEqual(30, duration.Value.TotalMinutes);
        }
        public void TestMinorBanDurationCalculations()
        {
            Initialize();

            DataAccess.BanClass minorBanClass = new BanClass()
            {
                Id = (int)BanClassType.Minor,
                Name = "Minor"
            };

            DataAccess.BanType minorBanType = new BanType()
            {
                BanClass = minorBanClass,
                BanClassId = minorBanClass.Id,
                BaseTimeInMinutes = 30,
                Description = "Minor 30 minute ban.",
                IsIncremental = true,
                RocNumber = 1
            };

            DataAccess.Login testUser = CreateUser(Guid.NewGuid().ToString().Substring(0, 20), "Test", "NA", 10);
            DataAccess.Identity identity = testUser.Identity;

            // Test 1x Minor Ban - 30 minutes
            TimeSpan? duration = Ban.CalculateDuration(identity, minorBanType);
            Assert.AreEqual(30, duration.Value.TotalMinutes);

            // Test 2x Minor Ban - 15 hours
            testUser.Bans.Add(CreateBan(testUser, minorBanType));
            duration = Ban.CalculateDuration(identity, minorBanType);
            Assert.AreEqual(900, duration.Value.TotalMinutes);

            // Test 3x Minor Ban - 5 days
            testUser.Bans.Add(CreateBan(testUser, minorBanType));
            duration = Ban.CalculateDuration(identity, minorBanType);
            Assert.AreEqual(7200, duration.Value.TotalMinutes);

            // Test 4x Minor Ban - 5 days
            testUser.Bans.Add(CreateBan(testUser, minorBanType));
            duration = Ban.CalculateDuration(identity, minorBanType);
            Assert.AreEqual(7200, duration.Value.TotalMinutes);

            // Test 5x Minor Ban - 5 days
            testUser.Bans.Add(CreateBan(testUser, minorBanType));
            duration = Ban.CalculateDuration(identity, minorBanType);
            Assert.AreEqual(7200, duration.Value.TotalMinutes);

            // Test 6x Minor Ban - 10 days
            testUser.Bans.Add(CreateBan(testUser, minorBanType));
            duration = Ban.CalculateDuration(identity, minorBanType);
            Assert.AreEqual(1440 * 10, duration.Value.TotalMinutes);

            // TODO: re-add when proper logic is in place.
            //// Test 7x Minor Ban - 30 days
            //identity.Bans.Add(CreateBan(testUser, minorBanType));
            //duration = Ban.CalculateDuration(identity, minorBanType);
            //Assert.AreEqual(1440 * 30, duration.Value.TotalMinutes);

            //// Test 8x Minor Ban - 90 days
            //identity.Bans.Add(CreateBan(testUser, minorBanType));
            //duration = Ban.CalculateDuration(identity, minorBanType);
            //Assert.AreEqual(1440 * 90, duration.Value.TotalMinutes);

            //// Test 9x Minor Ban - 90 days
            //identity.Bans.Add(CreateBan(testUser, minorBanType));
            //duration = Ban.CalculateDuration(identity, minorBanType);
            //Assert.AreEqual(1440 * 90, duration.Value.TotalMinutes);

            // test rolling window for minor bans.
            testUser.Bans.Clear();
            for(int i = 0; i < 5; i++)
                testUser.Bans.Add(CreateBan(testUser, minorBanType));

            Assert.AreEqual(5, identity.Bans.Count());

            // Test rolling window -- 4 recent bans == 5 days
            testUser.Bans[0].DateCreated = DateTime.Now.AddDays(-91);
            duration = Ban.CalculateDuration(identity, minorBanType);
            Assert.AreEqual(7200, duration.Value.TotalMinutes);

            // Test rolling window -- 3 recent bans == 5 days
            testUser.Bans[1].DateCreated = DateTime.Now.AddDays(-91);
            duration = Ban.CalculateDuration(identity, minorBanType);
            Assert.AreEqual(7200, duration.Value.TotalMinutes);

            // Test rolling window -- 2 recent bans == 5 days
            testUser.Bans[2].DateCreated = DateTime.Now.AddDays(-91);
            duration = Ban.CalculateDuration(identity, minorBanType);
            Assert.AreEqual(7200, duration.Value.TotalMinutes);

            // Test rolling window -- 1 recent ban == 15 hours
            testUser.Bans[3].DateCreated = DateTime.Now.AddDays(-91);
            duration = Ban.CalculateDuration(identity, minorBanType);
            Assert.AreEqual(900, duration.Value.TotalMinutes);

            // Test rolling window -- 0 recent bans == 30 minutes
            testUser.Bans[4].DateCreated = DateTime.Now.AddDays(-91);
            duration = Ban.CalculateDuration(testUser.Identity, minorBanType);
            Assert.AreEqual(30, duration.Value.TotalMinutes);
        }
 partial void UpdateBanType(BanType instance);
 partial void DeleteBanType(BanType instance);
 partial void InsertBanType(BanType instance);
		private void detach_BanTypes(BanType entity)
		{
			this.SendPropertyChanging();
			entity.BanClass = null;
		}
		private void attach_BanTypes(BanType entity)
		{
			this.SendPropertyChanging();
			entity.BanClass = this;
		}
        //public Login BanningLogin
        //{
        //    get { this.
        //}
        /// <summary>
        /// Calculate how long a person's ban will be based on the reason and who they are.
        /// http://web.archive.org/web/20070129051419/http://www.allegacademy.org/proposedbantime.shtml
        /// </summary>
        public static TimeSpan? CalculateDuration(Identity user, BanType banType)
        {
            TimeSpan? duration  = TimeSpan.MinValue;
            var days = banType.BanClass.Id == (int) Enumerations.BanClassType.Major ? 180 : 90;

            var recentBans = from b in user.Bans
                             where b.DateCreated > DateTime.Now.AddDays(-days)
                                && b.BanType != null
                                && b.BanType.BanClassId == banType.BanClassId
                             select b;

            var sameOffenses = from b in recentBans
                               where b.BanTypeId == banType.Id
                               select b;

            //Get # of the same infractions; Adding 1 for this instance
            var likeInfractions = sameOffenses.Count() + 1;
            var minutes = banType.BaseTimeInMinutes;

            //2nd or more infraction
            if(likeInfractions >= 2)
            {
                if (banType.BanClassId == (int)Enumerations.BanClassType.Minor)
                    minutes = (int)Math.Pow(banType.BaseTimeInMinutes, 2);
                else //Major
                    minutes = banType.BaseTimeInMinutes * 4;

                //Third or more infraction
                if(likeInfractions >= 3)
                {
                    if (banType.BanClassId == (int)Enumerations.BanClassType.Minor)
                        minutes *= 8;
                    else //Major
                        minutes *= 5;
                }
            }

            duration = TimeSpan.FromMinutes(minutes);

            //Calculate number of total infractions for this class; Adding 1 for this instance
            var totalInfractions = recentBans.Count() + 1;

            //If this is a minor ban, check if user has >= 6 minor bans
            if (banType.BanClassId == (int)Enumerations.BanClassType.Minor && (totalInfractions % 6 == 0))
            {
                switch (totalInfractions)
                {
                    case 6: //First-time habitual offender = 10 days
                        duration = TimeSpan.FromDays(10);
                        break;

                    case 12: //Second-time habitual offender = 30 days
                        duration = TimeSpan.FromDays(30);
                        break;

                    default: //Third or more time habitual offender = 90 days
                        duration = TimeSpan.FromDays(90);
                        break;
                }
            }

            //If this is a major ban, check if user has >= 4 major bans
            else if (banType.BanClassId == (int)Enumerations.BanClassType.Major && (totalInfractions % 4 == 0))
            {
                switch (totalInfractions)
                {
                    case 4: //First-time habitual offender = 30 days
                        duration = TimeSpan.FromDays(30);
                        break;

                    case 8: //Second-time habitual offender = 60 days
                        duration = TimeSpan.FromDays(60);
                        break;

                    default: //Third or more time habitual offender, results in permanent ban
                        duration = null;
                        break;
                }
            }

            // Check if the ban is permanent.
            if (banType.InfractionsBeforePermanentBan != null && totalInfractions > banType.InfractionsBeforePermanentBan.Value)
            {
                duration = TimeSpan.MaxValue;
            }

            return duration;
        }
        private void CreateTestData(out Login login1, out Login login2, out Login login3)
        {
            using (var db = new CSSDataContext())
            {
                ClearDataForCallsign("User1");
                ClearDataForCallsign("User2");
                ClearDataForCallsign("User3");
                //ClearDataForCallsign("User4");

                login1 = CreateUser("User1", "Password1", "*****@*****.**", 10);
                login2 = CreateUser("User2", "Password2", "*****@*****.**", 20);
                login3 = CreateUser("User3", "Password3", "*****@*****.**", 13); // User1 and 3 should have some duplicate IPs
                //login4 = CreateUser("User4", "Password4", "*****@*****.**");

                BanType banType = db.BanTypes.FirstOrDefault();

                if (banType == null)
                {
                    var banClass = new BanClass()
                    {
                        Name = "Auto"
                    };

                    db.BanClasses.InsertOnSubmit(banClass);
                    db.SubmitChanges();

                    banType = new BanType()
                    {
                        //BanClass = banClass,
                        BanClassId = banClass.Id,
                        BaseTimeInMinutes = 30,
                        Description = "Harassment / Threats",
                        IsIncremental = true,
                        RocNumber = 1
                    };

                    db.BanTypes.InsertOnSubmit(banType);
                    db.SubmitChanges();
                }

                db.Bans.InsertOnSubmit(new Ban()
                {
                    BannedByLoginId = 1,
                    //BanType = banType,
                    BanTypeId = banType.Id,
                    DateCreated = DateTime.Now,
                    DateExpires = DateTime.Now.AddDays(1),
                    InEffect = true,
                    Reason = "Pork Muffins!",
                    LoginId = login2.Id
                });

                db.SubmitChanges();

                db.Bans.InsertOnSubmit(new Ban()
                {
                    BannedByLoginId = 1,
                    //BanType = banType,
                    BanTypeId = banType.Id,
                    DateCreated = DateTime.Now.AddDays(-30),
                    DateExpires = DateTime.Now.AddDays(-29),
                    InEffect = false,
                    Reason = "Old ban.",
                    LoginId = login2.Id,
                });

                db.SubmitChanges();

                MachineRecordType machineRecordType = db.MachineRecordTypes.FirstOrDefault();

                if (machineRecordType == null)
                {
                    machineRecordType = new MachineRecordType()
                    {
                        Id = 1,
                        Name = "Network"
                    };

                    db.MachineRecordTypes.InsertOnSubmit(machineRecordType);

                    machineRecordType = new MachineRecordType()
                    {
                        Id = 2,
                        Name = "HardDisk"
                    };

                    machineRecordType = new MachineRecordType()
                    {
                        Id = 3,
                        Name = "EDID"
                    };

                    machineRecordType = new MachineRecordType()
                    {
                        Id = 4,
                        Name = "Serial"
                    };

                    machineRecordType = new MachineRecordType()
                    {
                        Id = 5,
                        Name = "Misc"
                    };

                    db.MachineRecordTypes.InsertOnSubmit(machineRecordType);

                    db.SubmitChanges();
                }

                db.MachineRecords.InsertOnSubmit(new MachineRecord()
                {
                    DeviceType = Allegiance.CommunitySecuritySystem.Common.Envelopes.AuthInfo.DeviceType.HardDisk,
                    Identifier = "1234567890",
                    LoginId = login3.Id,
                    RecordTypeId = (int)Allegiance.CommunitySecuritySystem.Common.Envelopes.AuthInfo.DeviceType.HardDisk
                });

                db.SubmitChanges();

                db.MachineRecords.InsertOnSubmit(new MachineRecord()
                {
                    DeviceType = Allegiance.CommunitySecuritySystem.Common.Envelopes.AuthInfo.DeviceType.Serial,
                    Identifier = "ABCDEFGHIJKLMNOP",
                    LoginId = login3.Id,
                    RecordTypeId = (int)Allegiance.CommunitySecuritySystem.Common.Envelopes.AuthInfo.DeviceType.Serial
                });

                db.SubmitChanges();

                Poll poll = db.Polls.FirstOrDefault();
                PollOption pollOption1 = null;

                if (poll == null)
                {
                    poll = new Poll()
                    {
                        DateCreated = DateTime.Now,
                        DateExpires = DateTime.Now.AddDays(30),
                        Question = "This is the question.",
                        LastRecalculation = DateTime.Now
                    };

                    db.Polls.InsertOnSubmit(poll);
                    db.SubmitChanges();

                    pollOption1 = new PollOption()
                    {
                        Option = "Option 1",
                        PollId = poll.Id,
                        VoteCount = 0
                    };

                    db.PollOptions.InsertOnSubmit(pollOption1);
                    db.SubmitChanges();
                }
                else
                {
                    pollOption1 = db.PollOptions.First();
                }

                db.PollVotes.InsertOnSubmit(new PollVote()
                {
                    LoginId = login3.Id,
                    PollOptionId = pollOption1.Id
                });

                db.SubmitChanges();
            }
        }