private void UpdateProductGenericAttributes(Product entityToUpdate, List <ProductGenericAttributeDto> dtoGenericAttributes)
        {
            if (dtoGenericAttributes == null)
            {
                return;
            }

            var attributes = new List <GenericAttribute>();

            // IF LIST IS EMPTY DELETE ALL GENERIC ATTRIBUTES!
            if (dtoGenericAttributes.Count == 0)
            {
                attributes = _genericAttributeService.GetAttributesForEntity(entityToUpdate.Id, "Product").ToList();
                attributes = attributes.Where(a => a.Key != "nop.product.admindid" && a.Key != "nop.product.attributevalue.recordid" && a.Key != "nop.product.attribute.combination.records" && a.Key != "nop.product.attribute.combination.admind_id").ToList();
                _genericAttributeService.DeleteAttributes(attributes);
            }

            var attribute = new GenericAttribute();

            foreach (var ga in dtoGenericAttributes)
            {
                var key = string.Format("nop.product.{0}", ga.Name);
                attribute = attributes.Where(a => a.Key == key).FirstOrDefault();
                if (attribute == null)
                {
                    _genericAttributeService.SaveAttribute <string>(entityToUpdate, key, ga.Value);
                }
                else
                {
                    attribute.Value = ga.Value;
                    _genericAttributeService.UpdateAttribute(attribute);
                }
            }
        }
        public void Execute()
        {
            var tokens = _genericAttributeService.GetAttributesByKey(BopCustomerDefaults.AccountActivationTokenAttribute)
                         .Where(token => token.CreatedOrUpdatedDateUTC < DateTime.Now.AddMinutes(-2)).ToList();

            _genericAttributeService.DeleteAttributes(tokens);
        }
Example #3
0
        /// <summary>
        /// Delete guest customers using LINQ
        /// </summary>
        /// <param name="createdFromUtc">Created from</param>
        /// <param name="createdToUtc">Created to</param>
        /// <returns>Number of delete customers</returns>
        protected virtual int DeleteGuestCustomersUseLinq(DateTime?createdFromUtc, DateTime?createdToUtc)
        {
            var guestRole = GetCustomerRoleBySystemName(SystemCustomerRoleNames.Guests);

            if (guestRole == null)
            {
                throw new GameException("'Guests' role could not be loaded");
            }

            var query = _customerRepository.Table;

            if (createdFromUtc.HasValue)
            {
                query = query.Where(c => createdFromUtc.Value <= c.CreatedOnUtc);
            }
            if (createdToUtc.HasValue)
            {
                query = query.Where(c => createdToUtc.Value >= c.CreatedOnUtc);
            }
            query = query.Where(c => c.CustomerCustomerRoleMapping.Select(cr => cr.CustomerRoleId).Contains(guestRole.Id));
            //don't delete system accounts
            query = query.Where(c => !c.IsSystemAccount);

            //only distinct customers (group by ID)
            query = from c in query
                    group c by c.Id
                    into cGroup
                    orderby cGroup.Key
                    select cGroup.FirstOrDefault();

            query = query.OrderBy(c => c.Id);
            var customers = query.ToList();

            var totalRecordsDeleted = 0;

            foreach (var c in customers)
            {
                try
                {
                    //delete attributes
                    var attributes = _genericAttributeService.GetAttributesForEntity(c.Id, "Customer");
                    _genericAttributeService.DeleteAttributes(attributes);

                    //delete from database
                    _customerRepository.Delete(c);
                    totalRecordsDeleted++;
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc);
                }
            }
            return(totalRecordsDeleted);
        }
        /// <summary>
        /// Uninstall the plugin
        /// </summary>
        public override void Uninstall()
        {
            //settings
            _settingService.DeleteSetting <FraudLabsProSettings>();

            //generic attributes
            var orders = _orderService.SearchOrders();

            foreach (var order in orders)
            {
                var genericAttributes = _genericAttributeService.GetAttributesForEntity(order.Id, order.GetType().Name).ToList()
                                        .Where(w => w.Key.Equals(FraudLabsProDefaults.OrderResultAttribute) || w.Key.Equals(FraudLabsProDefaults.OrderStatusAttribute))
                                        .ToArray();
                if (genericAttributes.Any())
                {
                    _genericAttributeService.DeleteAttributes(genericAttributes);
                }
            }

            //locales
            _localizationService.DeletePluginLocaleResources("Plugins.Misc.FraudLabsPro");

            base.Uninstall();
        }
