Example #1
0
        /// <summary>
        /// This sets up the dropdownlist for the possible bloggers and the MultiSelectList of tags
        /// </summary>
        /// <param name="context"></param>
        /// <param name="dto"></param>
        protected override void SetupSecondaryData(IGenericServicesDbContext context, DetailPostDto dto)
        {
            dto.Bloggers.SetupDropDownListContent(
                context.Set <Blog>()
                .ToList()
                .Select(x => new KeyValuePair <string, string>(x.Name, x.BlogId.ToString("D"))),
                "--- choose blogger ---");
            if (dto.PostId != 0)
            {
                //there is an entry, so set the selected value to that
                dto.Bloggers.SetSelectedValue(dto.BlogId.ToString("D"));
            }

            var preselectedTags = dto.PostId == 0
                ? new List <KeyValuePair <string, int> >()
                : context.Set <Tag>()
                                  .Where(x => x.Posts.Any(y => y.PostId == dto.PostId))
                                  .Select(x => new { Key = x.Name, Value = x.TagId })
                                  .ToList()
                                  .Select(x => new KeyValuePair <string, int>(x.Key, x.Value))
                                  .ToList();

            dto.UserChosenTags.SetupMultiSelectList(
                context.Set <Tag>().ToList().Select(x => new KeyValuePair <string, int>(x.Name, x.TagId)), preselectedTags);
        }
        /// <summary>
        /// This sets up the dropdownlist for the possible bloggers and the MultiSelectList of tags
        /// </summary>
        /// <param name="context"></param>
        /// <param name="dto"></param>
        protected override async Task SetupSecondaryDataAsync(IGenericServicesDbContext context, DetailPostDtoAsync dto)
        {
            var bloggers = await context.Set <Blog>().ToListAsync();

            dto.Bloggers.SetupDropDownListContent(bloggers.Select(x => new KeyValuePair <string, string>(x.Name, x.BlogId.ToString("D"))),
                                                  "--- choose blogger ---");
            if (dto.PostId != 0)
            {
                //there is an entry, so set the selected value to that
                dto.Bloggers.SetSelectedValue(dto.BlogId.ToString("D"));
            }

            List <KeyValuePair <string, int> > preselectedTags;

            if (dto.PostId == 0)
            {
                //create, so just produce empty list
                preselectedTags = new List <KeyValuePair <string, int> >();
            }
            else
            {
                var tags = await context.Set <Tag>()
                           .Where(x => x.Posts.Any(y => y.PostId == dto.PostId))
                           .Select(x => new { Key = x.Name, Value = x.TagId })
                           .ToListAsync();

                preselectedTags = tags.Select(x => new KeyValuePair <string, int>(x.Key, x.Value))
                                  .ToList();
            }

            dto.UserChosenTags.SetupMultiSelectList(
                context.Set <Tag>().ToList().Select(x => new KeyValuePair <string, int>(x.Name, x.TagId)), preselectedTags);
        }
        /// <summary>
        /// This will delete an item from the database
        /// </summary>
        /// <param name="keys">The keys must be given in the same order as entity framework has them</param>
        /// <returns></returns>
        public async Task <ISuccessOrErrors> DeleteAsync <TEntity>(params object[] keys) where TEntity : class
        {
            var keyProperties = _db.GetKeyProperties <TEntity>();

            if (keyProperties.Count != keys.Length)
            {
                throw new ArgumentException("The number of keys in the data entry did not match the number of keys provided");
            }

            var entityToDelete = await _db.Set <TEntity>().FindAsync(keys);

            if (entityToDelete == null)
            {
                return
                    (new SuccessOrErrors().AddSingleError(
                         "Could not delete entry as it was not in the database. Could it have been deleted by someone else?"));
            }

            _db.Set <TEntity>().Remove(entityToDelete);
            var result = await _db.SaveChangesWithCheckingAsync();

            if (result.IsValid)
            {
                result.SetSuccessMessage("Successfully deleted {0}.", typeof(TEntity).Name);
            }

            return(result);
        }
        private ISuccessOrErrors DeleteBloggerWithPost(IGenericServicesDbContext db, SimplePostDto post)
        {
            var blogger = db.Set <Blog>().SingleOrDefault(x => x.Name == post.BloggerName);

            db.Set <Blog>().Remove(blogger);
            return(SuccessOrErrors.Success("It was fine."));
        }
