public async Task CategoryRepository() {
			var id = Guid.Empty;

			// Insert category
			using (var api = new Api()) {
				var cat = new Models.Category() {
					Name = "My category",
				};
				api.Categories.Add(cat);

				Assert.IsTrue(cat.Id.HasValue);
				Assert.IsTrue(api.SaveChanges() > 0);

				id = cat.Id.Value;
			}

			// Get by slug
			using (var api = new Api()) {
				var cat = await api.Categories.GetBySlugAsync("my-category");

				Assert.IsNotNull(cat);
				Assert.AreEqual(cat.Name, "My category");
			}

			// Update category
			using (var api = new Api()) {
				var cat = await api.Categories.GetBySlugAsync("my-category");

				Assert.IsNotNull(cat);

				cat.Name = "My updated category";
				api.Categories.Add(cat);

				Assert.IsTrue(api.SaveChanges() > 0);
			}

			// Get by id
			using (var api = new Api()) {
				var cat = await api.Categories.GetByIdAsync(id);

				Assert.IsNotNull(cat);
				Assert.AreEqual(cat.Name, "My updated category");
			}

			// Remove category
			using (var api = new Api()) {
				var cat = await api.Categories.GetBySlugAsync("my-category");

				api.Categories.Remove(cat);

				Assert.IsTrue(api.SaveChanges() > 0);
			}
		}
Exemple #2
0
        public ActionResult catalog(String id=null)
        {
            Models.Category cat = new Models.Category();
            if (id == null)
            {
                ViewData["Message"] = cat.doListCategory();
            }
            else
            {
                int id_cat = Convert.ToInt32(id);
                ViewData["Message"] = cat.getCategory(id_cat);

            }

            return View("Catalog");
        }
Exemple #3
0
        public IActionResult OnPost(Models.Category categoryObj)
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            if (categoryObj.Id == 0)
            {
                _unitOfWork.Category.Add(categoryObj);
            }
            else
            {
                _unitOfWork.Category.Update(categoryObj);
            }

            _unitOfWork.Save();
            return(RedirectToPage("./Index"));
        }