Example #5
0
        /// <summary>
        /// Delete guest customer records
        /// </summary>
        /// <param name="createdFromUtc">Created date from (UTC); null to load all records</param>
        /// <param name="createdToUtc">Created date to (UTC); null to load all records</param>
        /// <param name="onlyWithoutShoppingCart">A value indicating whether to delete customers only without shopping cart</param>
        /// <returns>Number of deleted customers</returns>
        public virtual int DeleteGuestCustomers(DateTime?createdFromUtc, DateTime?createdToUtc, bool onlyWithoutShoppingCart)
        {
            if (_commonSettings.UseStoredProceduresIfSupported && _dataProvider.StoredProceduredSupported)
            {
                //stored procedures are enabled and supported by the database.
                //It's much faster than the LINQ implementation below

                #region Stored procedure

                //prepare parameters
                var pOnlyWithoutShoppingCart = _dataProvider.GetParameter();
                pOnlyWithoutShoppingCart.ParameterName = "OnlyWithoutShoppingCart";
                pOnlyWithoutShoppingCart.Value         = onlyWithoutShoppingCart;
                pOnlyWithoutShoppingCart.DbType        = DbType.Boolean;

                var pCreatedFromUtc = _dataProvider.GetParameter();
                pCreatedFromUtc.ParameterName = "CreatedFromUtc";
                pCreatedFromUtc.Value         = createdFromUtc.HasValue ? (object)createdFromUtc.Value : DBNull.Value;
                pCreatedFromUtc.DbType        = DbType.DateTime;

                var pCreatedToUtc = _dataProvider.GetParameter();
                pCreatedToUtc.ParameterName = "CreatedToUtc";
                pCreatedToUtc.Value         = createdToUtc.HasValue ? (object)createdToUtc.Value : DBNull.Value;
                pCreatedToUtc.DbType        = DbType.DateTime;

                var pTotalRecordsDeleted = _dataProvider.GetParameter();
                pTotalRecordsDeleted.ParameterName = "TotalRecordsDeleted";
                pTotalRecordsDeleted.Direction     = ParameterDirection.Output;
                pTotalRecordsDeleted.DbType        = DbType.Int32;

                //invoke stored procedure
                _dbContext.ExecuteSqlCommand(
                    "EXEC [DeleteGuests] @OnlyWithoutShoppingCart, @CreatedFromUtc, @CreatedToUtc, @TotalRecordsDeleted OUTPUT",
                    false, null,
                    pOnlyWithoutShoppingCart,
                    pCreatedFromUtc,
                    pCreatedToUtc,
                    pTotalRecordsDeleted);

                int totalRecordsDeleted = (pTotalRecordsDeleted.Value != DBNull.Value) ? Convert.ToInt32(pTotalRecordsDeleted.Value) : 0;
                return(totalRecordsDeleted);

                #endregion
            }
            else
            {
                //stored procedures aren't supported. Use LINQ

                #region No stored procedure

                var guestRole = GetCustomerRoleBySystemName(SystemCustomerRoleNames.Guests);
                if (guestRole == null)
                {
                    throw new NopException("'Guests' role could not be loaded");
                }

                var query = _customerRepository.Table;
                if (createdFromUtc.HasValue)
                {
                    query = query.Where(c => createdFromUtc.Value <= c.CreatedOnUtc);
                }
                if (createdToUtc.HasValue)
                {
                    query = query.Where(c => createdToUtc.Value >= c.CreatedOnUtc);
                }
                query = query.Where(c => c.CustomerRoles.Select(cr => cr.Id).Contains(guestRole.Id));
                if (onlyWithoutShoppingCart)
                {
                    query = query.Where(c => !c.ShoppingCartItems.Any());
                }
                //no orders
                query = from c in query
                        join o in _orderRepository.Table on c.Id equals o.CustomerId into c_o
                        from o in c_o.DefaultIfEmpty()
                        where !c_o.Any()
                        select c;
                //no blog comments
                query = from c in query
                        join bc in _blogCommentRepository.Table on c.Id equals bc.CustomerId into c_bc
                        from bc in c_bc.DefaultIfEmpty()
                        where !c_bc.Any()
                        select c;
                //no news comments
                query = from c in query
                        join nc in _newsCommentRepository.Table on c.Id equals nc.CustomerId into c_nc
                        from nc in c_nc.DefaultIfEmpty()
                        where !c_nc.Any()
                        select c;
                //no product reviews
                query = from c in query
                        join pr in _productReviewRepository.Table on c.Id equals pr.CustomerId into c_pr
                        from pr in c_pr.DefaultIfEmpty()
                        where !c_pr.Any()
                        select c;
                //no product reviews helpfulness
                query = from c in query
                        join prh in _productReviewHelpfulnessRepository.Table on c.Id equals prh.CustomerId into c_prh
                        from prh in c_prh.DefaultIfEmpty()
                        where !c_prh.Any()
                        select c;
                //no poll voting
                query = from c in query
                        join pvr in _pollVotingRecordRepository.Table on c.Id equals pvr.CustomerId into c_pvr
                        from pvr in c_pvr.DefaultIfEmpty()
                        where !c_pvr.Any()
                        select c;
                //no forum posts
                query = from c in query
                        join fp in _forumPostRepository.Table on c.Id equals fp.CustomerId into c_fp
                        from fp in c_fp.DefaultIfEmpty()
                        where !c_fp.Any()
                        select c;
                //no forum topics
                query = from c in query
                        join ft in _forumTopicRepository.Table on c.Id equals ft.CustomerId into c_ft
                        from ft in c_ft.DefaultIfEmpty()
                        where !c_ft.Any()
                        select c;
                //don't delete system accounts
                query = query.Where(c => !c.IsSystemAccount);

                //only distinct customers (group by ID)
                query = from c in query
                        group c by c.Id
                        into cGroup
                        orderby cGroup.Key
                        select cGroup.FirstOrDefault();

                query = query.OrderBy(c => c.Id);
                var customers = query.ToList();


                int totalRecordsDeleted = 0;
                foreach (var c in customers)
                {
                    try
                    {
                        //delete attributes
                        var attributes = _genericAttributeService.GetAttributesForEntity(c.Id, "Customer");
                        _genericAttributeService.DeleteAttributes(attributes);

                        //delete from database
                        _customerRepository.Delete(c);
                        totalRecordsDeleted++;
                    }
                    catch (Exception exc)
                    {
                        Debug.WriteLine(exc);
                    }
                }
                return(totalRecordsDeleted);

                #endregion
            }
        }