Example #5
0
        private async Task <ISuccessOrErrors> DeleteBloggerWithPost(IGenericServicesDbContext db, Post post)
        {
            var blogger = await db.Set <Blog>().FindAsync(post.BlogId);

            db.Set <Blog>().Remove(blogger);
            return(SuccessOrErrors.Success("It was fine."));
        }
        public static ISuccessOrErrors DeleteAssociatedAddress(IGenericServicesDbContext db, CustomerAddress customerAddress)
        {
            var address = db.Set<Address>().Find(customerAddress.AddressID);

            if (address == null)
                return
                    new SuccessOrErrors().AddSingleError(
                        "Could not delete the associated entry as it was not in the database. Could it have been deleted by someone else?");

            db.Set<Address>().Remove(address);
            return SuccessOrErrors.Success("Removed Ok");
        }
Example #7
0
        public static ISuccessOrErrors DeleteAssociatedAddress(IGenericServicesDbContext db, CustomerAddress customerAddress)
        {
            var address = db.Set <Address>().Find(customerAddress.AddressID);

            if (address == null)
            {
                return
                    (new SuccessOrErrors().AddSingleError(
                         "Could not delete the associated entry as it was not in the database. Could it have been deleted by someone else?"));
            }

            db.Set <Address>().Remove(address);
            return(SuccessOrErrors.Success("Removed Ok"));
        }
        //------------------------------------------------------------------------------------------
        //now the setup parts for the dropdown boxes

        /// <summary>
        /// This is called before a create and an update. It is an update if the dto key property is non zero.
        /// </summary>
        /// <param name="db"></param>
        /// <param name="dto"></param>
        protected override void SetupSecondaryData(IGenericServicesDbContext db, CrudSalesOrderDto dto)
        {
            var getPossibleAddresses = db.Set <CustomerAddress>().Include(x => x.Address).Where(x => x.CustomerID == dto.CustomerID).ToList();

            dto.ShipToOptions.SetupDropDownListContent(
                getPossibleAddresses.Select(
                    y =>
                    new KeyValuePair <string, string>(ListCustomerAddressDto.FormCustomerAddressFormatted(y),
                                                      y.AddressID.ToString("D"))),
                "--- choose ship to address ---");
            if (dto.SalesOrderID != 0 && dto.ShipToAddressID != null)
            {
                //there is an entry, so set the selected value to that
                dto.ShipToOptions.SetSelectedValue(((int)dto.ShipToAddressID).ToString("D"));
            }

            dto.BillToOptions.SetupDropDownListContent(
                getPossibleAddresses.Select(
                    y =>
                    new KeyValuePair <string, string>(ListCustomerAddressDto.FormCustomerAddressFormatted(y),
                                                      y.AddressID.ToString("D"))),
                "--- choose bill to address ---");
            if (dto.SalesOrderID != 0 && dto.BillToAddressID != null)
            {
                //there is an entry, so set the selected value to that
                dto.BillToOptions.SetSelectedValue(((int)dto.BillToAddressID).ToString("D"));
            }
        }
        /// <summary>
        /// This sets up useful information to show the user that he has the right order to update
        /// Note: that the SalesOrderID must be set but the others are purely for display
        /// </summary>
        /// <param name="salesOrderId"></param>
        public void SetupRestOfDto(int salesOrderId)
        {
            SalesOrderID = salesOrderId;
            var salesOrderHeader = _db.Set <SalesOrderHeader>().SingleOrDefault(x => x.SalesOrderID == salesOrderId);

            if (salesOrderHeader == null)
            {
                return;
            }

            SalesOrderNumber = salesOrderHeader.SalesOrderNumber;
            var customer = _db.Set <Customer>().SingleOrDefault(x => x.CustomerID == salesOrderHeader.CustomerID);

            if (customer == null)
            {
                return;
            }
            CustomerCompanyName = customer.CompanyName;
        }
        /// <summary>
        /// This is used to update the SalesOrderHeader total when a line item is deleted
        /// </summary>
        /// <param name="db"></param>
        /// <param name="lineItemBeingDeleted"></param>
        /// <returns></returns>
        public static ISuccessOrErrors UpdateSalesOrderHeader(IGenericServicesDbContext db, SalesOrderDetail lineItemBeingDeleted)
        {
            var salesOrderHeader = db.Set<SalesOrderHeader>().Include(x => x.SalesOrderDetails).Single(x => x.SalesOrderID == lineItemBeingDeleted.SalesOrderID);

            salesOrderHeader.SubTotal =
                salesOrderHeader.SalesOrderDetails.Where(
                    x => x.SalesOrderDetailID != lineItemBeingDeleted.SalesOrderDetailID).Sum(x => x.LineTotal);

            return SuccessOrErrors.Success("Removed Ok");
        }
        /// <summary>
        /// This is used to update the SalesOrderHeader total when a line item is deleted
        /// </summary>
        /// <param name="db"></param>
        /// <param name="lineItemBeingDeleted"></param>
        /// <returns></returns>
        public static ISuccessOrErrors UpdateSalesOrderHeader(IGenericServicesDbContext db, SalesOrderDetail lineItemBeingDeleted)
        {
            var salesOrderHeader = db.Set <SalesOrderHeader>().Include(x => x.SalesOrderDetails).Single(x => x.SalesOrderID == lineItemBeingDeleted.SalesOrderID);

            salesOrderHeader.SubTotal =
                salesOrderHeader.SalesOrderDetails.Where(
                    x => x.SalesOrderDetailID != lineItemBeingDeleted.SalesOrderDetailID).Sum(x => x.LineTotal);

            return(SuccessOrErrors.Success("Removed Ok"));
        }
