/// <summary>
        /// Delete guest customer records
        /// </summary>
        /// <param name="registrationFrom">Customer registration from; null to load all customers</param>
        /// <param name="registrationTo">Customer registration to; null to load all customers</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?registrationFrom, DateTime?registrationTo, bool onlyWithoutShoppingCart)
        {
            var guestRole = GetCustomerRoleBySystemName(SystemCustomerRoleNames.Guests);

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

            var query = _customerRepository.Table;

            if (registrationFrom.HasValue)
            {
                query = query.Where(c => registrationFrom.Value <= c.CreatedOnUtc);
            }
            if (registrationTo.HasValue)
            {
                query = query.Where(c => registrationTo.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 = query.Where(c => !c.Orders.Any());
            //no customer content
            query = query.Where(c => !c.CustomerContent.Any());
            //ensure that customers doesn't have forum posts or topics
            query = query.Where(c => !c.ForumTopics.Any());
            query = query.Where(c => !c.ForumPosts.Any());
            //don't delete system accounts
            query = query.Where(c => !c.IsSystemAccount);
            var customers = query.ToList();

            int numberOfDeletedCustomers = 0;

            foreach (var c in customers)
            {
                try
                {
                    //delete from database
                    _customerRepository.Delete(c);
                    numberOfDeletedCustomers++;

                    //delete attributes
                    var attributes = _genericAttributeService.GetAttributesForEntity(c.Id, "Customer");
                    foreach (var attribute in attributes)
                    {
                        _genericAttributeService.DeleteAttribute(attribute);
                    }
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc);
                }
            }

            return(numberOfDeletedCustomers);
        }
Exemple #2
0
        private void OnShipmentChange(Shipment args)
        {
            if (string.IsNullOrWhiteSpace(args.TrackingNumber))
            {
                return;
            }

            var genericAttrs = _genericAttributeService.GetAttributesForEntity(args.Id, "Shipment");

            // Events for tracking is not yet registered. We register and save this entry in the generic attributes
            if (genericAttrs.Any(g => g.Value.Equals(args.TrackingNumber)))
            {
                return;
            }

            //remove the old tracker
            var oldTrackAttr = genericAttrs.FirstOrDefault(g => g.Key.Equals(Constants.SHIPMENT_TRACK_NUMBER_ATTRIBUTE_NAME));

            if (oldTrackAttr != null && !oldTrackAttr.Value.Equals(args.TrackingNumber))
            {
                if (RemoveTracking(oldTrackAttr.Value))
                {
                    foreach (var genericAttribute in genericAttrs)
                    {
                        _genericAttributeService.DeleteAttribute(genericAttribute);
                    }
                }
            }

            //create the new tracking in Aftarship
            CreateTracking(args);
        }
        public void ShouldSetCreatedOrUpdatedDateUtcInInsertAttribute()
        {
            var attribute = new Core.Domain.Common.GenericAttribute
            {
                Key = "test", KeyGroup = "test", Value = "test", CreatedOrUpdatedDateUTC = null
            };

            _genericAttributeService.InsertAttribute(attribute);

            var createdOrUpdatedDate = attribute.CreatedOrUpdatedDateUTC;

            _genericAttributeService.DeleteAttribute(attribute);

            Assert.That(createdOrUpdatedDate,
                        Is.EqualTo(DateTime.UtcNow).Within(1).Minutes);
        }
        public IActionResult DeleteProduct(int id)
        {
            if (id <= 0)
            {
                return(Error(HttpStatusCode.BadRequest, "id", "invalid id"));
            }

            var product = _productApiService.GetProductById(id);

            if (product == null)
            {
                return(Error(HttpStatusCode.NotFound, "product", "not found"));
            }

            var genericAttribute = _genericAttributeService.GetAttributesForEntity(product.Id, "Product").FirstOrDefault();

            if (genericAttribute != null)
            {
                _genericAttributeService.DeleteAttribute(genericAttribute);
            }

            _productService.DeleteProduct(product);

            //activity log
            CustomerActivityService.InsertActivity("DeleteProduct",
                                                   string.Format(LocalizationService.GetResource("ActivityLog.DeleteProduct"), product.Name), product);

            return(new RawJsonActionResult("{}"));
        }
        public ActionResult SMSDelete(ListSMSModel model)
        {
            if (!ModelState.IsValid)
            {
                return(Json(new DataSourceResult {
                    Errors = ModelState.SerializeErrors()
                }));
            }

            var storeId            = GetActiveStoreScopeConfiguration(_storeService, _workContext);
            var sendInBlueSettings = _settingService.LoadSetting <SendInBlueSettings>(storeId);

            //delete generic attributes
            var message = _messageTemplateService.GetMessageTemplateById(model.MessageId);

            if (message != null)
            {
                var attributes   = _genericAttributeService.GetAttributesForEntity(message.Id, "MessageTemplate");
                var smsAttribute = attributes.FirstOrDefault(x => x.Key == "UseSMS");
                if (smsAttribute != null)
                {
                    _genericAttributeService.DeleteAttribute(smsAttribute);
                }
                smsAttribute = attributes.FirstOrDefault(x => x.Key == "SMSText");
                if (smsAttribute != null)
                {
                    _genericAttributeService.DeleteAttribute(smsAttribute);
                }
                smsAttribute = attributes.FirstOrDefault(x => x.Key == "PhoneTypeId");
                if (smsAttribute != null)
                {
                    _genericAttributeService.DeleteAttribute(smsAttribute);
                }
            }

            //update list of the message templates which are sending in SMS
            if (sendInBlueSettings.SMSMessageTemplatesIds.Contains(model.MessageId))
            {
                sendInBlueSettings.SMSMessageTemplatesIds.Remove(model.MessageId);
                _settingService.SaveSetting(sendInBlueSettings, x => x.SMSMessageTemplatesIds, storeId, false);
                _settingService.ClearCache();
            }

            return(new NullJsonResult());
        }
        public ActionResult GenericAttributeDelete(int id, GridCommand command)
        {
            var attr = _genericAttributeService.GetAttributeById(id);

            if (_services.Permissions.Authorize(StandardPermissionProvider.AccessAdminPanel))
            {
                _genericAttributeService.DeleteAttribute(attr);
            }

            return(GenericAttributesSelect(attr.KeyGroup, attr.EntityId, command));
        }
        public ActionResult GenericAttributeDelete(int id, string entityName, GridCommand command)
        {
            var infos = GetGenericAttributesInfos(entityName);
            var attr  = _genericAttributeService.GetAttributeById(id);

            if (infos.UpdatePermission.HasValue() && !Services.Permissions.Authorize(infos.UpdatePermission))
            {
                NotifyError(Services.Permissions.GetUnauthorizedMessage(infos.UpdatePermission));
            }
            else
            {
                _genericAttributeService.DeleteAttribute(attr);
            }

            return(GenericAttributesSelect(attr.KeyGroup, attr.EntityId, command));
        }
        public ActionResult GenericAttributeDelete(int id, GridCommand command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.AccessAdminPanel))
            {
                return(AccessDeniedView());
            }

            var attr = _genericAttributeService.GetAttributeById(id);

            if (attr == null)
            {
                throw new System.Web.HttpException(404, "No resource found with the specified id");
            }

            _genericAttributeService.DeleteAttribute(attr);

            return(GenericAttributesSelect(attr.KeyGroup, attr.EntityId, command));
        }