Exemple #4
0
        public Models.Category Create(Models.Category entity, string userName)
        {
            try
            {
                if (!CategoryAccessControl.Pass(RestfulAction.Create, entity, userName))
                {
                    throw new NoAccessException("No Access");
                }

                entity.Creator = userName;
                entity.Created = DateTime.Now;

                return(RestfulCategory.Create(entity));
            }
            catch
            {
                throw;
            }
        }
        public ActionResult SaveAddedCategory(Models.Category category)
        {
            PRFancyRepository dal = new PRFancyRepository();
            PRFancyAutoMapper <Models.Category, category> map = new PRFancyAutoMapper <Models.Category, category>();

            try
            {
                if (dal.AddCategory(map.Translate(category)))
                {
                    return(RedirectToAction("ViewAllCategory"));
                }
                return(View("Error"));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }
Exemple #6
0
        public void AddCategoryReturnsARedirectAndAddsCategory()
        {
            // Arrange
            var mock        = new Mock <ICategoriesRepository>();
            var controller  = new CategoriesController(mock.Object);
            var newCategory = new Models.Category()
            {
                Name = "Example"
            };

            // Act
            var result = controller.Create(newCategory);

            // Assert
            var redirectToActionResult = Assert.IsType <RedirectToActionResult>(result);

            Assert.AreEqual("Index", redirectToActionResult.ActionName);
            mock.Verify(r => r.Save(newCategory));
        }
Exemple #7
0
        public ActionResult CategoryCreate(ViewModels.CategoryCreateViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            using (var db = new Models.FazerDB())
            {
                var category = new Models.Category
                {
                    Name = model.Name
                };

                db.Categories.Add(category);
                db.SaveChanges();
            }

            return(RedirectToAction("CategoryIndex"));
        }
        public async Task WhenAddAsyncIsCalledThenAllFieldsArePopulated()
        {
            var category = new Models.Category
            {
                Name            = "Bills",
                CategoryGroupId = 1
            };

            await this.categoryRepository.AddAsync(category);

            List <Category> insertedCategories = this.databaseHelper.Select <Category>(c => c.Name == "Bills");

            Assume.That(insertedCategories.Count, Is.EqualTo(1));

            Category insertedCategory = insertedCategories.First();

            Assert.That(insertedCategory.Name, Is.EqualTo("Bills"));
            Assert.That(insertedCategory.CategoryGroupId, Is.EqualTo(1));
        }
        public object GetCategory(int parent_id)
        {
            Category c = new Models.Category();

            IEnumerable <Category> result = null;

            if (parent_id == 0)
            {
                result = db.Categories.Where(p => p.Parent == null).ToList();
            }
            else
            {
                result = db.Categories.Where(p => p.Parent.Id == parent_id).ToList();
            }
            return(new {
                Data = result,
                Message = 0
            });
        }
        public IActionResult Upsert(Models.Category category)
        {
            if (ModelState.IsValid)
            {
                if (category.Id == 0)
                {
                    _unitOfWork.CategoryRepository.Add(category);
                }
                else
                {
                    _unitOfWork.CategoryRepository.Update(category);
                }

                _unitOfWork.Save();

                return(RedirectToAction(nameof(Index)));
            }

            return(View(category));
        }
        public ActionResult Post([FromBody] Models.Category category)
        {
            if (category == null)
            {
                return(BadRequest());
            }
            var cat = this._mapper.Map <Entities.Category>(category);

            cat.CreatedIP = "21.21.12.12";
            var result = this._categoriesRepository.Insert(cat);

            if (result != null)
            {
                return(Created("api/categories", result.Id));
            }
            else
            {
                return(BadRequest("Failed to create category."));
            }
        }
        public ActionResult Edit(int id, Models.Category requestCategory)
        {
            try
            {
                Models.Category category = db.Categories.Find(id);
                if (TryUpdateModel(category))
                {
                    category.CategoryName = requestCategory.CategoryName;
                    db.SaveChanges();
                    TempData["message"] = "Categoria a fost editata cu succes!";
                    return(RedirectToAction("Index"));
                }
                return(View(requestCategory));
            }

            catch (Exception e)
            {
                return(View(requestCategory));
            }
        }
Exemple #13
0
        private List <Models.Category> ConstructCategoriesList(ProjectDonor pd, List <GeneralLedger> glList)
        {
            List <BudgetCategory> bcList = budgetService.GetBudgetCategories(pd);

            Models.Category        modelBC;
            List <Models.Category> categories = new List <Models.Category>();

            foreach (BudgetCategory bc in bcList)
            {
                modelBC = new Models.Category();
                modelBC.EntityBudgetCategory = bc;
                modelBC.Id          = bc.Id.ToString();
                modelBC.BudgetLines = PopulateCategoryBudgetLines(modelBC.EntityBudgetCategory, glList);
                if (modelBC.BudgetLines.Count > 0)
                {
                    categories.Add(modelBC);
                }
            }
            return(categories);
        }
Exemple #14
0
        public List <Models.Category> getAllCategories()
        {
            SqlCommand             cmd;
            List <Models.Category> categories = new List <Models.Category>();

            String query = "SELECT * FROM dbo.Categories";

            using (SqlConnection conn = new SqlConnection(CONNECTIONSTRING))
            {
                conn.Open();
                cmd = new SqlCommand(query, conn);
                SqlDataReader dtCats = cmd.ExecuteReader();
                while (dtCats.Read())
                {
                    Models.Category cat = new Models.Category(dtCats.GetFieldValue <int>(0), dtCats.GetFieldValue <string>(1), dtCats.GetFieldValue <string>(2));
                    categories.Add(cat);
                }
            }
            return(categories);
        }
Exemple #15
0
        public ActionResult Create(Models.Category data)
        {
            try
            {
                if (!string.IsNullOrEmpty(data.Description))
                {
                    data.Description = Utilities.StringUtility.EscapeXml(System.Web.HttpUtility.HtmlDecode(data.Description));
                }

                return(Json
                       (
                           new
                {
                    Entity = RestfulJsonProccessor.Category.Single(RestfulCategory.Create(data, User.Identity.IsAuthenticated ? User.Identity.Name : null), User.Identity.IsAuthenticated ? User.Identity.Name : null)
                },
                           JsonRequestBehavior.AllowGet
                       ));
            }
            catch (RestfulModels.NoAccessException)
            {
                Response.StatusCode = 401;
                return(null);
            }
            catch (RestfulModels.ValidationException e)
            {
                Response.StatusCode = 406;
                return(Json
                       (
                           new
                {
                    ValidationErrors = e
                },
                           JsonRequestBehavior.AllowGet
                       ));
            }
            catch
            {
                Response.StatusCode = 500;
                return(null);
            }
        }
        public ActionResult Put(string id, [FromBody] Models.Category category)
        {
            if (category == null)
            {
                return(BadRequest());
            }
            var cat = this._mapper.Map <Entities.Category>(category);

            cat.ModifiedIP = "12.32.34.12";
            var result = this._categoriesRepository.Update(id, cat);

            if (result)
            {
                var item = this._categoriesRepository.Find(id);
                return(Ok(item));
            }
            else
            {
                return(BadRequest("Failed to update category."));
            }
        }
        public virtual ActionResult <Models.Category> GetCategoryByName([FromRoute][Required] string categoryName)
        {
            var categoryDao = _categoryDal.getCategoryByName(categoryName);

            if (categoryDao == null)
            {
                Console.WriteLine("Category with name %s not found!", categoryName);

                ApiResponse response = new ApiResponse();
                response.Code    = 404;
                response.Type    = "Not Found";
                response.Message = "Category with the name does not exist.";
                return(NotFound(response));
            }

            Models.Category result = new Models.Category();
            result.Id   = categoryDao.Id;
            result.Name = categoryDao.Name;

            return(StatusCode(200, result));
        }
Exemple #18
0
        public async Task <ActionResult <Models.Category> > Create(CategoryCreateResponse response)
        {
            using var transaction = _context.Database.BeginTransaction();
            var user = new Models.User {
                Id = 1
            };

            _context.Attach(user);

            var site = await _context
                       .Sites
                       .Where(s => s.Id == response.SiteId)
                       .Include(s => s.Categories)
                       .FirstOrDefaultAsync();

            if (site is null)
            {
                return(NotFound("Site not exist"));
            }

            if (site.Categories.Any(c => c.Slug == response.Slug))
            {
                return(BadRequest("Exist slug"));
            }

            var category = new Models.Category
            {
                Name = response.Name,
                Slug = response.Slug,
                Site = site,
            };

            _context.Categories.Add(category);

            await _context.SaveChangesAsync();

            transaction.Commit();
            return(category);
        }
        public void AddForum_returns_one_when_correct()
        {
            var category = new Models.Category {
                Id = Guid.NewGuid().ToString(), Name = TestsConstants.ValidCategoryName2
            };

            this.dbService.DbContext.Categories.Add(category);
            this.dbService.DbContext.SaveChanges();

            var model = new ForumFormInputModel();

            model.ForumModel.Name     = TestsConstants.ValidForumName;
            model.ForumModel.Category = category.Name;

            var expectedResult = 1;

            var actualResult = this.forumService.AddForum(model, category.Id);

            Assert.Equal(expectedResult, actualResult);

            this.SeedDb();
        }
Exemple #20
0
        /// <summary>
        /// Test the category repository.
        /// </summary>
        protected void Run()
        {
            using (var api = new Api()) {
                // Add new model
                var model = new Models.Category()
                {
                    Title = "My category"
                };
                api.Categories.Add(model);
                api.SaveChanges();
            }

            using (var api = new Api()) {
                // Get model
                var model = api.Categories.GetSingle(where : c => c.Slug == "my-category");
                Assert.IsNotNull(model);

                // Update model
                model.Title = "Updated";
                api.SaveChanges();
            }

            using (var api = new Api()) {
                // Verify update
                var model = api.Categories.GetSingle(where : c => c.Slug == "my-category");
                Assert.IsNotNull(model);
                Assert.AreEqual("Updated", model.Title);

                // Remove model
                api.Categories.Remove(model);
                api.SaveChanges();
            }

            using (var api = new Api()) {
                // Verify remove
                var model = api.Categories.GetSingle(where : c => c.Slug == "my-category");
                Assert.IsNull(model);
            }
        }
        public async Task WhenGetIsCalledThenCorrectCategoryIsReturned()
        {
            var categoriesToInsert = new List <Category>
            {
                new Category
                {
                    Id              = 1,
                    Name            = "Bills",
                    CategoryGroupId = 1,
                    Budget          = 50.00M
                },
                new Category
                {
                    Id              = 2,
                    Name            = "Rent",
                    CategoryGroupId = 1,
                    Budget          = 650.00M
                },
                new Category
                {
                    Id              = 3,
                    Name            = "Groceries",
                    CategoryGroupId = 1,
                    Budget          = 150.00M
                }
            };

            this.databaseHelper.Insert(categoriesToInsert);

            Models.Category result = await this.categoryRepository.GetAsync(2);

            Assert.Multiple(() =>
            {
                Assert.That(result.Id, Is.EqualTo(2));
                Assert.That(result.Name, Is.EqualTo("Rent"));
                Assert.That(result.CategoryGroupId, Is.EqualTo(1));
                Assert.That(result.Budget, Is.EqualTo(650.00M));
            });
        }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            int pId = 0;

            int.TryParse(context.Request["parentId"], out pId);
            string cName = context.Request["name"];

            Models.Category c = new Models.Category()
            {
                CategoryName = cName, ParentId = pId
            };
            try
            {
                CommonNews.Helper.OperateContext.Current.AddNewsType(c);
                context.Response.Write("true");
            }
            catch (Exception)
            {
                context.Response.Write("error");
            }
        }