Example #6
0
        /// <summary>
        /// Permanent delete of customer
        /// </summary>
        /// <param name="customer">Customer</param>
        public virtual void PermanentDeleteCustomer(Customer customer)
        {
            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            //blog comments
            var blogComments = _blogService.GetAllComments(customerId: customer.Id);

            _blogService.DeleteBlogComments(blogComments);

            //news comments
            var newsComments = _newsService.GetAllComments(customerId: customer.Id);

            _newsService.DeleteNewsComments(newsComments);



            //external authentication record
            foreach (var ear in customer.ExternalAuthenticationRecords)
            {
                _externalAuthenticationService.DeleteExternalAuthenticationRecord(ear);
            }

            //forum subscriptions
            var forumSubscriptions = _forumService.GetAllSubscriptions(customer.Id);

            foreach (var forumSubscription in forumSubscriptions)
            {
                _forumService.DeleteSubscription(forumSubscription);
            }


            //private messages (sent)
            foreach (var pm in _forumService.GetAllPrivateMessages(0, customer.Id, 0, null, null, null, null))
            {
                _forumService.DeletePrivateMessage(pm);
            }

            //private messages (received)
            foreach (var pm in _forumService.GetAllPrivateMessages(0, 0, customer.Id, null, null, null, null))
            {
                _forumService.DeletePrivateMessage(pm);
            }

            //newsletter
            var allStores = _storeService.GetAllStores();

            foreach (var store in allStores)
            {
                var newsletter = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(customer.Email, store.Id);
                if (newsletter != null)
                {
                    _newsLetterSubscriptionService.DeleteNewsLetterSubscription(newsletter);
                }
            }

            //addresses
            foreach (var address in customer.Addresses)
            {
                _customerService.RemoveCustomerAddress(customer, address);
                _customerService.UpdateCustomer(customer);
                //now delete the address record
                _addressService.DeleteAddress(address);
            }

            //generic attributes
            var keyGroup          = customer.GetUnproxiedEntityType().Name;
            var genericAttributes = _genericAttributeService.GetAttributesForEntity(customer.Id, keyGroup);

            _genericAttributeService.DeleteAttributes(genericAttributes);

            //ignore ActivityLog
            //ignore ForumPost, ForumTopic, ignore ForumPostVote
            //ignore Log
            //ignore PollVotingRecord
            //ignore ProductReviewHelpfulness
            //ignore RecurringPayment
            //ignore ReturnRequest
            //ignore RewardPointsHistory
            //and we do not delete orders

            //remove from Registered role, add to Guest one
            if (customer.IsRegistered())
            {
                var registeredRole = _customerService.GetCustomerRoleBySystemName(GSCustomerDefaults.RegisteredRoleName);
                customer.CustomerCustomerRoleMappings
                .Remove(customer.CustomerCustomerRoleMappings.FirstOrDefault(mapping => mapping.CustomerRoleId == registeredRole.Id));
            }

            if (!customer.IsGuest())
            {
                var guestRole = _customerService.GetCustomerRoleBySystemName(GSCustomerDefaults.GuestsRoleName);
                customer.CustomerCustomerRoleMappings.Add(new CustomerCustomerRoleMapping {
                    CustomerRole = guestRole
                });
            }

            var email = customer.Email;

            //clear other information
            customer.Email             = string.Empty;
            customer.EmailToRevalidate = string.Empty;
            customer.Username          = string.Empty;
            customer.Active            = false;
            customer.Deleted           = true;
            _customerService.UpdateCustomer(customer);

            //raise event
            _eventPublisher.Publish(new CustomerPermanentlyDeleted(customer.Id, email));
        }