Example #12
0
        /// <summary>
        /// This will delete an item from the database
        /// </summary>
        /// <param name="keys">The keys must be given in the same order as entity framework has them</param>
        /// <returns></returns>
        public async Task <ISuccessOrErrors> DeleteAsync <TEntity>(params object[] keys) where TEntity : class
        {
            var entityToDelete = await _db.Set <TEntity>().FindAsync(keys).ConfigureAwait(false);

            if (entityToDelete == null)
            {
                return
                    (new SuccessOrErrors().AddSingleError(
                         "Could not delete entry as it was not in the database. Could it have been deleted by someone else?"));
            }

            _db.Set <TEntity>().Remove(entityToDelete);
            var result = await _db.SaveChangesWithCheckingAsync().ConfigureAwait(false);

            if (result.IsValid)
            {
                result.SetSuccessMessage("Successfully deleted {0}.", typeof(TEntity).Name);
            }

            return(result);
        }
        //This code is the second attempt at improving the SQL query for Customers
        //It uses the from ... in format of LINQ which allows a let assignment in it.
        //This produces a better SQL query

        protected override IQueryable <ListCustomerVer2Dto> ListQueryUntracked(IGenericServicesDbContext context)
        {
            return(from x in context.Set <Customer>()
                   let hasBoughtBefore = x.SalesOrderHeaders.Any()
                                         select new ListCustomerVer2Dto
            {
                CustomerID = x.CustomerID,
                CompanyName = x.CompanyName,
                FullName = x.Title + (x.Title == null ? "" : " ") + x.FirstName + " " + x.LastName + " " + x.Suffix,
                HasBoughtBefore = hasBoughtBefore,
                TotalAllOrders = hasBoughtBefore ? x.SalesOrderHeaders.Sum(y => y.TotalDue) : 0
            });
        }
        private static ISuccessOrErrors SetupRestOfDto(IGenericServicesDbContext db, CrudSalesOrderDto dto)
        {
            var status = SuccessOrErrors.Success("OK if no errors set");

            var shipToAddressId = dto.ShipToOptions.SelectedValueAsInt;

            dto.ShipToAddressID = shipToAddressId != null &&
                                  db.Set <CustomerAddress>()
                                  .SingleOrDefault(
                x => x.AddressID == shipToAddressId && x.CustomerID == dto.CustomerID) != null
                ? shipToAddressId
                : null;             //could do more error checking here, but we fail safe if any error

            var billToAddressId = dto.BillToOptions.SelectedValueAsInt;

            dto.BillToAddressID = billToAddressId != null &&
                                  db.Set <CustomerAddress>()
                                  .SingleOrDefault(
                x => x.AddressID == billToAddressId && x.CustomerID == dto.CustomerID) != null
                ? billToAddressId
                : null;             //could do more error checking here, but we fail safe if any error

            return(status);
        }
        protected override ISuccessOrErrors <SalesOrderDetail> CreateDataFromDto(IGenericServicesDbContext context, CreateLineItemDto source)
        {
            var status = base.CreateDataFromDto(context, source);

            if (!status.IsValid)
            {
                return(status);
            }

            //we read the list price from the products
            status.Result.UnitPrice         = context.Set <Product>().Single(x => x.ProductID == source.ProductID).ListPrice;
            status.Result.UnitPriceDiscount = 0;

            return(status);
        }
 //For update to work we need to include the Address for it to be tracked.
 protected override CustomerAddress FindItemTrackedForUpdate(IGenericServicesDbContext context)
 {
     return(context.Set <CustomerAddress>()
            .Where(x => x.CustomerID == CustomerID && x.AddressID == AddressID)
            .Include(x => x.Address).SingleOrDefault());
 }
