Example #1
0
        public ActionResult Index()
        {
            string userId = User.Identity.GetUserId();
            List <UserRelationShip> userRels = new List <UserRelationShip>();

            using (var entDb = new EntityDbContext())
            {
                var relationships = from ur in entDb.UserRelationShips
                                    where ur.followerId == userId
                                    select ur;
                int rels = relationships.Count();
                userRels = relationships.ToList();
            }

            //not efficient, but here we go ...
            List <AspNetUser> usersFollowing = new List <AspNetUser>();

            using (var entDb = new EntityDbContext())
            {
                foreach (UserRelationShip rel in userRels)
                {
                    usersFollowing.Add(entDb.AspNetUsers.Find(rel.followingId));
                }
            }

            return(View(usersFollowing));
        }
Example #2
0
 public void LoadFieldsDefinition(EntityDbContext dc)
 {
     if (Fields == null)
     {
         Fields = dc.FieldInBundle.Where(x => x.BundleId == BundleId).ToList();
     }
 }
        public JsonResult GetAverages(string from, string to)
        {
            var code = RouteData.Values["id"];


            List <double> averages = new List <double>();
            List <String> dates    = new List <String>();

            try
            {
                if (code != null)
                {
                    using (EntityDbContext db = new EntityDbContext())
                    {
                        //If date range has been changed
                        if (from != null && to != null)
                        {
                            var temp = db.Postions.Where(x => x.CurrencyCode == code).ToList();

                            DateTime dateFrom = new DateTime();
                            DateTime dateTo   = new DateTime();

                            DateTime.TryParse(from, out dateFrom);
                            DateTime.TryParse(to, out dateTo);


                            for (int i = 0; i < temp.Count; i++)
                            {
                                if (temp[i].Date.Date >= dateFrom.Date && temp[i].Date.Date <= dateTo.Date)
                                {
                                    averages.Add(temp[i].Average);
                                    dates.Add(temp[i].Date.ToString("yyyy-MM-dd"));
                                }
                            }
                        }
                        //On document load where all dates are required
                        else
                        {
                            averages = db.Postions.Where(x => x.CurrencyCode == code).Select(x => x.Average).ToList();
                            if (averages.Count > 0)
                            {
                                var tempData = db.Postions.Where(x => x.CurrencyCode == code).Select(x => x.Date).ToList();
                                for (int i = 0; i < tempData.Count; i++)
                                {
                                    dates.Add(tempData[i].ToString("yyyy-MM-dd"));
                                }
                            }
                        }

                        return(Json(new { data = averages, x = dates }, JsonRequestBehavior.AllowGet));
                    }
                }
                //if in some case, there was no id in route, it sends back null
                return(Json(null, JsonRequestBehavior.AllowGet));
            }
            catch (Exception)
            {
                return(Json(new { Error = "Błąd połączenia" }, JsonRequestBehavior.AllowGet));
            }
        }
Example #4
0
        private static void ProcessSqlFiles(ref EntityDbContext context, string path, string query)
        {
            var files   = Directory.GetFiles(path).Select(Path.GetFileNameWithoutExtension).ToList();
            var objects = context.Database.SqlQuery <string>(query).ToList();
            var updates = files.Except(objects);

            foreach (var update in updates)
            {
                foreach (var statement in GetSqlStatements($"{path}/{update}.sql"))
                {
                    if (!string.IsNullOrWhiteSpace(statement))
                    {
                        if (statement.Contains("FULLTEXT"))
                        {
                            using (var conn = new SqlConnection(context.Database.Connection.ConnectionString))
                            {
                                conn.Open();
                                using (var cmd = new SqlCommand(statement, conn))
                                {
                                    cmd.ExecuteNonQuery();
                                }
                            }
                        }
                        else
                        {
                            context.Database.ExecuteSqlCommand(statement);
                        }
                    }
                }
            }
        }
 public BaseApplication(
     IEmailSender _emailSender,
     LocalDbContext _ldbc,
     EntityDbContext _edbc,
     ExamsDbContext _xdbc,
     IModuleRepo _moduleRepo,
     IAppDetails _app,
     IModuleMarkRepo _moduleMarkRepo,
     IModuleMarkChangeLogRepo _moduleMarkChangeLogRepo,
     ICMPMarksImportRepo _cmpMarksImportRepo,
     TestDbContext _tdbc,
     IStudentRepo _studentRepo
     )
 {
     emailSender             = _emailSender;
     ldbc                    = _ldbc;
     edbc                    = _edbc;
     tdbc                    = _tdbc;
     xdbc                    = _xdbc;
     moduleRepo              = _moduleRepo;
     moduleMarkRepo          = _moduleMarkRepo;
     moduleMarkChangeLogRepo = _moduleMarkChangeLogRepo;
     app = _app;
     cmpMarksImportRepo = _cmpMarksImportRepo;
     //Test cases
     studentRepo = _studentRepo;
 }