Example #7
0
        /// <summary>
        /// Permanent delete of customer
        /// </summary>
        /// <param name="customer">Customer</param>
        public virtual void PermanentDeleteCustomer(Customer customer)
        {
            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            //blog comments
            var blogComments = _blogService.GetAllComments(customerId: customer.Id);

            _blogService.DeleteBlogComments(blogComments);

            //news comments
            var newsComments = _newsService.GetAllComments(customerId: customer.Id);

            _newsService.DeleteNewsComments(newsComments);

            //back in stock subscriptions
            var backInStockSubscriptions = _backInStockSubscriptionService.GetAllSubscriptionsByCustomerId(customer.Id);

            foreach (var backInStockSubscription in backInStockSubscriptions)
            {
                _backInStockSubscriptionService.DeleteSubscription(backInStockSubscription);
            }

            //product review
            var productReviews   = _productService.GetAllProductReviews(customerId: customer.Id, approved: null);
            var reviewedProducts = _productService.GetProductsByIds(productReviews.Select(p => p.ProductId).Distinct().ToArray());

            _productService.DeleteProductReviews(productReviews);
            //update product totals
            foreach (var product in reviewedProducts)
            {
                _productService.UpdateProductReviewTotals(product);
            }

            //external authentication record
            foreach (var ear in customer.ExternalAuthenticationRecords)
            {
                _externalAuthenticationService.DeleteExternalAuthenticationRecord(ear);
            }

            //forum subscriptions
            var forumSubscriptions = _forumService.GetAllSubscriptions(customerId: customer.Id);

            foreach (var forumSubscription in forumSubscriptions)
            {
                _forumService.DeleteSubscription(forumSubscription);
            }

            //shopping cart items
            foreach (var sci in customer.ShoppingCartItems)
            {
                _shoppingCartService.DeleteShoppingCartItem(sci);
            }

            //private messages (sent)
            foreach (var pm in _forumService.GetAllPrivateMessages(storeId: 0, fromCustomerId: customer.Id, toCustomerId: 0,
                                                                   isRead: null, isDeletedByAuthor: null, isDeletedByRecipient: null, keywords: null))
            {
                _forumService.DeletePrivateMessage(pm);
            }
            //private messages (received)
            foreach (var pm in _forumService.GetAllPrivateMessages(storeId: 0, fromCustomerId: 0, toCustomerId: customer.Id,
                                                                   isRead: null, isDeletedByAuthor: null, isDeletedByRecipient: null, keywords: null))
            {
                _forumService.DeletePrivateMessage(pm);
            }

            //newsletter
            var allStores = _storeService.GetAllStores();

            foreach (var store in allStores)
            {
                var newsletter = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(customer.Email, store.Id);
                if (newsletter != null)
                {
                    _newsLetterSubscriptionService.DeleteNewsLetterSubscription(newsletter);
                }
            }

            //addresses
            foreach (var address in customer.Addresses)
            {
                customer.RemoveAddress(address);
                _customerService.UpdateCustomer(customer);
                //now delete the address record
                _addressService.DeleteAddress(address);
            }

            //generic attributes
            var keyGroup          = customer.GetUnproxiedEntityType().Name;
            var genericAttributes = _genericAttributeService.GetAttributesForEntity(customer.Id, keyGroup);

            _genericAttributeService.DeleteAttributes(genericAttributes);

            //ignore ActivityLog
            //ignore ForumPost, ForumTopic, ignore ForumPostVote
            //ignore Log
            //ignore PollVotingRecord
            //ignore ProductReviewHelpfulness
            //ignore RecurringPayment
            //ignore ReturnRequest
            //ignore RewardPointsHistory
            //and we do not delete orders

            //remove from Registered role, add to Guest one
            if (customer.IsRegistered())
            {
                var registeredRole = _customerService.GetCustomerRoleBySystemName(NopCustomerDefaults.RegisteredRoleName);
                customer.CustomerCustomerRoleMappings
                .Remove(customer.CustomerCustomerRoleMappings.FirstOrDefault(mapping => mapping.CustomerRoleId == registeredRole.Id));
            }
            if (!customer.IsGuest())
            {
                var guestRole = _customerService.GetCustomerRoleBySystemName(NopCustomerDefaults.GuestsRoleName);
                customer.CustomerCustomerRoleMappings.Add(new CustomerCustomerRoleMapping {
                    CustomerRole = guestRole
                });
            }

            var email = customer.Email;

            //clear other information
            customer.Email             = "";
            customer.EmailToRevalidate = "";
            customer.Username          = "";
            customer.Active            = false;
            customer.Deleted           = true;
            _customerService.UpdateCustomer(customer);

            //raise event
            _eventPublisher.Publish(new CustomerPermanentlyDeleted(customer.Id, email));
        }
        /// <summary>
        /// Delete guest customers using LINQ
        /// </summary>
        /// <param name="createdFromUtc">Created from</param>
        /// <param name="createdToUtc">Created to</param>
        /// <param name="onlyWithoutShoppingCart">Delete only without shopping cart</param>
        /// <returns>Number of delete customers</returns>
        protected virtual int DeleteGuestCustomersUseLinq(DateTime?createdFromUtc, DateTime?createdToUtc, bool onlyWithoutShoppingCart)
        {
            var guestRole = GetCustomerRoleBySystemName(SystemCustomerRoleNames.Guests);

            if (guestRole == null)
            {
                throw new NopException("'Guests' role could not be loaded");
            }

            var query = _customerRepository.Table;

            if (createdFromUtc.HasValue)
            {
                query = query.Where(c => createdFromUtc.Value <= c.CreatedOnUtc);
            }
            if (createdToUtc.HasValue)
            {
                query = query.Where(c => createdToUtc.Value >= c.CreatedOnUtc);
            }
            query = query.Where(c => c.CustomerRoles.Select(cr => cr.Id).Contains(guestRole.Id));
            if (onlyWithoutShoppingCart)
            {
                query = query.Where(c => !c.ShoppingCartItems.Any());
            }
            //no orders
            query = from c in query
                    join o in _orderRepository.Table on c.Id equals o.CustomerId into c_o
                    from o in c_o.DefaultIfEmpty()
                    where !c_o.Any()
                    select c;

            //no blog comments
            query = from c in query
                    join bc in _blogCommentRepository.Table on c.Id equals bc.CustomerId into c_bc
                    from bc in c_bc.DefaultIfEmpty()
                    where !c_bc.Any()
                    select c;

            //no news comments
            query = from c in query
                    join nc in _newsCommentRepository.Table on c.Id equals nc.CustomerId into c_nc
                    from nc in c_nc.DefaultIfEmpty()
                    where !c_nc.Any()
                    select c;

            //no product reviews
            query = from c in query
                    join pr in _productReviewRepository.Table on c.Id equals pr.CustomerId into c_pr
                    from pr in c_pr.DefaultIfEmpty()
                    where !c_pr.Any()
                    select c;

            //no product reviews helpfulness
            query = from c in query
                    join prh in _productReviewHelpfulnessRepository.Table on c.Id equals prh.CustomerId into c_prh
                    from prh in c_prh.DefaultIfEmpty()
                    where !c_prh.Any()
                    select c;

            //no poll voting
            query = from c in query
                    join pvr in _pollVotingRecordRepository.Table on c.Id equals pvr.CustomerId into c_pvr
                    from pvr in c_pvr.DefaultIfEmpty()
                    where !c_pvr.Any()
                    select c;

            //no forum posts
            query = from c in query
                    join fp in _forumPostRepository.Table on c.Id equals fp.CustomerId into c_fp
                    from fp in c_fp.DefaultIfEmpty()
                    where !c_fp.Any()
                    select c;

            //no forum topics
            query = from c in query
                    join ft in _forumTopicRepository.Table on c.Id equals ft.CustomerId into c_ft
                    from ft in c_ft.DefaultIfEmpty()
                    where !c_ft.Any()
                    select c;

            //don't delete system accounts
            query = query.Where(c => !c.IsSystemAccount);

            //only distinct customers (group by ID)
            query = from c in query
                    group c by c.Id
                    into cGroup
                    orderby cGroup.Key
                    select cGroup.FirstOrDefault();

            query = query.OrderBy(c => c.Id);
            var customers = query.ToList();

            var totalRecordsDeleted = 0;

            foreach (var c in customers)
            {
                try
                {
                    //delete attributes
                    var attributes = _genericAttributeService.GetAttributesForEntity(c.Id, "Customer");
                    _genericAttributeService.DeleteAttributes(attributes);

                    //delete from database
                    _customerRepository.Delete(c);
                    totalRecordsDeleted++;
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc);
                }
            }
            return(totalRecordsDeleted);
        }