Example #17
0
 /// <summary>
 /// This is used for update. This returns the TEntity item that fits the key(s) in the DTO.
 /// Override this if you need to include any related entries when doing a complex update.
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 internal protected virtual async Task <TEntity> FindItemTrackedForUpdateAsync(IGenericServicesDbContext context)
 {
     return(await context.Set <TEntity>().FindAsync(GetKeyValues(context)));
 }
 /// <summary>
 /// This returns the TEntity item that fits the key(s) in the DTO.
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 internal protected override async Task <TEntity> FindItemTrackedForUpdateAsync(IGenericServicesDbContext context)
 {
     using (new LogStartStop(this))
         return(await context.Set <TEntity>().FindAsync(GetKeyValues(context)).ConfigureAwait(false));
 }
Example #19
0
 /// <summary>
 /// Used only by Update. This returns the TEntity item that fits the key(s) in the DTO.
 /// Override this if you need to include any related entries when doing a complex update.
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 internal protected virtual TEntity FindItemTrackedForUpdate(IGenericServicesDbContext context)
 {
     return(context.Set <TEntity>().Find(GetKeyValues(context)));
 }
Example #20
0
 /// <summary>
 /// This method is called to get the data table. Can be overridden if include statements are needed.
 /// </summary>
 /// <param name="context"></param>
 /// <returns>returns an IQueryable of the table TEntity as Untracked</returns>
 protected virtual IQueryable <TEntity> GetDataUntracked(IGenericServicesDbContext context)
 {
     return(context.Set <TEntity>().AsNoTracking());
 }
Example #21
0
 public bool EntityExists(int key)
 {
     return(_db.Set <TEntity>().Find(key) != null);
 }
 private ISuccessOrErrors DeleteBloggerWithPost(IGenericServicesDbContext db, SimplePostDto post)
 {
     var blogger = db.Set<Blog>().SingleOrDefault(x => x.Name == post.BloggerName);
     db.Set<Blog>().Remove(blogger);
     return SuccessOrErrors.Success("It was fine.");
 }
 private async Task<ISuccessOrErrors> DeleteBloggerWithPost(IGenericServicesDbContext db, Post post)
 {
     var blogger = await db.Set<Blog>().FindAsync(post.BlogId);
     db.Set<Blog>().Remove(blogger);
     return SuccessOrErrors.Success("It was fine.");
 }