Exemple #9
0
        public void RemoveKeys(int customerId)
        {
            if (customerId != 0)
            {
                var data = (
                    from a in _genericAttributes.Table
                    where a.EntityId == customerId && a.KeyGroup == "Customer" && a.Key == WebApiCachingUserData.Key
                    select a).ToList();

                if (data.Count > 0)
                {
                    foreach (var itm in data)
                    {
                        _genericAttributeService.DeleteAttribute(itm);
                    }

                    WebApiCachingUserData.Remove();
                }
            }
        }
        /// <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");
                        foreach (var attribute in attributes)
                        {
                            _genericAttributeService.DeleteAttribute(attribute);
                        }


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

                #endregion
            }
        }
Exemple #11
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>
        /// <param name="maxNumberOfRecordsToDelete">Maximum number of customer records to delete</param>
        /// <returns>Number of deleted customers</returns>
        public virtual int DeleteGuestCustomers(DateTime?createdFromUtc,
                                                DateTime?createdToUtc, bool onlyWithoutShoppingCart, int maxNumberOfRecordsToDelete)
        {
            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 = new PagedList <Customer>(query, 0, maxNumberOfRecordsToDelete);


            int numberOfDeletedCustomers = 0;

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


                    //delete from database
                    _customerRepository.Delete(c);
                    numberOfDeletedCustomers++;
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc);
                }
            }
            return(numberOfDeletedCustomers);
        }