Example #9
0
        /// <summary>
        /// Delete guest user records
        /// </summary>
        /// <param name="createdFromUtc">Created date from (UTC); null to load all records</param>
        /// <param name="createdToUtc">Created date to (UTC); null to load all records</param>
        /// <returns>Number of deleted users</returns>
        public virtual int DeleteGuestUsers(DateTime?createdFromUtc, DateTime?createdToUtc)
        {
            if (_commonSettings.UseStoredProceduresIfSupported && _dataProvider.StoredProceduredSupported)
            {
                //stored procedures are enabled and supported by the database.
                //It's much faster than the LINQ implementation below

                #region Stored procedure

                //prepare parameters
                var pCreatedFromUtc = _dataProvider.GetParameter();
                pCreatedFromUtc.ParameterName = "CreatedFromUtc";
                pCreatedFromUtc.Value         = createdFromUtc.HasValue ? (object)createdFromUtc.Value : DBNull.Value;
                pCreatedFromUtc.DbType        = DbType.DateTime;

                var pCreatedToUtc = _dataProvider.GetParameter();
                pCreatedToUtc.ParameterName = "CreatedToUtc";
                pCreatedToUtc.Value         = createdToUtc.HasValue ? (object)createdToUtc.Value : DBNull.Value;
                pCreatedToUtc.DbType        = DbType.DateTime;

                var pTotalRecordsDeleted = _dataProvider.GetParameter();
                pTotalRecordsDeleted.ParameterName = "TotalRecordsDeleted";
                pTotalRecordsDeleted.Direction     = ParameterDirection.Output;
                pTotalRecordsDeleted.DbType        = DbType.Int32;

                //invoke stored procedure
                _dbContext.ExecuteSqlCommand(
                    "EXEC [DeleteGuests]  @CreatedFromUtc, @CreatedToUtc, @TotalRecordsDeleted OUTPUT",
                    false, null,
                    pCreatedFromUtc,
                    pCreatedToUtc,
                    pTotalRecordsDeleted);

                int totalRecordsDeleted = (pTotalRecordsDeleted.Value != DBNull.Value) ? Convert.ToInt32(pTotalRecordsDeleted.Value) : 0;
                return(totalRecordsDeleted);

                #endregion
            }
            else
            {
                //stored procedures aren't supported. Use LINQ

                #region No stored procedure

                var guestRole = GetUserRoleBySystemName(SystemUserRoleNames.Guests);
                if (guestRole == null)
                {
                    throw new SysException("'Guests' role could not be loaded");
                }

                var query = _userRepository.Table;
                if (createdFromUtc.HasValue)
                {
                    query = query.Where(c => createdFromUtc.Value <= c.CreatedOnUtc);
                }
                if (createdToUtc.HasValue)
                {
                    query = query.Where(c => createdToUtc.Value >= c.CreatedOnUtc);
                }
                query = query.Where(c => c.UserRoles.Select(cr => cr.Id).Contains(guestRole.Id));

                //don't delete system accounts
                query = query.Where(c => !c.IsSystemAccount);

                //only distinct users (group by ID)
                query = from c in query
                        group c by c.Id
                        into cGroup
                        orderby cGroup.Key
                        select cGroup.FirstOrDefault();

                query = query.OrderBy(c => c.Id);
                var users = query.ToList();


                int totalRecordsDeleted = 0;
                foreach (var c in users)
                {
                    try
                    {
                        //delete attributes
                        var attributes = _genericAttributeService.GetAttributesForEntity(c.Id, "User");
                        _genericAttributeService.DeleteAttributes(attributes);

                        //delete from database
                        _userRepository.Delete(c);
                        totalRecordsDeleted++;
                    }
                    catch (Exception exc)
                    {
                        Debug.WriteLine(exc);
                    }
                }
                return(totalRecordsDeleted);

                #endregion
            }
        }
        /// <summary>
        /// Uninstall the plugin
        /// </summary>
        public override void Uninstall()
        {
            //generic attributes
            var onDateSettings = _rewardPointsOnDateSettingsService.GetAllRewardPointsOnDateSettings().ToList();

            onDateSettings.ForEach(setting => _genericAttributeService.SaveAttribute(setting, "CustomersAwardedOnDate", string.Empty));

            _blogService.GetAllComments().ToList().ForEach(comment =>
                                                           _genericAttributeService.SaveAttribute(comment, "CustomerAwardedForBlogComment", string.Empty, comment.StoreId));

            _newsService.GetAllComments().ToList().ForEach(comment =>
                                                           _genericAttributeService.SaveAttribute(comment, "CustomerAwardedForNewsComment", string.Empty, comment.StoreId));

            _productService.GetAllProductReviews(0, null).ToList().ForEach(review =>
                                                                           _genericAttributeService.SaveAttribute(review, "CustomerAwardedForProductReview", string.Empty, review.StoreId));

            _newsLetterSubscriptionService.GetAllNewsLetterSubscriptions().ToList().ForEach(subscription =>
                                                                                            _genericAttributeService.SaveAttribute(subscription, "CustomerAwardedForSubscription", string.Empty, subscription.StoreId));

            _customerService.GetAllCustomers().ToList().ForEach(customer =>
                                                                _genericAttributeService.DeleteAttributes(_genericAttributeService.GetAttributesForEntity(customer.Id, "Customer")
                                                                                                          .Where(attribute => attribute.Key.Equals("PurchaseStartTime")).ToList()));

            //localized properties
            var localizedSettings = new[]
            {
                _settingService.GetSetting("RewardPointsForBlogCommentsSettings.Message"),
                _settingService.GetSetting("RewardPointsForFastPurchaseSettings.Message"),
                _settingService.GetSetting("RewardPointsForFirstPurchaseSettings.Message"),
                _settingService.GetSetting("RewardPointsForNewsCommentsSettings.Message"),
                _settingService.GetSetting("RewardPointsForNewsletterSubscriptionsSettings.Message"),
                _settingService.GetSetting("RewardPointsForProductReviewsSettings.Message")
            }.Where(setting => setting != null).ToList();

            foreach (var language in _languageService.GetAllLanguages(true))
            {
                localizedSettings.ForEach(setting => _localizedEntityService.SaveLocalizedValue(setting, x => x.Value, string.Empty, language.Id));
                onDateSettings.ForEach(setting => _localizedEntityService.SaveLocalizedValue(setting, x => x.Message, string.Empty, language.Id));
            }

            //database objects
            _objectContext.Uninstall();

            //settings
            _settingService.DeleteSetting <RewardPointsForBlogCommentsSettings>();
            _settingService.DeleteSetting <RewardPointsForFastPurchaseSettings>();
            _settingService.DeleteSetting <RewardPointsForFirstPurchaseSettings>();
            _settingService.DeleteSetting <RewardPointsForNewsCommentsSettings>();
            _settingService.DeleteSetting <RewardPointsForNewsletterSubscriptionsSettings>();
            _settingService.DeleteSetting <RewardPointsForProductReviewsSettings>();
            _settingService.DeleteSetting <RewardPointsForRegistrationSettings>();

            //scheduled task
            var task = _scheduleTaskService.GetTaskByType(EXTENDED_REWARD_POINTS_PROGRAM_TASK_TYPE);

            if (task != null)
            {
                _scheduleTaskService.DeleteTask(task);
            }

            //locales
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.Fields.ActivatePointsImmediately");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.Fields.ActivatePointsImmediately.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.Fields.ActivationDelay");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.Fields.ActivationDelay.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.Fields.IsEnabled");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.Fields.IsEnabled.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.Fields.Message");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.Fields.Message.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.Fields.Points");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.Fields.Points.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForBlogComments");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForBlogComments.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForFirstPurchase");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForFirstPurchase.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForFastPurchase");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForFastPurchase.Fields.Minutes");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForFastPurchase.Fields.Minutes.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForFastPurchase.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForNewsComments");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForNewsComments.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForNewsletterSubscriptions");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForNewsletterSubscriptions.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForProductReviews");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForProductReviews.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForRegistration");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForRegistration.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.RewardPointsOnDate");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.RewardPointsOnDate.AddNew");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.RewardPointsOnDate.Edit");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.RewardPointsOnDate.Fields.AwardingDate");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.RewardPointsOnDate.Fields.AwardingDate.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.RewardPointsOnDate.Fields.CustomerRole");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.RewardPointsOnDate.Fields.CustomerRole.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.RewardPointsOnDate.Fields.Store");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.RewardPointsOnDate.Fields.Store.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.RewardPointsOnDate.Hint");

            base.Uninstall();
        }