Example #6
0
        public static async Task LogLoginAttempt(HttpRequestBase request, string loginName, Guid?userGuid = null, bool lockedOut = false, bool twoFactorChallenge = false, bool twoFactorVerified = false)
        {
            try
            {
                using (var context = new EntityDbContext())
                {
                    LoginEntityModel login = new LoginEntityModel
                    {
                        UserGuid           = userGuid,
                        LoginName          = loginName,
                        UserAgent          = request.UserAgent,
                        UserHostAddress    = request.UserHostAddress,
                        UserHostName       = request.UserHostName,
                        AccountLockedOut   = lockedOut,
                        TwoFactorChallenge = twoFactorChallenge,
                        TwoFactorVerified  = twoFactorVerified,
                        LoginAttemptDt     = DateTimeOffset.UtcNow
                    };

                    context.Entry(login).State = System.Data.Entity.EntityState.Added;

                    await context.SaveChangesAsync();
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);

                throw;
            }
        }
Example #7
0
        public static IEnumerable <SelectListItem> RequestTypeSelectItems(Guid?shopGuid = null)
        {
            // Load Cache.
            var requestTypes = System.Web.HttpContext.Current?.Cache?[RequestTypeCacheKey] as List <SelectListItem>;

            // Check Cache.
            if (requestTypes?.Any() ?? false)
            {
                return(FilterRequestTypes(requestTypes, shopGuid));
            }

            using (var context = new EntityDbContext())
            {
                // Load List From Database.
                requestTypes = context.ScanRequestTypes?.Where(t => t.ActiveFlag)
                               .OrderBy(t => t.SortOrder)
                               .Where(x => x.RequestTypeId != 6 && x.RequestTypeId != 7) // Exclude Self Scan & Scan Analysis.
                               .Select(t => new SelectListItem {
                    Value = t.RequestTypeId.ToString(), Text = t.TypeName
                })
                               .ToList();
            }

            // Save to Cache.
            if ((requestTypes?.Any() ?? false) && System.Web.HttpContext.Current?.Cache != null)
            {
                System.Web.HttpContext.Current.Cache[RequestTypeCacheKey] = requestTypes;
            }

            // Return.
            return(FilterRequestTypes(requestTypes, shopGuid));
        }
Example #8
0
        public static void SeedDefaults(ref EntityDbContext context)
        {
            // Update Default System User.
            context.Users.AddOrUpdate(
                u => u.UserName,
                new UserEntityModel
            {
                UserName          = "******",
                Email             = "*****@*****.**",
                FirstName         = "AirPro",
                LastName          = "System",
                JobTitle          = "System Account",
                SecurityStamp     = Guid.NewGuid().ToString("D"),
                LockoutEnabled    = true,
                LockoutEndDateUtc = DateTime.MaxValue
            });

            context.SaveChanges();

            SetPaymentTypes(context);

            SetRequestCategories(context);

            SetCurrencies(context);

            SetNotificationTemplates(context);
        }
Example #9
0
        public static void CreateViews(ref EntityDbContext context)
        {
            var path  = $"{Assembly.GetExecutingAssembly().GetExecutingAssemblyPath()}/Views";
            var query = "SELECT TABLE_SCHEMA + '.' + TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS";

            ProcessSqlFiles(ref context, path, query);
        }