Exemple #12
0
        public virtual void AnonymizeCustomer(Customer customer, bool pseudomyzeContent)
        {
            Guard.NotNull(customer, nameof(customer));

            var language     = customer.GetLanguage();
            var customerName = customer.GetFullName() ?? customer.Username ?? customer.FindEmail();

            using (var scope = new DbContextScope(_services.DbContext, autoCommit: false))
            {
                // Set to deleted
                customer.Deleted = true;

                // Unassign roles
                customer.CustomerRoles.Clear();
                customer.CustomerRoles.Add(_services.Resolve <ICustomerService>().GetCustomerRoleBySystemName(SystemCustomerRoleNames.Guests));

                // Delete shopping cart & wishlist (TBD: (mc) Really?!?)
                _shoppingCartService.DeleteExpiredShoppingCartItems(DateTime.UtcNow, customer.Id);

                // Delete forum subscriptions
                var forumSubscriptions = _forumService.GetAllSubscriptions(customer.Id, 0, 0, 0, int.MaxValue);
                foreach (var forumSub in forumSubscriptions)
                {
                    _forumService.DeleteSubscription(forumSub);
                }

                // Delete BackInStock subscriptions
                var backInStockSubscriptions = _backInStockSubscriptionService.GetAllSubscriptionsByCustomerId(customer.Id, 0, 0, int.MaxValue);
                foreach (var stockSub in backInStockSubscriptions)
                {
                    _backInStockSubscriptionService.DeleteSubscription(stockSub);
                }

                // Generic attributes
                var attributes = _genericAttributeService.GetAttributesForEntity(customer.Id, "Customer");
                foreach (var attr in attributes)
                {
                    // we don't need to mask generic attrs, we just delete them.
                    _genericAttributeService.DeleteAttribute(attr);
                }

                // Customer Data
                AnonymizeData(customer, x => x.Username, IdentifierDataType.UserName, language);
                AnonymizeData(customer, x => x.Email, IdentifierDataType.EmailAddress, language);
                AnonymizeData(customer, x => x.LastIpAddress, IdentifierDataType.IpAddress, language);
                if (pseudomyzeContent)
                {
                    AnonymizeData(customer, x => x.AdminComment, IdentifierDataType.LongText, language);
                    AnonymizeData(customer, x => x.LastLoginDateUtc, IdentifierDataType.DateTime, language);
                    AnonymizeData(customer, x => x.LastActivityDateUtc, IdentifierDataType.DateTime, language);
                }

                // Addresses
                foreach (var address in customer.Addresses)
                {
                    AnonymizeAddress(address, language);
                }

                // Private messages
                if (pseudomyzeContent)
                {
                    var privateMessages = _forumService.GetAllPrivateMessages(0, customer.Id, 0, null, null, null, null, 0, int.MaxValue);
                    foreach (var msg in privateMessages)
                    {
                        AnonymizeData(msg, x => x.Subject, IdentifierDataType.Text, language);
                        AnonymizeData(msg, x => x.Text, IdentifierDataType.LongText, language);
                    }
                }

                // Forum topics
                if (pseudomyzeContent)
                {
                    foreach (var topic in customer.ForumTopics)
                    {
                        AnonymizeData(topic, x => x.Subject, IdentifierDataType.Text, language);
                    }
                }

                // Forum posts
                foreach (var post in customer.ForumPosts)
                {
                    AnonymizeData(post, x => x.IPAddress, IdentifierDataType.IpAddress, language);
                    if (pseudomyzeContent)
                    {
                        AnonymizeData(post, x => x.Text, IdentifierDataType.LongText, language);
                    }
                }

                // Customer Content
                foreach (var item in customer.CustomerContent)
                {
                    AnonymizeData(item, x => x.IpAddress, IdentifierDataType.IpAddress, language);

                    if (pseudomyzeContent)
                    {
                        switch (item)
                        {
                        case ProductReview c:
                            AnonymizeData(c, x => x.ReviewText, IdentifierDataType.LongText, language);
                            AnonymizeData(c, x => x.Title, IdentifierDataType.Text, language);
                            break;

                        case NewsComment c:
                            AnonymizeData(c, x => x.CommentText, IdentifierDataType.LongText, language);
                            AnonymizeData(c, x => x.CommentTitle, IdentifierDataType.Text, language);
                            break;

                        case BlogComment c:
                            AnonymizeData(c, x => x.CommentText, IdentifierDataType.LongText, language);
                            break;
                        }
                    }
                }

                //// Anonymize Order IPs
                //// TBD: Don't! Doesn't feel right because of fraud detection etc.
                //foreach (var order in customer.Orders)
                //{
                //	AnonymizeData(order, x => x.CustomerIp, IdentifierDataType.IpAddress, language);
                //}

                // SAVE!!!
                //_services.DbContext.DetachAll(); // TEST
                scope.Commit();

                // Log
                Logger.Info(T("Gdpr.Anonymize.Success", language.Id, customerName));
            }
        }
        /// <summary>
        /// Delete guest customer records
        /// </summary>
        /// <param name="registrationFrom">Customer registration from; null to load all customers</param>
        /// <param name="registrationTo">Customer registration to; null to load all customers</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?registrationFrom,
                                                DateTime?registrationTo, bool onlyWithoutShoppingCart)
        {
            var guestRole = GetCustomerRoleBySystemName(SystemCustomerRoleNames.Guests);

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

            var query = _customerRepository.Table;

            if (registrationFrom.HasValue)
            {
                query = query.Where(c => registrationFrom.Value <= c.CreatedOnUtc);
            }
            if (registrationTo.HasValue)
            {
                query = query.Where(c => registrationTo.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 (inner join)
            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 customer content
            query = query.Where(c => !c.CustomerContent.Any());
            //ensure that customers doesn't have forum posts or topics (inner join)
            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;

            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 numberOfDeletedCustomers = 0;

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


                    //delete from database
                    _customerRepository.Delete(c);
                    numberOfDeletedCustomers++;
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc);
                }
            }
            return(numberOfDeletedCustomers);
        }
Exemple #14
0
 /// <summary>
 /// Deletes an attribute
 /// </summary>
 /// <param name="attribute">Attribute</param>
 public void DeleteAttribute(GenericAttribute attribute)
 {
     _genericAttributeService.DeleteAttribute(attribute);
 }