Exemple #23
0
        public Models.Category Update(int id, Models.Category entity, string userName)
        {
            try
            {
                var old = RestfulCategory.Read(id);

                if (!CategoryAccessControl.Pass(RestfulAction.Update, old, userName))
                {
                    throw new NoAccessException("No Access");
                }

                entity.Title   = old.Title;
                entity.Creator = userName;
                entity.Created = old.Created;
                entity.Updated = DateTime.Now;

                return(RestfulCategory.Update(id, entity));
            }
            catch
            {
                throw;
            }
        }
Exemple #24
0
        // GET api/values
        public List <Models.Category> Get()
        {
            var categories = new List <Models.Category>();

            using (var context = new FORUMEntities3())
            {
                if (context.Categories.Count() > 0)
                {
                    var xx = (from em in context.Categories
                              select new { em.CategoryId, em.CategoryName, em.Description, em.Topics }).ToList();
                    foreach (var category in xx)
                    {
                        var cat = new Models.Category();
                        cat.CategoryId   = category.CategoryId;
                        cat.CategoryName = category.CategoryName;
                        cat.Description  = category.Description;
                        cat.TopicsCount  = category.Topics.Count();
                        categories.Add(cat);
                    }
                }
            }
            return(categories);
        }
Exemple #25
0
        public ActionResult additem()
        {
            try
            {
                if (this.CheckAuth())
                {
                    ViewData["Message"] = "Заполните пожалуйста поля";
                    Models.Category category = new Models.Category();
                    ViewData["category"] = category.doSelectCategory();
                    return View("AddItem");
                }
                else
                {
                    return View("Ajax");

                }
            }
            catch
            {
                ViewData["Message"] = "Заполните пожалуйста поля";
                return View("AddItem");
            }
        }
 public ActionResult SaveUpdatedCategory(Models.Category cat)
 {
     if (ModelState.IsValid)
     {
         try
         {
             bool status = rep.UpdateCategory(mapMod.Translate(cat));
             if (status)
             {
                 return(RedirectToAction("ViewCategory"));
             }
             else
             {
                 return(View("Error"));
             }
         }
         catch (Exception ex)
         {
             return(View("Error"));
         }
     }
     return(View("UpdateCategory", cat));
 }