Example #10
0
        public async Task <bool> CreateAsync(PerfilView dados)
        {
            using (var context = new EntityDbContext())
            {
                try
                {
                    var perfilmodel = new Perfil();

                    perfilmodel.Nome            = dados.Nome.ToString();
                    perfilmodel.Descricao       = dados.Descricao.ToString();
                    perfilmodel.DataCriacao     = DateTime.Now;
                    perfilmodel.DataAtualizacao = DateTime.Now;

                    await context.Perfildbset.AddAsync(perfilmodel);

                    await context.SaveChangesAsync();

                    return(true);
                }
                catch
                {
                    return(false);
                }
            }
        }
 public void InitializeDatabase_HasNoSideEffects()
 {
     var dbInitializer = new BrownfieldDbInitializer();
     var dbContext = new EntityDbContext();
     dbInitializer.InitializeDatabase(dbContext);
     dbContext.ShouldNotBeNull();
 }
        public static void SaveFacetValues <TEntity>(this TEntity entity, EntityDbContext entityDbContext)
            where TEntity : IEntity, IExtensible
        {
            var FacetData = entity.FindExtension <EntityFacetData>();

            if (FacetData == null)
            {
                return;
            }

            var FacetValueSet = entityDbContext.GetDataSet <FacetValue>();

            foreach (var key in FacetData.FacetValues.Keys.ToList())
            {
                var FacetValue = FacetData.FacetValues[key];

                if (FacetValue.Id == 0 && FacetValue.Value != null)
                {
                    FacetValue.FacetId  = key.Id;
                    FacetValue.EntityId = entity.Id;

                    FacetValueSet.Add(FacetValue);
                }
            }

            entityDbContext.SaveChanges();
        }
        public static void LoadFacetValues <TEntity>(this TEntity entity, EntityDbContext entityDbContext)
            where TEntity : IEntity, IExtensible
        {
            var FacetData = entity.FindExtension <EntityFacetData>();

            if (FacetData != null)
            {
                return;
            }

            var cachedEntityTypeSet = entityDbContext.GetCachedDataSet <CachedEntityType>();
            var cachedFacetset      = entityDbContext.GetCachedDataSet <CachedFacet>();
            var FacetValueSet       = entityDbContext.GetDataSet <FacetValue>();

            CachedEntityType entityType = cachedEntityTypeSet.GetByType <TEntity>();

            var Facets = cachedFacetset.GetAll()
                         .Where(a => a.EntityTypeId == entityType.Id)
                         .Where(a => a.DoQualifiersMatchForEntity(entity))
                         .ToList();

            var FacetIds = Facets.Select(a => a.Id)
                           .ToList();
            var FacetValues = FacetValueSet.Where(a => FacetIds.Contains(a.FacetId))
                              .ToList();

            var values = Facets.ToDictionary(
                a => a,
                a => FacetValues.FirstOrDefault(b => b.FacetId == a.Id) ?? FacetValueSet.Create());

            FacetData = new EntityFacetData(values);

            entity.AddOrReplaceExtension(FacetData);
        }
 private void InitViews(EntityDbContext dc, List <JToken> jViews)
 {
     jViews.ForEach(jView => {
         var dmView = jView.ToObject <View>();
         dmView.Add(dc);
     });
 }
Example #15
0
 public void DatabaseName_IsTestName()
 {
     using (var dbContext = new EntityDbContext())
     {
         dbContext.Database.Connection.Database.ShouldEqual("TripodIocIntegrationTestDb");
     }
 }
Example #16
0
        public static void SeedUserDefinedTypes(ref EntityDbContext context)
        {
            var path  = $"{Assembly.GetExecutingAssembly().GetExecutingAssemblyPath()}/UserDefinedTypes";
            var query = "SELECT s.name + '.' + tt.name FROM sys.table_types tt INNER JOIN sys.schemas s ON tt.schema_id = s.schema_id";

            ProcessSqlFiles(ref context, path, query);
        }
Example #17
0
        public void Handler_ReturnsUser_ById()
        {
            using (var dbContext = new EntityDbContext())
            {
                var userName = Guid.NewGuid().ToString();
                var user     = new User {
                    Name = userName
                };
                dbContext.Create(user);
                var rowsAffected = dbContext.SaveChangesAsync().Result;
                var handler      = new HandleUserByQuery(dbContext);

                var result = handler.Handle(new UserBy(user.Id)
                {
                    EagerLoad = new Expression <Func <User, object> >[]
                    {
                        x => x.Permissions,
                    }
                }).Result;

                Assert.NotNull(result);
                result.ShouldEqual(user);
                rowsAffected.ShouldEqual(1);
            }
        }
Example #18
0
        public static void CreateProcedures(ref EntityDbContext context)
        {
            var path  = $"{Assembly.GetExecutingAssembly().GetExecutingAssemblyPath()}/Procedures";
            var query = "SELECT ROUTINE_SCHEMA + '.' + ROUTINE_NAME FROM INFORMATION_SCHEMA.ROUTINES";

            ProcessSqlFiles(ref context, path, query);
        }
Example #19
0
        public ActionResult Index()
        {
            var context = new EntityDbContext();
            var list    = context.Albums.OrderByDescending(x => x.PublisherDate).Take(20).ToList();

            return(View(list));
        }
Example #20
0
        public static IEnumerable <SelectListItem> BillingCurrencySelectItems()
        {
            // Load Cache.
            var currencies =
                System.Web.HttpContext.Current?.Cache[BillingCurrencySelectionCacheKey] as List <SelectListItem>;

            // Check Cache.
            if (currencies?.Any() ?? false)
            {
                return(currencies);
            }

            // Load From Database.
            using (var context = new EntityDbContext())
            {
                currencies = context.Currencies?
                             .Select(i => new SelectListItem {
                    Value = i.CurrencyId.ToString(), Text = i.Name
                }).ToList();
            }

            // Save to Cache.
            if ((currencies?.Any() ?? false) && System.Web.HttpContext.Current?.Cache != null)
            {
                System.Web.HttpContext.Current.Cache[BillingCurrencySelectionCacheKey] = currencies;
            }

            // Return.
            return(currencies);
        }