Example #11
0
        /// <summary>
        /// Uninstall the plugin
        /// </summary>
        public override void Uninstall()
        {
            //smtp accounts
            foreach (var store in _storeService.GetAllStores())
            {
                var emailAccountId = _settingService.GetSettingByKey <int>("SendinBlueSettings.EmailAccountId",
                                                                           storeId: store.Id, loadSharedValueIfNotFound: true);
                var emailAccount = _emailAccountService.GetEmailAccountById(emailAccountId);
                if (emailAccount != null)
                {
                    _emailAccountService.DeleteEmailAccount(emailAccount);
                }
            }

            //settings
            _settingService.DeleteSetting <SendinBlueSettings>();

            //generic attributes
            foreach (var store in _storeService.GetAllStores())
            {
                var messageTemplates = _messageTemplateService.GetAllMessageTemplates(store.Id);
                foreach (var messageTemplate in messageTemplates)
                {
                    var genericAttributes = _genericAttributeService.GetAttributesForEntity(messageTemplate.Id, messageTemplate.GetUnproxiedEntityType().Name).ToList()
                                            .Where(w => w.Key.Equals(SendinBlueDefaults.TemplateIdAttribute) || w.Key.Equals(SendinBlueDefaults.SendinBlueTemplateAttribute))
                                            .ToArray();
                    _genericAttributeService.DeleteAttributes(genericAttributes);
                }
            }

            //schedule task
            var task = _scheduleTaskService.GetTaskByType(SendinBlueDefaults.SynchronizationTask);

            if (task != null)
            {
                _scheduleTaskService.DeleteTask(task);
            }

            //locales
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.AccountInfo");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.AccountInfo.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.ActivateSMTP");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.AddNewSMSNotification");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.BillingAddressPhone");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.BillingAddressPhone");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.CustomerPhone");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.CustomerPhone");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.EditTemplate");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.EditTemplate");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.AllowedTokens");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.AllowedTokens.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.ApiKey");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.ApiKey.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.CampaignList");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.CampaignList.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.CampaignSenderName");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.CampaignSenderName.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.CampaignText");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.CampaignText.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.List");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.List.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.MaKey");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.MaKey.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.Sender");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.Sender.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.SmsSenderName");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.SmsSenderName.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.SmtpKey");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.SmtpKey.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.StoreOwnerPhoneNumber");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.StoreOwnerPhoneNumber.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.TrackingScript");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.TrackingScript.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.UseMarketingAutomation");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.UseMarketingAutomation.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.UseSmsNotifications");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.UseSmsNotifications.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.UseSmtp");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Fields.UseSmtp.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.General");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.ImportProcess");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.ManualSync");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.SyncNow");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.MarketingAutomation");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.MyPhone");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.MyPhone");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.PhoneType");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.SendinBlueTemplate");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.SendinBlueTemplate");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.SendinBlueTemplate");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.SMS");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.SMS.Campaigns");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.SMS.Campaigns.Sent");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.SMS.Campaigns.Submit");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.SMSText");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.StandardTemplate");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.StandardTemplate");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.StandardTemplate");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Synchronization");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.TemplateType");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.SendinBlue.Transactional");

            base.Uninstall();
        }