Exemple #27
0
        private static object DataProcess(Models.Category data, string userName)
        {
            try
            {
                return(new
                {
                    Id = data.Id,
                    Title = data.Title,
                    Abbreviation = data.Abbreviation,
                    ChineseTitle = data.ChineseTitle,
                    Description = data.Description,
                    Creator = RestfulJsonProccessor.Account.MiniSingle(data.Creator),
                    Created = data.Created.ToString(),
                    Updated = data.Updated.ToString(),

                    Options = ControlProcess(data, userName)
                });
            }
            catch
            {
                throw;
            }
        }
Exemple #28
0
		/// <summary>
		/// Test the category repository.
		/// </summary>
		protected void Run() {
			using (var api = new Api()) {
				// Add new model
				var model = new Models.Category() {
					Title = "My category"
				};
				api.Categories.Add(model);
				api.SaveChanges();
			}

			using (var api = new Api()) {
				// Get model
				var model = api.Categories.GetSingle(where: c => c.Slug == "my-category");
				Assert.IsNotNull(model);

				// Update model
				model.Title = "Updated";
				api.SaveChanges();
			}

			using (var api = new Api()) {
				// Verify update
				var model = api.Categories.GetSingle(where: c => c.Slug == "my-category");
				Assert.IsNotNull(model);
				Assert.AreEqual("Updated", model.Title);

				// Remove model
				api.Categories.Remove(model);
				api.SaveChanges();
			}

			using (var api = new Api()) {
				// Verify remove
				var model = api.Categories.GetSingle(where: c => c.Slug == "my-category");
				Assert.IsNull(model);
			}
		}