Example #21
0
        public async Task <bool> CreateAsync(UsuarioView dados)
        {
            using (var context = new EntityDbContext())
            {
                try
                {
                    var usuariomodel = new Usuario();

                    usuariomodel.User            = dados.User.ToString();
                    usuariomodel.Senha           = dados.Senha.ToString();
                    usuariomodel.Nome            = dados.Nome.ToString();
                    usuariomodel.PerfilId        = dados.PerfilId;
                    usuariomodel.DataCriacao     = DateTime.Now;
                    usuariomodel.DataAtualizacao = DateTime.Now;

                    await context.Usuariodbset.AddAsync(usuariomodel);

                    await context.SaveChangesAsync();

                    return(true);
                }
                catch
                {
                    return(false);
                }
            }
        }
        public HttpResponseMessage Delete(int id)
        {
            try
            {
                using (EntityDbContext objDB = new EntityDbContext())
                {
                    var carData = objDB.Cars.SingleOrDefault(p => p.CarID == id);
                    if (carData == null)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.NotFound, string.Format("Car Does not Exists")));
                    }
                    else
                    {
                        objDB.Cars.Remove(carData);
                        objDB.SaveChanges();
                    }

                    var msg = Request.CreateResponse(HttpStatusCode.OK, "Record Deleted");
                    msg.Headers.Location = Request.RequestUri;

                    return(msg);
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }
        }
Example #23
0
        public ActionResult SRefreshUser(Guid id)
        {
            EntityDbContext _context   = new EntityDbContext();
            var             person     = _context.Persons.SingleOrDefault(x => x.ID == id);
            string          HtmlString = "";

            if (person == null)
            {
                HtmlString = "<li class=\"active\"  id=\"User\"><a href = \"/Account/login\">登录</a></li>";
                return(Json(HtmlString));
            }
            else
            {
                var Cart = _context.Cart.Where(x => x.Person.ID == id).ToList();
                HtmlString += "<input type=hidden id=" + person.ID + " value=" + person.ID + "/>";
                HtmlString += "<a href =\"#\" class=\"dropdown-toggle\" data-toggle=dropdown  role = button   aria-haspopup=true aria-expanded=false>";
                HtmlString += " <img src =" + person.Avarda + " style = \"height:25px;width:25px; border-radius:50%;\" />";
                HtmlString += " " + person.Name + "<span class=\"caret\"></span> </a>";
                HtmlString += "<ul class=\" dropdown-menu \">";
                HtmlString += "<li><a href =\"/ShoppingCart/ShoppingCart\">购物车(" + Cart.Count + ")</a> </li>";
                HtmlString += "<li><a href = \"/Order/index\">我的订单</a> </li>";
                HtmlString += "<li><a href = \"/AddressPerson/index\">设置收件人</a></li>";
                HtmlString += "<li><a href = \"/my/index\">个人信息</a> </li>";
                HtmlString += "<li><a href = \"/Account/RevisePwd \">修改密码</a> </li>";
                HtmlString += "<li><a href = \"/Account/loginout\">注销</a> </li>";
                HtmlString += "</ul>";
            }
            return(Json(HtmlString));
        }
        public HttpResponseMessage Put([FromBody] CarsStock Nvalue, int id)
        {
            try
            {
                using (EntityDbContext objDB = new EntityDbContext())
                {
                    var carData = objDB.Cars.SingleOrDefault(p => p.CarID == id);
                    if (carData == null)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.NotFound, string.Format("Car Does not Exists")));
                    }
                    else
                    {
                        carData.CarName  = Nvalue.CarName;
                        carData.CarModel = Nvalue.CarModel;
                        carData.CarPrice = Nvalue.CarPrice;
                        carData.CarColor = Nvalue.CarColor;

                        objDB.SaveChanges();

                        var msg = Request.CreateResponse(HttpStatusCode.OK, "Record Updated");
                        msg.Headers.Location = Request.RequestUri;

                        return(msg);
                    }
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }
        }