Example #12
0
        public async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            #region Store

            var geocode = new GoogleGeocoder {
                ApiKey = _configuration["APIKey"]
            };

            var stores = new List <Store>();

            using (var conn = new SqlConnection(SqlHelper.ConnectionString))
            {
                var commandText = @"SELECT TOP 10 [outlet_no], [outlet_name], [price_level], [area_code], 
                                [address1], [address2], [address3], [postcode], [city], [state], [country] 
                                FROM [dbo].[btb_HHT_Outlet] WHERE [status] = 1";

                var reader = await SqlHelper.ExecuteReader(conn, CommandType.Text, commandText, null);

                while (reader.Read())
                {
                    var existingStore = await _storeRepository.GetByIdAsync(Convert.ToInt32(reader["outlet_no"]));

                    if (existingStore != null && (existingStore.Status == Convert.ToByte(true) || existingStore.UserStores.Any()))
                    {
                        continue;
                    }

                    var store = new Store
                    {
                        P_BranchNo = Convert.ToInt32(reader["outlet_no"]),
                        P_Name     = reader["outlet_name"].ToString(),
                        P_AreaCode = reader["area_code"].ToString(),
                        P_Addr1    = reader["address1"].ToString(),
                        P_Addr2    = reader["address2"].ToString(),
                        P_Addr3    = reader["address3"].ToString(),
                        P_Postcode = Convert.ToInt32(reader["postcode"].ToString()),
                        P_City     = reader["city"].ToString(),
                        P_State    = reader["state"].ToString(),
                        P_Country  = reader["country"].ToString()
                    };

                    if (!string.IsNullOrEmpty(store.P_Addr1) && store.P_Postcode != 0 &&
                        !string.IsNullOrEmpty(store.P_State) && !string.IsNullOrEmpty(store.P_Country))
                    {
                        var getCoordinates = await geocode.GeocodeAsync(
                            $"{store.P_Addr1}{store.P_Addr2}{store.P_Addr3}{store.P_Postcode}{store.P_City}{store.P_State}{store.P_Country}");

                        var addresses = getCoordinates as IList <GoogleAddress> ?? getCoordinates.ToList();
                        if (addresses.Any())
                        {
                            store.Latitude  = addresses.First().Coordinates.Latitude;
                            store.Longitude = addresses.First().Coordinates.Longitude;
                        }
                    }

                    stores.Add(store);
                }
            }

            try
            {
                var clearStores =
                    from s in _storeRepository.Table
                    where s.Status != Convert.ToByte(true)
                    select s;
                if (clearStores.Any(s => s.UserStores.Count.Equals(0)))
                {
                    var deletedStores = clearStores.Count();

                    await _storeRepository.DeleteAsync(clearStores);

                    await _userActivityService.InsertActivityAsync("ClearStore", $"Deleted old master data from [Store] (Total deleted stores = {deletedStores})", new Store());
                }

                await _storeRepository.InsertAsync(stores);

                await _userActivityService.InsertActivityAsync("DownloadStore", $"Downloaded master data to [Store] (Total added stores = {stores.Count})", new Store());
            }
            catch (Exception exception)
            {
                _logger.Error("An error occurred while downloading data to table [Store]", exception);
            }

            #endregion

            #region Role

            var roles = new List <Role>();

            using (var conn = new SqlConnection(SqlHelper.ConnectionString))
            {
                var commandText = @"SELECT DISTINCT(CASE WHEN [role] = '' OR[role] IS NULL THEN 'Outlet' ELSE[role] END) AS Role 
                                    FROM [dbo].[btb_HHT_Staff]";

                var reader = await SqlHelper.ExecuteReader(conn, CommandType.Text, commandText, null);

                while (reader.Read())
                {
                    var existingRole = _roleRepository.Table.FirstOrDefault(x => x.Name.Equals(reader["Role"].ToString(), StringComparison.InvariantCultureIgnoreCase));
                    if (existingRole != null && existingRole.Active)
                    {
                        continue;
                    }

                    if (!reader["Role"].ToString().Contains("Admin", StringComparison.InvariantCultureIgnoreCase) &&
                        !reader["Role"].ToString().Contains("Registered", StringComparison.InvariantCultureIgnoreCase))
                    {
                        var role = new Role
                        {
                            Name       = reader["Role"].ToString(),
                            SystemName = reader["Role"].ToString(),
                        };

                        roles.Add(role);
                    }
                }
            }

            try
            {
                var clearRoles =
                    from r in _roleRepository.Table
                    where !r.IsSystemRole && !r.Active
                    select r;
                if (clearRoles.Any())
                {
                    var deletedRoles = clearRoles.Count();

                    await _roleRepository.DeleteAsync(clearRoles);

                    await _userActivityService.InsertActivityAsync("ClearRole", $"Deleted old master data from [Role] (Total deleted roles = {deletedRoles})", new Role());
                }

                await _roleRepository.InsertAsync(roles);

                await _userActivityService.InsertActivityAsync("DownloadRole", $"Downloaded master data to [Role] (Total added roles = {roles.Count})", new Role());
            }
            catch (Exception exception)
            {
                _logger.Error("An error occurred while downloading data to table [Role]", exception);
            }

            #endregion

            #region User

            try
            {
                var clearUsers =
                    from u in _userRepository.Table
                    where !u.IsSystemAccount && !u.Active
                    select u;
                if (clearUsers.Any(u => u.UserStores.Count.Equals(0) && u.UserRoles.Count.Equals(0)))
                {
                    //remove from generic attribute
                    foreach (var user in clearUsers.ToList())
                    {
                        var genericAttributes = await _genericAttributeService.GetAttributesForEntityAsync(user.Id, typeof(User).Name);

                        await _genericAttributeService.DeleteAttributes(genericAttributes.ToList());
                    }

                    var deletedUsers = clearUsers.Count();

                    await _userRepository.DeleteAsync(clearUsers);

                    await _userActivityService.InsertActivityAsync("ClearUser", $"Deleted old master data from [User] (Total deleted users = {deletedUsers})", new User());
                }

                var registeredRole = _userService.GetRoleBySystemName(UserDefaults.RegisteredRoleName);

                using (var conn = new SqlConnection(SqlHelper.ConnectionString))
                {
                    var commandText = @"SELECT TOP 10 [staff_no], [staff_barcode], [staff_name], [department_code], [role], [email] 
                                        FROM [dbo].[btb_HHT_Staff]";

                    var reader = await SqlHelper.ExecuteReader(conn, CommandType.Text, commandText, null);

                    while (reader.Read())
                    {
                        var existingUser = await _userService.GetUserByUsernameAsync(reader["staff_no"].ToString());

                        if (existingUser != null && (existingUser.Active || existingUser.UserStores.Any() || existingUser.UserRoles.Any()))
                        {
                            continue;
                        }

                        var systemName = string.IsNullOrEmpty(reader["role"].ToString()) ? "Outlet" : reader["role"].ToString() == "Admin" ? "Administrators" : reader["role"].ToString();

                        if (!string.IsNullOrWhiteSpace(reader["email"].ToString()))
                        {
                            var user = new User
                            {
                                UserGuid      = Guid.NewGuid(),
                                Email         = reader["email"].ToString().Trim(),
                                Username      = reader["staff_no"].ToString(),
                                CreatedOnUtc  = DateTime.UtcNow,
                                ModifiedOnUtc = DateTime.UtcNow,
                            };

                            var role = _userService.GetRoleBySystemName(systemName);
                            user.AddUserRole(new UserRole {
                                Role = role
                            });
                            user.AddUserRole(new UserRole {
                                Role = registeredRole
                            });

                            await _userService.InsertUserAsync(user);

                            await _genericAttributeService.SaveAttributeAsync(user, UserDefaults.FirstNameAttribute,
                                                                              reader["staff_name"].ToString());

                            _userPasswordRepository.Insert(new UserPassword
                            {
                                User           = user,
                                Password       = "******",
                                PasswordFormat = PasswordFormat.Clear,
                                PasswordSalt   = string.Empty,
                                CreatedOnUtc   = DateTime.UtcNow
                            });
                        }
                    }
                }

                await _userActivityService.InsertActivityAsync("DownloadUser", $"Downloaded master data to [User] (Total added users = {_userRepository.Table.Count()})", new User());
            }
            catch (Exception exception)
            {
                _logger.Error("An error occurred while downloading data to table [User]", exception);
            }

            #endregion

            #region Item

            var items = new List <Item>();

            using (var conn = new SqlConnection(SqlHelper.ConnectionString))
            {
                var commandText = @"SELECT TOP 10 [P_StockCode], [P_Desc], [P_SubCategoryID], [P_SPrice1], [P_SPrice2], 
                                    [P_SPrice3], [P_SPrice4], [P_SPrice5], [P_SPrice6], [P_SPrice7], [P_SPrice8],
                                    [P_SPrice9], [P_SPrice10], [P_SPrice11], [P_SPrice12], [P_SPrice13], [P_SPrice14],
                                    [P_SPrice15], [P_ModifyDT], [P_OrderStatus], [P_DisplayShelfLife] 
                                    FROM [dbo].[ItemMaster]";

                var reader = await SqlHelper.ExecuteReader(conn, CommandType.Text, commandText, null);

                while (reader.Read())
                {
                    var existingItem = _itemRepository.Table.FirstOrDefault(x => x.P_StockCode.Equals(reader["P_StockCode"].ToString(), StringComparison.InvariantCultureIgnoreCase));
                    if (existingItem != null)
                    {
                        continue;
                    }

                    var item = new Item
                    {
                        P_StockCode        = reader["P_StockCode"].ToString(),
                        P_Desc             = reader["P_Desc"].ToString(),
                        P_SubCategoryID    = Convert.ToInt32(reader["P_SubCategoryID"]),
                        P_SPrice1          = Convert.ToDouble(reader["P_SPrice1"].ToString()),
                        P_SPrice2          = Convert.ToDouble(reader["P_SPrice2"].ToString()),
                        P_SPrice3          = Convert.ToDouble(reader["P_SPrice3"].ToString()),
                        P_SPrice4          = Convert.ToDouble(reader["P_SPrice4"].ToString()),
                        P_SPrice5          = Convert.ToDouble(reader["P_SPrice5"].ToString()),
                        P_SPrice6          = Convert.ToDouble(reader["P_SPrice6"].ToString()),
                        P_SPrice7          = Convert.ToDouble(reader["P_SPrice7"].ToString()),
                        P_SPrice8          = Convert.ToDouble(reader["P_SPrice8"].ToString()),
                        P_SPrice9          = Convert.ToDouble(reader["P_SPrice9"].ToString()),
                        P_SPrice10         = Convert.ToDouble(reader["P_SPrice10"].ToString()),
                        P_SPrice11         = Convert.ToDouble(reader["P_SPrice11"].ToString()),
                        P_SPrice12         = Convert.ToDouble(reader["P_SPrice12"].ToString()),
                        P_SPrice13         = Convert.ToDouble(reader["P_SPrice13"].ToString()),
                        P_SPrice14         = Convert.ToDouble(reader["P_SPrice14"].ToString()),
                        P_SPrice15         = Convert.ToDouble(reader["P_SPrice15"].ToString()),
                        P_ModifyDT         = Convert.ToDateTime(reader["P_ModifyDT"].ToString()),
                        P_OrderStatus      = Convert.ToInt32(reader["P_OrderStatus"].ToString()),
                        P_DisplayShelfLife = Convert.ToInt32(reader["P_DisplayShelfLife"].ToString())
                    };

                    items.Add(item);
                }
            }

            try
            {
                var clearItems =
                    from i in _itemRepository.Table
                    where string.IsNullOrEmpty(i.P_StockCode) && string.IsNullOrEmpty(i.P_Desc)
                    select i;
                if (clearItems.Any())
                {
                    var deletedItems = clearItems.Count();

                    await _itemRepository.DeleteAsync(clearItems);

                    await _userActivityService.InsertActivityAsync("ClearItem", $"Deleted old master data from [Item] (Total deleted items = {deletedItems})", new Item());
                }

                await _itemRepository.InsertAsync(items);

                await _userActivityService.InsertActivityAsync("DownloadItem", $"Downloaded master data to [Item] (Total added items = {items.Count})", new Item());
            }
            catch (Exception exception)
            {
                _logger.Error("An error occurred while downloading data to table [Item]", exception);
            }

            #endregion
        }
Example #13
0
 /// <summary>
 /// Deletes an attributes
 /// </summary>
 /// <param name="attributes">Attributes</param>
 public void DeleteAttributes(IList <GenericAttribute> attributes)
 {
     _genericAttributeService.DeleteAttributes(attributes);
 }