Exemple #29
0
        public ActionResult additem(HttpPostedFileBase file, HttpPostedFileBase screenshot, Models.Item it)
        {
            Models.Category category = new Models.Category();
                if (file.ContentLength > 0 && it.description != "" && screenshot.ContentLength > 0 && it.title != "" && this.CheckAuth())
                {
                    if (screenshot.ContentType != "image/jpeg" && screenshot.ContentType != "image/png" && screenshot.ContentType != "image/gif")
                    {
                        ViewData["Message"] = "Скриншот должен быть только jpg,gif,png ";

                        ViewData["category"] = category.doSelectCategory();
                        return View("AddItem");
                    }
                    int id_user = Convert.ToInt32(Session["user_id"]);
                    var fileName = Path.GetFileName(file.FileName);

                    var screenname = Path.GetFileName(screenshot.FileName);
                    var path = Path.Combine(Server.MapPath("~/files"), fileName);
                    file.SaveAs(path);
                    path = Path.Combine(Server.MapPath("~/url"), screenname);

                    screenshot.SaveAs(path);
                    string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);
                    screenname = baseUrl + "/url/" + screenname;
                    it.doAddItem(it.title, it.description, screenname, it.id_category, id_user, it.value, fileName);

                    //ViewData["Message"] = it.title;
                    ViewData["Message"] = "Товар успешно добавлен";

                    ViewData["category"] = category.doSelectCategory();
                    return View("AddItem");
                }
                ViewData["Message"] = "Вы заполнили не все поля!";

                ViewData["category"] = category.doSelectCategory();
                return View("AddItem");
        }
Exemple #30
0
 public IActionResult Update([FromBody] Models.Category category)
 {
     _unitOfWork.CategoryRepository.Update(category);
     _unitOfWork.Complete();
     return(new JsonResult(category));
 }
        public async Task <Models.Category> UpdateCategory([FromBody] Models.Category category)
        {
            var updated = await _categoryRepository.UpdateAsyn(category);

            return(updated);
        }
Exemple #32
0
 public async Task Edit([FromBody] Models.Category category)
 {
     await categoryRepository.UpdateAsync(category.CategoryId, new DataAccess.Category {
         Id = category.CategoryId, CategoryName = category.CategoryName
     });
 }
Exemple #33
0
 public static Category From(Models.Category source)
 {
     return(new Category().PopulateWith(source));
 }
Exemple #34
0
 public String doSelectCategory()
 {
     try
     {
         Models.Category category = new Models.Category();
         String result = category.doSelectCategory();
         return result;
     }
     catch
     {
         return "";
     }
 }
Exemple #35
0
 internal void Add(Models.Category category)
 {
     throw new NotImplementedException();
 }
Exemple #36
0
 public static DTO.Category ToDTO(this Models.Category model)
 {
     Mapper.Initialize(p => p.CreateMap <Models.Category, DTO.Category>());
     return(Mapper.Map <DTO.Category>(model));
 }
Exemple #37
0
 //вывод списка категорий
 public String getCatalog()
 {
     try
     {
         //получение данных  из модели
         Models.Category category = new Models.Category();
         String text = category.doListCategory();
         return text;
     }
     catch
     {
         return "";
     }
 }
Exemple #38
0
 //получение списка товаров из  определенной категории
 public String getItemfromCat(int id)
 {
     try
     {
         if (id == null) return "";
         Models.Category category = new Models.Category();
         String result = category.getCategory(id);
         return result;
     }
     catch
     {
         return "Нет товаров в категории!";
     }
 }
Exemple #39
0
		/// <summary>
		/// Adds the categories to the given post.
		/// </summary>
		/// <param name="api">The current api</param>
		/// <param name="post">The post</param>
		/// <param name="categories">The categories</param>
		private static void AddCategories(IApi api, Models.Post post, string[] categories) {
			post.Categories.Clear();

			// Add categories
			foreach (var cat in categories) {
				var c = api.Categories.GetBySlug(Utils.GenerateSlug(cat));
				if (c == null)
					c = new Models.Category() { 
						Name = cat
					};
				post.Categories.Add(c);
			}
		}