Example #25
0
        public Type GetEntityType(EntityDbContext dc)
        {
            var entityName = dc.Table <Bundle>().Find(Id).EntityName;
            var entityType = TypeHelper.GetClassesWithInterface <IBundlableEntity>(EntityDbContext.Assembles).FirstOrDefault(x => x.Name == entityName);

            return(entityType);
        }
 void IDisposable.Dispose()
 {
     using (var dbContext = new EntityDbContext())
     {
         dbContext.Database.Delete();
     }
 }
        protected AbstractBasicUpdateTest()
        {
            _sqliteConnection =
                new SqliteConnection(new SqliteConnectionStringBuilder {
                DataSource = ":memory:"
            }.ConnectionString);

            _sqliteConnection.Open();

            var optionsBuilder = new DbContextOptionsBuilder <EntityDbContext>()
                                 .UseSqlite(_sqliteConnection)
                                 .UseLoggerFactory(new SerilogLoggerFactory(new LoggerConfiguration()
                                                                            .WriteTo.Console()
                                                                            .CreateLogger()));

            _dbContext = new EntityDbContext(optionsBuilder.Options);

            _fixture = new Fixture();

            /*
             * _fixture.Customize<Level1>(x =>
             *  x.Without(y => y.DummyModelRef)
             *      .Without(y => y.DummyModelRefId));
             *
             * _fixture.Customize<Level2>(x =>
             *  x.Without(y => y.Level1Ref)
             *      .Without(y => y.Level1RefId));
             *
             * _fixture.Customize<Level3>(x =>
             *  x.Without(y => y.Level2Ref)
             *      .Without(y => y.Level2RefId));*/
        }