Exemple #40
0
        public static Category GetSafteyScore(StepCollection steps)
        {
            Category category = new Models.Category();
            category.Rank = 2;
            category.Comment = "";
            category.Name = "Safety";

            try
            {
                using (var sqlConnection = new SqlConnection("Data Source=tv10a009ta.database.windows.net;Initial Catalog=ShouldIDrive_db;Persist Security Info=True;User ID=shoulddriveadmin;Password=ShouldIDrive123"))
                {
                    if (sqlConnection.State == ConnectionState.Closed)
                        sqlConnection.Open();

                    using (var sqlCommand = new SqlCommand("dbo.GetCrashStats", sqlConnection))
                    {
                        sqlCommand.Parameters.Clear();

                        var pathParameter = new SqlParameter("@path", SqlDbType.Udt)
                        {
                            UdtTypeName = "Geometry",
                            Value = steps.GetPolyline(),
                            Direction = ParameterDirection.Input
                        };

                        sqlCommand.Parameters.Add(pathParameter);
                        sqlCommand.CommandType = CommandType.StoredProcedure;

                        var sqlReader = sqlCommand.ExecuteReader();

                        int score = 0;

                        if (sqlReader.Read())
                        {
                            string severity = sqlReader.GetString(sqlReader.GetOrdinal("severity"));
                            int count = sqlReader.GetInt32(sqlReader.GetOrdinal("NumCrashes"));
                            int total = 0;
                            int crimeCount = GetCrimeScore(steps);

                            switch(severity)
                            {
                                case "Fatal":
                                    total = total + count;
                                    score = score + (10 * count);
                                    break;

                                case "Hospital":
                                    total = total + count;
                                    score = score + (8 * count);
                                    break;

                                case "Medical":
                                    total = total + count;
                                    score = score + (7 * count);
                                    break;

                                case "Property Damage Only (Major)":
                                    total = total + count;
                                    score = score + (5 * count);
                                    break;

                                case "Property Damage Only (Minor)":
                                    total = total + count;
                                    score = score + (3 * count);
                                    break;

                                case "Unknown":
                                    total = total + count;
                                    score = score + (1 * count);
                                    break;

                                default:
                                    break;
                            }

                            if (total > 0)
                            {
                                category.Comment = string.Format("There has been {0} accidents on the selected route over the last 4 years.", total);
                            }

                            if (score < 10)
                            {
                                category.Rank = 1;
                            }
                            else if (score < 100)
                            {
                                category.Rank = 2;
                            }
                            else if (score >= 100)
                            {
                                category.Rank = 3;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {

            }

            return category;
        }
Exemple #41
0
        public static void Main(string[] args)
        {
            string filePath = null;
            if (args.Length == 0)
            {
                throw new ArgumentException("Should be called with a Json PlayDrone file to import.");
            }

            filePath = args[0];

            var log = new Logger();
            var appConverter = new FileReader(log);

            var apps = appConverter.FileToModel(filePath);
            var count = apps.Count();

            // Setup connection
            var connectionString = ConfigurationManager.ConnectionStrings["MarketDbConnectionString"];
            using (var connection = new SqlConnection(connectionString.ConnectionString))
            {
                // Initialise app store with logger and connection
                var appSqlStore = new AppStore(connection);
                var appStore = new AppLogger(appSqlStore, appSqlStore, log);
                var categorySqlStore = new CategoryStore();
                var categoryCacheStore = new CategoryCache(categorySqlStore, categorySqlStore);
                var categoryStore = new CategoryLogger(categoryCacheStore, categoryCacheStore, log);

                // Assuming apps are added in order to save multiple queries to the database.
                var existingAppCount = appStore.Count();

                // Loop through apps. App store will save every 100,000 apps
                var appsToSave = new List<Models.App>();
                var appCounter = 0;
                for (int i = existingAppCount; i < count; i++)
                {
                    // Get the app from the list.
                    var app = apps[i];

                    // Store the app category if it doesn't exist.
                    if (!categoryStore.Exists(app.category))
                    {
                        var category = new Models.Category { Id = Guid.NewGuid(), Name = app.category };
                        categoryStore.Save(category);
                    }

                    // Lookup app category id.
                    var categoryId = categoryStore.GetId(app.category);

                    app.id = Guid.NewGuid();
                    app.categoryId = categoryId;
                    appsToSave.Add(app);
                    log.LogOperation(string.Format("App {0}/{1} added: {2}", i + 1, count, app.app_id));
                    appCounter++;

                    // Save apps
                    if(appCounter >= 100000)
                    {
                        appStore.SaveMany(appsToSave);
                        appsToSave.Clear();
                        appCounter = 0;
                    }
                }

                // Save the remainder
                appStore.SaveMany(appsToSave);

                log.LogOperation("DONE!!!!");
            }
        }