Example #28
0
        protected void Application_Start()
        {
            var builder = new ContainerBuilder();

            builder.RegisterControllers(typeof(MvcApplication).Assembly);
            builder.RegisterType <DbContextProvider>().As <IDbContextProvider>().InstancePerRequest();
            builder.RegisterType <ShopRepository>().As <IShopRepository>().InstancePerRequest();

            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            Database.SetInitializer(new ShopDBInitializer());
            EntityDbContext context = new EntityDbContext();

            context.Database.Initialize(true);

            var grabber = new SourceGrabber();
            var updater = new DbUpdater();
            var parser  = new XmlParser();

            updater.AddOrUpdateItems(context, grabber, parser, ConfigurationManager.AppSettings["SourceURL"]);

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
Example #29
0
        /// <summary>
        /// Add bundlable entity record
        /// </summary>
        /// <param name="dc"></param>
        /// <param name="jEntity"></param>
        public BundleDbRecord AddRecord(EntityDbContext dc, JObject jEntity)
        {
            var type = TypeHelper.GetClassesWithInterface <IBundlableEntity>(EntityDbContext.Assembles).FirstOrDefault(x => x.Name == EntityName);

            // extract data to main object, fill field record later.
            var record = jEntity.ToObject(type) as BundleDbRecord;

            record.BundleId = Id;
            record.Id       = record.Id ?? Guid.NewGuid().ToString();
            record.Fields   = Fields;

            // fill custom fields
            record.Fields.ForEach(field =>
            {
                var fieldType = TypeHelper.GetClassesWithInterface <IFieldRepository>(EntityDbContext.Assembles).FirstOrDefault(x => x.Name == field.FieldTypeName + "Field");
                if (fieldType == null)
                {
                    Console.WriteLine($"{field.FieldTypeName} field not found. Ignored {field.Name} column. {field.Id}");
                }
                else
                {
                    var fieldInstance           = (FieldRepository)Activator.CreateInstance(fieldType);
                    fieldInstance.BundleFieldId = field.Id;
                    field.Records = fieldInstance.Extract(record.Id, field, jEntity[field.Name], fieldType);
                }
            });

            record.InsertEntity(dc, record.GetEntityName());

            return(record);
        }
Example #30
0
        public static IEnumerable <SelectListItem> WarningIndicatorSelectItems()
        {
            // Load Cache.
            var warningIndicators =
                System.Web.HttpContext.Current?.Cache[WarningIndicatorCacheKey] as List <SelectListItem>;

            // Check Cache.
            if (warningIndicators?.Any() ?? false)
            {
                return(warningIndicators);
            }

            // Load From Database.
            using (var context = new EntityDbContext())
            {
                warningIndicators = context.ScanWarningIndicators?.OrderBy(i => i.Name)
                                    .Select(i => new SelectListItem {
                    Value = i.WarningIndicatorId.ToString(), Text = i.Name
                }).ToList();
            }

            // Save to Cache.
            if ((warningIndicators?.Any() ?? false) && System.Web.HttpContext.Current?.Cache != null)
            {
                System.Web.HttpContext.Current.Cache[WarningIndicatorCacheKey] = warningIndicators;
            }

            // Return.
            return(warningIndicators);
        }
Example #31
0
        public async Task <bool> CreateAsync(Faixas dados)
        {
            using (var context = new EntityDbContext())
            {
                try
                {
                    var Faixamodel = new Faixas();

                    Faixamodel.Cor             = dados.Cor.ToString();
                    Faixamodel.Aulas_Meta      = dados.Aulas_Meta;
                    Faixamodel.DataCriacao     = DateTime.Now;
                    Faixamodel.DataAtualizacao = DateTime.Now;

                    await context.Faixasbset.AddAsync(Faixamodel);

                    await context.SaveChangesAsync();

                    return(true);
                }
                catch
                {
                    return(false);
                }
            }
        }
Example #32
0
        public static IEnumerable <SelectListItem> InsuranceCompanySelectItems()
        {
            // Load Cache.
            var insuranceCompanies =
                System.Web.HttpContext.Current?.Cache[InsuranceCompanyCacheKey] as List <SelectListItem>;

            // Check Cache.
            if (insuranceCompanies?.Any() ?? false)
            {
                return(insuranceCompanies);
            }

            // Load From Database.
            using (var context = new EntityDbContext())
            {
                insuranceCompanies = context.InsuranceCompanies?.OrderBy(i => i.InsuranceCompanyName).Where(i => !i.DisabledInd)
                                     .Select(i => new SelectListItem {
                    Value = i.InsuranceCompanyId.ToString(), Text = i.InsuranceCompanyName
                }).ToList();
            }

            // Save to Cache.
            if ((insuranceCompanies?.Any() ?? false) && System.Web.HttpContext.Current?.Cache != null)
            {
                System.Web.HttpContext.Current.Cache[InsuranceCompanyCacheKey] = insuranceCompanies;
            }

            // Return.
            return(insuranceCompanies);
        }
Example #33
0
        private void LoginUser(Guid userGuid)
        {
            try
            {
                // Set Session Var.
                Session["KeepSession"] = 1;

                // Check Session.
                if (Session.SessionID == null)
                {
                    return;
                }

                // Connect to Database.
                using (var context = new EntityDbContext())
                {
                    // Lookup User.
                    var user = context.Users.Find(userGuid);

                    // Check User.
                    if (user == null)
                    {
                        return;
                    }

                    // Clear Session.
                    user.SessionId = Session.SessionID;
                    context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
        }
Example #34
0
 public void EagerLoad_ReturnsNull_WhenQueryIsNull()
 {
     using (var dbContext = new EntityDbContext())
     {
         var result = dbContext.EagerLoad<Permission>(null, x => x.Users);
         result.ShouldBeNull();
     }
 }
Example #35
0
 public void ModelCreator_HasPublicSetter()
 {
     var modelCreator = new Mock<ICreateDbModel>(MockBehavior.Loose);
     var dbContext = new EntityDbContext
     {
         ModelCreator = modelCreator.Object
     };
     dbContext.ModelCreator.ShouldEqual(modelCreator.Object);
 }
Example #36
0
 public void Initializer_HasPublicSetter()
 {
     var initializer = new Mock<IDatabaseInitializer<EntityDbContext>>(MockBehavior.Loose);
     var dbContext = new EntityDbContext
     {
         Initializer = initializer.Object
     };
     dbContext.Initializer.ShouldEqual(initializer.Object);
 }
Example #37
0
        public void NoArgGet_ReturnsDataFromStore()
        {
            using (var dbContext = new EntityDbContext())
            {
                var entities = dbContext.Get<User>().Take(2).ToArray();

                entities.ShouldNotBeNull();
                entities.Length.ShouldBeInRange(0, 2);
            }
        }
 public EntityDbContextDatabaseInitializer()
 {
     var dbContext = new EntityDbContext
     {
         Initializer = new DropCreateDatabaseIfModelChanges<EntityDbContext>()
     };
     dbContext.Initializer.InitializeDatabase(dbContext);
     var users = dbContext.Set<User>().ToArray();
     Assert.NotNull(users);
     users.Count().ShouldBeInRange(0, int.MaxValue);
     dbContext.Dispose();
 }
Example #39
0
        public void Query_ReturnsData()
        {
            using (var dbContext = new EntityDbContext())
            {
                var createdEntity = new User { Name = Guid.NewGuid().ToString() };
                dbContext.Create(createdEntity);
                var affectedRows = dbContext.SaveChangesAsync().Result;
                affectedRows.ShouldEqual(1);

                var queriedEntity = dbContext.Query<User>().SingleOrDefaultAsync(x => x.Id == createdEntity.Id).Result;

                Assert.NotNull(queriedEntity);
                createdEntity.Id.ShouldEqual(queriedEntity.Id);
            }
        }
        public void InitializeDatabase_CustomizesDuringSeed_WhenDatabaseDoesNotExist()
        {
            using (var dbContext = new EntityDbContext())
            {
                dbContext.Database.Delete(); // force initializer to seed
                var dbCustomizer = new Mock<ICustomizeDb>(MockBehavior.Strict);
                dbCustomizer.Setup(x => x.Customize(It.IsAny<EntityDbContext>()));
                var dbInitializer = new GreenfieldDbInitializer(dbCustomizer.Object);
                dbContext.Initializer = dbInitializer;
                dbContext.Initializer.InitializeDatabase(dbContext);

                dbCustomizer.Verify(x => x.Customize(It.IsAny<EntityDbContext>()), Times.Once);
                dbContext.Dispose();
            }
        }
Example #41
0
        public void Handler_ReturnsUser_ByName_CaseInsensitively()
        {
            using (var dbContext = new EntityDbContext())
            {
                var userName = Guid.NewGuid().ToString().ToUpper();
                var user = new User { Name = userName };
                dbContext.Create(user);
                var rowsAffected = dbContext.SaveChangesAsync().Result;
                var handler = new HandleUserByQuery(dbContext);

                var result = handler.Handle(new UserBy(userName.ToLower())).Result;

                Assert.NotNull(result);
                result.ShouldEqual(user);
                rowsAffected.ShouldEqual(1);
            }
        }
Example #42
0
        public void UserLoginStoreInterface_FindAsync_FindsMatchingRemoteMemberships()
        {
            using (var dbContext = new EntityDbContext())
            {
                var user = new User { Name = Guid.NewGuid().ToString() };
                var remote1 = new RemoteMembership
                {
                    Id =
                    {
                        LoginProvider = Guid.NewGuid().ToString(),
                        ProviderKey = Guid.NewGuid().ToString()
                    }
                };
                var remote2 = new RemoteMembership
                {
                    Id =
                    {
                        LoginProvider = Guid.NewGuid().ToString(),
                        ProviderKey = Guid.NewGuid().ToString()
                    }
                };
                var remote3 = new RemoteMembership
                {
                    Id =
                    {
                        LoginProvider = Guid.NewGuid().ToString(),
                        ProviderKey = Guid.NewGuid().ToString()
                    }
                };
                user.RemoteMemberships.Add(remote1);
                user.RemoteMemberships.Add(remote2);
                user.RemoteMemberships.Add(remote3);
                dbContext.Create(user);
                dbContext.SaveChangesAsync().GetAwaiter().GetResult();

                var securityStore = new SecurityStore(dbContext);
                var result = securityStore.FindAsync(new UserLoginInfo(remote2.LoginProvider, remote2.ProviderKey)).Result;

                result.ShouldNotBeNull();
                result.ShouldEqual(user);
            }
        }
Example #43
0
        public void EagerLoad_IncludesRelatedData()
        {
            using (var dbContext = new EntityDbContext())
            {
                var userName = Guid.NewGuid().ToString();
                var permissionName = Guid.NewGuid().ToString();
                var user = new User { Name = userName, };
                user.Permissions.Add(new Permission { Name = permissionName });
                dbContext.Create(user);
                var affectedRows = dbContext.SaveChangesAsync().Result;
                affectedRows.ShouldEqual(3);

                var entity = dbContext.Query<User>()
                    .EagerLoad(new Expression<Func<User, object>>[]
                {
                    x => x.Permissions,
                }).Single(x => x.Name.Equals(userName));
                entity.Permissions.Count.ShouldEqual(1);
                entity.Permissions.Single().Name.ShouldEqual(permissionName);
            }
        }
Example #44
0
        public void UserRoleStoreInterface_AddToRoleAsync_GivesUserPermission()
        {
            using (var dbContext = new EntityDbContext())
            {
                var user = new User { Name = Guid.NewGuid().ToString() };
                var permission1 = new Permission { Name = Guid.NewGuid().ToString() };
                var permission2 = new Permission { Name = Guid.NewGuid().ToString() };
                var permission3 = new Permission { Name = Guid.NewGuid().ToString() };
                dbContext.Create(user);
                dbContext.Create(permission1);
                dbContext.Create(permission2);
                dbContext.Create(permission3);
                dbContext.SaveChangesAsync().GetAwaiter().GetResult();

                var securityStore = new SecurityStore(dbContext);
                securityStore.AddToRoleAsync(user, permission2.Name).Wait();
                dbContext.SaveChangesAsync().Wait();

                user.Permissions.ShouldContain(permission2);
                permission2.Users.ShouldContain(user);
            }
        }
Example #45
0
        public void Handler_ReturnsUser_ById()
        {
            using (var dbContext = new EntityDbContext())
            {
                var userName = Guid.NewGuid().ToString();
                var user = new User { Name = userName };
                dbContext.Create(user);
                var rowsAffected = dbContext.SaveChangesAsync().Result;
                var handler = new HandleUserByQuery(dbContext);

                var result = handler.Handle(new UserBy(user.Id)
                {
                    EagerLoad = new Expression<Func<User, object>>[]
                    {
                        x => x.Permissions,
                    }
                }).Result;

                Assert.NotNull(result);
                result.ShouldEqual(user);
                rowsAffected.ShouldEqual(1);
            }
        }
Example #46
0
 public void GetAsync_ReturnsNull_WhenPrimaryKeyDoesNotMatchRow()
 {
     using (var dbContext = new EntityDbContext())
     {
         var entity = dbContext.GetAsync<User>(int.MaxValue).Result;
         entity.ShouldBeNull();
     }
 }
Example #47
0
 public void Get_ThrowsArgumentNullException_WhenFirstKeyValueArgumentIsNull()
 {
     using (var dbContext = new EntityDbContext())
     {
         var exception = Assert.Throws<ArgumentNullException>(() => dbContext.Get<User>(null));
         exception.ShouldNotBeNull();
         exception.ParamName.ShouldEqual("firstKeyValue");
     }
 }
Example #48
0
 public void Create_AddsEntityToDb_WhenChangesAreSaved()
 {
     using (var dbContext = new EntityDbContext())
     {
         var entity = new User { Name = Guid.NewGuid().ToString() };
         dbContext.Create(entity);
         entity.Id.ShouldEqual(0);
         var affectedRows = dbContext.SaveChangesAsync().Result;
         affectedRows.ShouldEqual(1);
         entity.Id.ShouldNotEqual(0);
     }
 }
Example #49
0
 public void Create_SetsEntityState_ToAdded()
 {
     using (var dbContext = new EntityDbContext())
     {
         var entity = new User { Name = Guid.NewGuid().ToString() };
         dbContext.Entry(entity).State.ShouldEqual(EntityState.Detached);
         dbContext.Create(entity);
         dbContext.Entry(entity).State.ShouldEqual(EntityState.Added);
     }
 }
Example #50
0
        public void Update_SetsEntityState_ToModified()
        {
            using (var dbContext = new EntityDbContext())
            {
                var permissionName = Guid.NewGuid().ToString();
                var entity = new Permission { Name = permissionName, Description = "d1" };
                dbContext.Create(entity);
                var affectedRows = dbContext.SaveChangesAsync().Result;

                affectedRows.ShouldEqual(1);
                dbContext.Entry(entity).State.ShouldEqual(EntityState.Unchanged);
                dbContext.Update(entity);
                dbContext.Entry(entity).State.ShouldEqual(EntityState.Modified);
            }
        }
Example #51
0
        public void ReloadAsync_ChangesModifiedEntityState_ToUnchanged()
        {
            using (var dbContext = new EntityDbContext())
            {
                var description = Guid.NewGuid().ToString();
                var entity = new Permission { Name = Guid.NewGuid().ToString(), Description = description };
                dbContext.Create(entity);
                var affectedRows = dbContext.SaveChangesAsync().Result;

                affectedRows.ShouldEqual(1);
                dbContext.Entry(entity).State.ShouldEqual(EntityState.Unchanged);
                entity.Description = Guid.NewGuid().ToString();
                dbContext.Entry(entity).State.ShouldEqual(EntityState.Modified);
                dbContext.ReloadAsync(entity).Wait();
                dbContext.Entry(entity).State.ShouldEqual(EntityState.Unchanged);
                entity.Description.ShouldEqual(description);
            }
        }
Example #52
0
        public void DiscardChangesAsync_ChangesAddedEntityState_ToDetached()
        {
            using (var dbContext = new EntityDbContext())
            {
                var entity = new User { Name = Guid.NewGuid().ToString() };
                dbContext.Create(entity);

                dbContext.Entry(entity).State.ShouldEqual(EntityState.Added);
                dbContext.DiscardChangesAsync().Wait();
                dbContext.Entry(entity).State.ShouldEqual(EntityState.Detached);
            }
        }
Example #53
0
        public void DiscardChangesAsync_ChangesDeletedEntityState_ToUnchanged()
        {
            using (var dbContext = new EntityDbContext())
            {
                var entity = new User { Name = Guid.NewGuid().ToString() };
                dbContext.Create(entity);
                var affectedRows = dbContext.SaveChangesAsync().Result;

                affectedRows.ShouldEqual(1);
                dbContext.Entry(entity).State.ShouldEqual(EntityState.Unchanged);
                dbContext.Delete(entity);
                dbContext.Entry(entity).State.ShouldEqual(EntityState.Deleted);
                dbContext.DiscardChangesAsync().Wait();
                dbContext.Entry(entity).State.ShouldEqual(EntityState.Unchanged);

            }
        }
Example #54
0
 public void Ctor_SetsInitializer_ToBrownfield()
 {
     var dbContext = new EntityDbContext();
     dbContext.Initializer.ShouldNotBeNull();
     dbContext.Initializer.GetType().ShouldEqual(typeof(BrownfieldDbInitializer));
 }