public virtual void UpdateAttribute(GenericAttribute attribute)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException("attribute");
            }

            _genericAttributeRepository.Update(attribute);

            if (attribute.KeyGroup.IsCaseInsensitiveEqual("Order") && attribute.EntityId != 0)
            {
                var order = _orderRepository.GetById(attribute.EntityId);
                _eventPublisher.PublishOrderUpdated(order);
            }
        }
Beispiel #2
0
        public void InsertAttribute(GenericAttribute attribute)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException("attribute");
            }
            _repository.Insert(attribute);
            string key = string.Format(GENERICATTRIBUTE_KEY, attribute.EntityId, attribute.KeyGroup);

            //cache
            //_cacheManager.RemoveByPattern(GENERICATTRIBUTE_PATTERN_KEY);nop的做法 感觉没有必要 都删
            _cacheManager.Remove(key);
            //event notification
            _eventPublisher.EntityInserted(attribute);
        }
Beispiel #3
0
        /// <summary>
        ///     Inserts an attribute
        /// </summary>
        /// <param name="attribute">attribute</param>
        public virtual void InsertAttribute(GenericAttribute attribute)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException(nameof(attribute));
            }

            //_genericAttributeRepository.Insert(attribute);

            //cache
            //_cacheManager.RemoveByPattern(GENERICATTRIBUTE_PATTERN_KEY);

            //event notification
            _eventPublisher.EntityCreated(attribute);
        }
        /// <summary>
        /// Inserts an attribute
        /// </summary>
        /// <param name="attribute">attribute</param>
        public virtual void InsertAttribute(GenericAttribute attribute)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException(nameof(attribute));
            }

            _genericAttributeRepository.Insert(attribute);

            //cache
            _cacheManager.RemoveByPrefix(NopCommonDefaults.GenericAttributePrefixCacheKey);

            //event notification
            _eventPublisher.EntityInserted(attribute);
        }
        /// <summary>
        /// Updates the attribute
        /// </summary>
        /// <param name="attribute">Attribute</param>
        public virtual void UpdateAttribute(GenericAttribute attribute)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException(nameof(attribute));
            }

            _genericAttributeRepository.Update(attribute);

            //cache
            _cacheManager.RemoveByPrefix(GenericAttributePrefixCacheKey);

            //event notification
            _eventPublisher.EntityUpdated(attribute);
        }
Beispiel #6
0
        /// <summary>
        /// Deletes an attribute
        /// </summary>
        /// <param name="attribute">Attribute</param>
        public virtual void DeleteAttribute(GenericAttribute attribute)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException(nameof(attribute));
            }

            _genericAttributeRepository.Delete(attribute);

            //cache
            _cacheManager.RemoveByPattern(NopCommonDefaults.GenericAttributePatternCacheKey);

            //event notification
            _eventPublisher.EntityDeleted(attribute);
        }
Beispiel #7
0
        /// <summary>
        /// Deletes an attribute
        /// </summary>
        /// <param name="attribute">Attribute</param>
        public virtual void DeleteAttribute(GenericAttribute attribute)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException("attribute");
            }

            _genericAttributeRepository.Delete(attribute);

            //cache
            _cacheManager.RemoveByPattern(GENERICATTRIBUTE_PATTERN_KEY);

            //event notification
            _eventPublisher.EntityDeleted(attribute);
        }
Beispiel #8
0
        /// <summary>
        /// 更新通用属性
        /// </summary>
        /// <param name="attribute">通用属性</param>
        public virtual void UpdateAttribute(GenericAttribute attribute)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException(nameof(attribute));
            }

            _genericAttributeRepository.Update(attribute);

            //缓存
            _cacheManager.RemoveByPattern(GENERICATTRIBUTE_PATTERN_KEY);

            //发布事件
            _eventPublisher.EntityUpdated(attribute);
        }
Beispiel #9
0
        public virtual void DeleteAttribute(GenericAttribute attribute)
        {
            Guard.NotNull(attribute, nameof(attribute));

            int    entityId = attribute.EntityId;
            string keyGroup = attribute.KeyGroup;

            _genericAttributeRepository.Delete(attribute);

            if (keyGroup.IsCaseInsensitiveEqual("Order") && entityId != 0)
            {
                var order = _orderRepository.GetById(entityId);
                _eventPublisher.PublishOrderUpdated(order);
            }
        }
        /// <summary>
        /// Save attribute value
        /// </summary>
        /// <typeparam name="TPropType">Property type</typeparam>
        /// <param name="entity">Entity</param>
        /// <param name="key">Key</param>
        /// <param name="value">Value</param>
        /// <param name="storeId">Store identifier; pass 0 if this attribute will be available for all stores</param>
        public virtual void SaveAttribute <TPropType>(BaseEntity entity, string key, TPropType value, int storeId = 0)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            string keyGroup = entity.GetUnproxiedEntityType().Name;

            var props = GetAttributesForEntity(entity.Id, keyGroup)
                        .Where(x => x.StoreId == storeId)
                        .ToList();
            var prop = props.FirstOrDefault(ga =>
                                            ga.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase)); //should be culture invariant

            string valueStr = value.Convert <string>();

            if (prop != null)
            {
                if (string.IsNullOrWhiteSpace(valueStr))
                {
                    //delete
                    DeleteAttribute(prop);
                }
                else
                {
                    //update
                    prop.Value = valueStr;
                    UpdateAttribute(prop);
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(valueStr))
                {
                    //insert
                    prop = new GenericAttribute()
                    {
                        EntityId = entity.Id,
                        Key      = key,
                        KeyGroup = keyGroup,
                        Value    = valueStr,
                        StoreId  = storeId
                    };
                    InsertAttribute(prop);
                }
            }
        }
Beispiel #11
0
        /// <summary>
        /// 添加通用属性
        /// </summary>
        /// <typeparam name="TPropType">值类型</typeparam>
        /// <param name="entity">实体</param>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public virtual void SaveAttribute <TPropType>(BaseEntity entity, string key, TPropType value)
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }

            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            string keyGroup = entity.GetUnproxiedEntityType().Name;

            var props = GetAttributesForEntity(entity.Id, keyGroup).ToList();

            var prop = props.FirstOrDefault(ga =>
                                            ga.Key.Equals(key, StringComparison.OrdinalIgnoreCase));

            var valueStr = CommonHelper.To <string>(value);

            if (prop != null)
            {
                if (string.IsNullOrWhiteSpace(valueStr))
                {
                    DeleteAttribute(prop);
                }
                else
                {
                    prop.Value = valueStr;
                    UpdateAttribute(prop);
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(valueStr))
                {
                    prop = new GenericAttribute
                    {
                        EntityId = entity.Id,
                        Key      = key,
                        KeyGroup = keyGroup,
                        Value    = valueStr
                    };
                    InsertAttribute(prop);
                }
            }
        }
        private static CustomerDto Merge(IList <CustomerAttributeMappingDto> mappingsForMerge, int defaultLanguageId)
        {
            // We expect the customer to be always set.
            var customerDto = mappingsForMerge.First().Customer.ToDto();

            var attributes = mappingsForMerge.Select(x => x.Attribute).ToList();

            // If there is no Language Id generic attribute create one with the default language id.
            if (!attributes.Any(atr => atr != null && atr.Key.Equals(LanguageId, StringComparison.InvariantCultureIgnoreCase)))
            {
                var languageId = new GenericAttribute
                {
                    Key   = LanguageId,
                    Value = defaultLanguageId.ToString()
                };

                attributes.Add(languageId);
            }

            foreach (var attribute in attributes)
            {
                if (attribute != null)
                {
                    if (attribute.Key.Equals(FirstName, StringComparison.InvariantCultureIgnoreCase))
                    {
                        customerDto.FirstName = attribute.Value;
                    }
                    else if (attribute.Key.Equals(LastName, StringComparison.InvariantCultureIgnoreCase))
                    {
                        customerDto.LastName = attribute.Value;
                    }
                    else if (attribute.Key.Equals(LanguageId, StringComparison.InvariantCultureIgnoreCase))
                    {
                        customerDto.LanguageId = attribute.Value;
                    }
                    else if (attribute.Key.Equals(DateOfBirth, StringComparison.InvariantCultureIgnoreCase))
                    {
                        customerDto.DateOfBirth = string.IsNullOrEmpty(attribute.Value) ? (DateTime?)null : DateTime.Parse(attribute.Value);
                    }
                    else if (attribute.Key.Equals(Gender, StringComparison.InvariantCultureIgnoreCase))
                    {
                        customerDto.Gender = attribute.Value;
                    }
                }
            }

            return(customerDto);
        }
Beispiel #13
0
 private void FilterAttributes(ArrayList attris, string className)
 {
     for (int i = 0; i < attris.Count; i++)
     {
         GenericAttribute attribute = (GenericAttribute)attris[i];
         if ((attribute.Category == "I") || (attribute.Category == "S"))
         {
             DEMetaAttribute attach = attribute.Attach as DEMetaAttribute;
             if (!attach.IsViewable)
             {
                 attris.Remove(attribute);
                 i--;
             }
         }
     }
 }
        /// <summary>
        /// Gets a value indicating whether customer is in a certain customer role
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <param name="customerRoleSystemName">Customer role system name</param>
        /// <param name="onlyActiveCustomerRoles">A value indicating whether we should look only in active customer roles</param>
        /// <returns>Result</returns>
        public static bool IsValidToken(this Customer customer, GenericAttribute token, string compareToken)
        {
            if (customer is null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            if (token is null ||
                string.IsNullOrEmpty(token.Value) ||
                token.CreatedOrUpdatedDateUTC < DateTime.UtcNow.AddMinutes(-2) ||
                !token.Value.Equals(compareToken, StringComparison.InvariantCultureIgnoreCase))
            {
                return(false);
            }
            return(true);
        }
Beispiel #15
0
        public virtual void SaveAttribute <TProp>(int entityId, string key, string entityName, TProp value, int storeId = 0)
        {
            Guard.NotZero(entityId, nameof(entityId));

            var valueStr = value.Convert <string>();
            var props    = GetAttributesForEntity(entityId, entityName);

            // should be culture invariant
            var prop = props.FirstOrDefault(ga => ga.StoreId == storeId && ga.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase));

            if (prop != null)
            {
                if (string.IsNullOrWhiteSpace(valueStr))
                {
                    // delete
                    DeleteAttribute(prop);
                    CacheTryRemove(entityName, entityId, prop);
                }
                else
                {
                    // update
                    prop.Value = valueStr;
                    UpdateAttribute(prop);
                    CacheTryAddOrUpdate(entityName, entityId, prop);
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(valueStr))
                {
                    // insert
                    prop = new GenericAttribute
                    {
                        EntityId = entityId,
                        Key      = key,
                        KeyGroup = entityName,
                        Value    = valueStr,
                        StoreId  = storeId
                    };

                    InsertAttribute(prop);

                    CacheTryAddOrUpdate(entityName, entityId, prop);
                }
            }
        }
        public ActionResult GenericAttribute_Update(GenericAttribute model)
        {
            try
            {
                var genericAttribute = _genericAttributeService.GetAttributeById(model.Id);
                genericAttribute.Id          = model.Id;
                genericAttribute.EntityKey   = model.EntityKey;
                genericAttribute.EntityValue = model.EntityValue;

                _genericAttributeService.Update(genericAttribute);
                return(new NullJsonResult());
            }
            catch (Exception)
            {
                return(new NullJsonResult());
            }
        }
Beispiel #17
0
        public void SaveAttribute <TPropType>(BaseEntity entity, string key, TPropType value, int storeId = 0)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            string keyGroup = entity.GetUnproxiedEntityType().Name;

            var props = GetAttributesForEntity(entity.Id, keyGroup).Where(m => m.StoreId == storeId).ToList();
            var prop  = props.FirstOrDefault(m => m.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase));

            var valueStr = CommonHelper.To <string>(value);

            if (prop != null)
            {
                if (string.IsNullOrEmpty(valueStr))
                {
                    DeleteAttribute(prop);
                }
                else
                {
                    UpdateAttribute(prop);
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(valueStr))
                {
                    prop = new GenericAttribute()
                    {
                        EntityId = entity.Id,
                        Key      = key,
                        KeyGroup = keyGroup,
                        Value    = valueStr,
                        StoreId  = storeId
                    };
                    InsertAttribute(prop);
                }
            }
        }
        public void Can_save_and_load_genericAttribute()
        {
            var genericAttribute = new GenericAttribute
            {
                EntityId = 1,
                KeyGroup = "KeyGroup 1",
                Key      = "Key 1",
                Value    = "Value 1",
            };

            var fromDb = SaveAndLoadEntity(genericAttribute);

            fromDb.ShouldNotBeNull();
            fromDb.EntityId.ShouldEqual(1);
            fromDb.KeyGroup.ShouldEqual("KeyGroup 1");
            fromDb.Key.ShouldEqual("Key 1");
            fromDb.Value.ShouldEqual("Value 1");
        }
        private CustomerDto Merge(IList <CustomerAttributeMappingDto> mappingsForMerge, int defaultLanguageId)
        {
            var customerDto = new CustomerDto();

            // We expect the customer to be always set.
            customerDto = mappingsForMerge.First().Customer.ToDto();

            List <GenericAttribute> attributes = mappingsForMerge.Select(x => x.Attribute).ToList();

            // If there is no Language Id generic attribute create one with the default language id.
            if (!attributes.Any(atr => atr != null && atr.Key.Equals(LanguageId, StringComparison.InvariantCultureIgnoreCase)))
            {
                GenericAttribute languageId = new GenericAttribute
                {
                    Key   = LanguageId,
                    Value = defaultLanguageId.ToString()
                };

                attributes.Add(languageId);
            }

            foreach (var attribute in attributes)
            {
                if (attribute != null)
                {
                    if (attribute.Key.Equals(FirstName, StringComparison.InvariantCultureIgnoreCase))
                    {
                        customerDto.FirstName = attribute.Value;
                    }
                    else if (attribute.Key.Equals(LastName, StringComparison.InvariantCultureIgnoreCase))
                    {
                        customerDto.LastName = attribute.Value;
                    }
                    else if (attribute.Key.Equals(LanguageId, StringComparison.InvariantCultureIgnoreCase))
                    {
                        customerDto.LanguageId = attribute.Value;
                    }
                }
            }

            return(customerDto);
        }
Beispiel #20
0
        private GenericAttribute[] FilterAttrs(GenericAttribute[] elements)
        {
            if (elements == null)
            {
                return(null);
            }
            ArrayList list = new ArrayList();

            GenericAttribute[] attributeArray = elements;
            for (int i = 0; i < attributeArray.Length; i++)
            {
                object           obj2      = attributeArray[i];
                GenericAttribute attribute = obj2 as GenericAttribute;
                if ((attribute != null) && (!(attribute.Attach is DEMetaAttribute) || (attribute.Attach as DEMetaAttribute).IsViewable))
                {
                    list.Add(attribute);
                }
            }
            return((GenericAttribute[])list.ToArray(typeof(GenericAttribute)));
        }
Beispiel #21
0
        /// <summary>
        /// Updates the attribute
        /// </summary>
        /// <param name="attribute">Attribute</param>
        public virtual void UpdateAttribute(GenericAttribute attribute)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException("attribute");
            }

            _genericAttributeRepository.Update(attribute);

            //cache
            _cacheManager.RemoveByPattern(GENERICATTRIBUTE_PATTERN_KEY);

            //event notifications
            _eventPublisher.EntityUpdated(attribute);

            if (attribute.KeyGroup.IsCaseInsensitiveEqual("Order") && attribute.EntityId != 0)
            {
                var order = _orderRepository.GetById(attribute.EntityId);
                _eventPublisher.PublishOrderUpdated(order);
            }
        }
        public virtual void DeleteAttribute(GenericAttribute attribute)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException("attribute");
            }

            int    entityId = attribute.EntityId;
            string keyGroup = attribute.KeyGroup;

            _genericAttributeRepository.Delete(attribute);

            //event notifications
            _eventPublisher.EntityDeleted(attribute);

            if (keyGroup.IsCaseInsensitiveEqual("Order") && entityId != 0)
            {
                var order = _orderRepository.GetById(entityId);
                _eventPublisher.PublishOrderUpdated(order);
            }
        }
Beispiel #23
0
        /// <summary>
        /// 根据属性获取对象
        /// </summary>
        /// <param name="currentAttr">当前属性</param>
        /// <param name="matchAttr">匹配的属性</param>
        private DEBusinessItem[] GetMatchItems(GenericAttribute currentAttr, GenericAttribute matchAttr)
        {
            if (currentAttr == null || matchAttr == null)
            {
                return(null);
            }
            var currentValue = _currentItem.GetAttrValue(_currentItem.ClassName, currentAttr.Name);

            if (currentValue == null)
            {
                return(null);
            }
            var       attrName = string.Format("{0}.{1}", matchAttr.Category, matchAttr.Name);
            Hashtable hashTb   = new Hashtable()
            {
                { attrName, currentValue }
            };
            var items = PLItem.Agent.GetBizItemsByAttr(matchAttr.ClassName, hashTb, ClientData.LogonUser.Oid);

            return(items);
        }
        public ActionResult GenericAttributeAdd(GenericAttributeModel model, GridCommand command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.AccessAdminPanel))
            {
                return(AccessDeniedView());
            }

            model.Key   = model.Key.TrimSafe();
            model.Value = model.Value.TrimSafe();

            if (!ModelState.IsValid)
            {
                // display the first model error
                var modelStateErrorMessages = this.ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage);
                return(Content(modelStateErrorMessages.FirstOrDefault()));
            }

            var storeId = _storeContext.CurrentStore.Id;

            var attr = _genericAttributeService.GetAttribute <string>(model.EntityName, model.EntityId, model.Key, storeId);

            if (attr == null)
            {
                var ga = new GenericAttribute
                {
                    StoreId  = storeId,
                    KeyGroup = model.EntityName,
                    EntityId = model.EntityId,
                    Key      = model.Key,
                    Value    = model.Value
                };
                _genericAttributeService.InsertAttribute(ga);
            }
            else
            {
                return(Content(string.Format(_localizationService.GetResource("Admin.Common.GenericAttributes.NameAlreadyExists"), model.Key)));
            }

            return(GenericAttributesSelect(model.EntityName, model.EntityId, command));
        }
Beispiel #25
0
        public bool CreateKeys(int customerId)
        {
            if (customerId != 0)
            {
                var    hmac = new HmacAuthentication();
                var    userData = WebApiCachingUserData.Data();
                string key1, key2;

                for (int i = 0; i < 9999; ++i)
                {
                    if (hmac.CreateKeys(out key1, out key2) && !userData.Exists(x => x.PublicKey.IsCaseInsensitiveEqual(key1)))
                    {
                        var apiUser = new WebApiUserCacheData
                        {
                            CustomerId = customerId,
                            PublicKey  = key1,
                            SecretKey  = key2,
                            Enabled    = true
                        };

                        RemoveKeys(customerId);

                        var attribute = new GenericAttribute
                        {
                            EntityId = customerId,
                            KeyGroup = "Customer",
                            Key      = WebApiCachingUserData.Key,
                            Value    = apiUser.ToString()
                        };

                        _genericAttributeService.InsertAttribute(attribute);

                        WebApiCachingUserData.Remove();
                        return(true);
                    }
                }
            }
            return(false);
        }
Beispiel #26
0
        public void WriteGenericAttributes(dynamic parentNode)
        {
            if (parentNode == null || parentNode._GenericAttributes == null)
            {
                return;
            }

            _writer.WriteStartElement("GenericAttributes");
            foreach (dynamic genericAttribute in parentNode._GenericAttributes)
            {
                GenericAttribute entity = genericAttribute.Entity;

                _writer.WriteStartElement("GenericAttribute");
                _writer.Write("Id", entity.Id.ToString());
                _writer.Write("EntityId", entity.EntityId.ToString());
                _writer.Write("KeyGroup", entity.KeyGroup);
                _writer.Write("Key", entity.Key);
                _writer.Write("Value", (string)genericAttribute.Value);
                _writer.Write("StoreId", entity.StoreId.ToString());
                _writer.WriteEndElement();              // GenericAttribute
            }
            _writer.WriteEndElement();                  // GenericAttributes
        }
        private void PrepareAvailableLanguageModel(
            AvailableLanguageModel model,
            AvailableResourcesModel resources,
            Dictionary <int, GenericAttribute> translatedPercentageAtLastImport,
            Language language           = null,
            LanguageDownloadState state = null)
        {
            GenericAttribute attribute = null;

            model.Id                   = resources.Id;
            model.PreviousSetId        = resources.PreviousSetId;
            model.IsInstalled          = language != null;
            model.Name                 = GetCultureDisplayName(resources.Language.Culture) ?? resources.Language.Name;
            model.LanguageCulture      = resources.Language.Culture;
            model.UniqueSeoCode        = resources.Language.TwoLetterIsoCode;
            model.Rtl                  = resources.Language.Rtl;
            model.Version              = resources.Version;
            model.Type                 = resources.Type;
            model.Published            = resources.Published;
            model.DisplayOrder         = resources.DisplayOrder;
            model.TranslatedCount      = resources.TranslatedCount;
            model.TranslatedPercentage = resources.TranslatedPercentage;
            model.IsDownloadRunning    = state != null && state.Id == resources.Id;
            model.UpdatedOn            = _dateTimeHelper.ConvertToUserTime(resources.UpdatedOn, DateTimeKind.Utc);
            model.UpdatedOnString      = model.UpdatedOn.RelativeFormat(false, "f");
            model.FlagImageFileName    = GetFlagFileName(resources.Language.Culture);

            if (language != null && translatedPercentageAtLastImport.TryGetValue(language.Id, out attribute))
            {
                // Only show percent at last import if it's less than the current percentage.
                var percentAtLastImport = Math.Round(attribute.Value.Convert <decimal>(), 2);
                if (percentAtLastImport < model.TranslatedPercentage)
                {
                    model.TranslatedPercentageAtLastImport = percentAtLastImport;
                }
            }
        }
        public CustomerDto GetCustomerById(int id, bool showDeleted = false)
        {
            if (id == 0)
            {
                return(null);
            }

            // Here we expect to get two records, one for the first name and one for the last name.
            List <CustomerAttributeMappingDto> customerAttributeMappings = (from customer in _customerRepository.TableNoTracking
                                                                            join attribute in _genericAttributeRepository.TableNoTracking on customer.Id equals attribute.EntityId
                                                                            where customer.Id == id &&
                                                                            attribute.KeyGroup.Equals(KeyGroup, StringComparison.InvariantCultureIgnoreCase) &&
                                                                            (attribute.Key.Equals(FirstName, StringComparison.InvariantCultureIgnoreCase) ||
                                                                             attribute.Key.Equals(LastName, StringComparison.InvariantCultureIgnoreCase) ||
                                                                             attribute.Key.Equals(LanguageId, StringComparison.InvariantCultureIgnoreCase))
                                                                            select new CustomerAttributeMappingDto()
            {
                Attribute = attribute,
                Customer = customer
            }).ToList();

            CustomerDto customerDto = null;

            // This is in case we have first and last names set for the customer.
            if (customerAttributeMappings.Count > 0)
            {
                Customer customer = customerAttributeMappings.First().Customer;
                // The customer object is the same in all mappings.
                customerDto = customer.ToDto();

                var defaultStoreLanguageId = GetDefaultStoreLangaugeId();

                // If there is no Language Id generic attribute create one with the default language id.
                if (!customerAttributeMappings.Any(cam => cam != null && cam.Attribute != null && cam.Attribute.Key.Equals(LanguageId, StringComparison.InvariantCultureIgnoreCase)))
                {
                    GenericAttribute languageId = new GenericAttribute
                    {
                        Key   = LanguageId,
                        Value = defaultStoreLanguageId.ToString()
                    };

                    CustomerAttributeMappingDto customerAttributeMappingDto = new CustomerAttributeMappingDto
                    {
                        Customer  = customer,
                        Attribute = languageId
                    };

                    customerAttributeMappings.Add(customerAttributeMappingDto);
                }

                foreach (var mapping in customerAttributeMappings)
                {
                    if (!showDeleted && mapping.Customer.Deleted)
                    {
                        continue;
                    }

                    if (mapping.Attribute != null)
                    {
                        if (mapping.Attribute.Key.Equals(FirstName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            customerDto.FirstName = mapping.Attribute.Value;
                        }
                        else if (mapping.Attribute.Key.Equals(LastName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            customerDto.LastName = mapping.Attribute.Value;
                        }
                        else if (mapping.Attribute.Key.Equals(LanguageId, StringComparison.InvariantCultureIgnoreCase))
                        {
                            customerDto.LanguageId = mapping.Attribute.Value;
                        }
                    }
                }
            }
            else
            {
                // This is when we do not have first and last name set.
                Customer currentCustomer = _customerRepository.TableNoTracking.FirstOrDefault(customer => customer.Id == id);

                if (currentCustomer != null)
                {
                    if (showDeleted || !currentCustomer.Deleted)
                    {
                        customerDto = currentCustomer.ToDto();
                    }
                }
            }

            return(customerDto);
        }
Beispiel #29
0
        /// <summary>
        /// Save attribute value
        /// </summary>
        /// <typeparam name="TPropType">Property type</typeparam>
        /// <param name="entity">Entity</param>
        /// <param name="key">Key</param>
        /// <param name="value">Value</param>
        /// <param name="storeId">Store identifier; pass 0 if this attribute will be available for all stores</param>
        public virtual void SaveAttribute <TPropType>(BaseEntity entity, string key, TPropType value, string storeId = "")
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            string keyGroup = entity.GetType().Name;

            var collection = _baseRepository.Database.GetCollection <GenericAttributeBaseEntity>(keyGroup);
            var query      = _baseRepository.Database.GetCollection <GenericAttributeBaseEntity>(keyGroup).AsQueryable();

            var props = query.Where(x => x.Id == entity.Id).SelectMany(x => x.GenericAttributes).ToList();

            var prop = props.FirstOrDefault(ga =>
                                            ga.Key.Equals(key, StringComparison.OrdinalIgnoreCase)); //should be culture invariant

            var valueStr = CommonHelper.To <string>(value);

            if (prop != null)
            {
                if (string.IsNullOrWhiteSpace(valueStr))
                {
                    //delete
                    var builder      = Builders <GenericAttributeBaseEntity> .Update;
                    var updatefilter = builder.PullFilter(x => x.GenericAttributes, y => y.Key == prop.Key && y.StoreId == storeId);
                    var result       = collection.UpdateManyAsync(new BsonDocument("_id", entity.Id), updatefilter).Result;
                }
                else
                {
                    //update
                    prop.Value = valueStr;
                    var builder = Builders <GenericAttributeBaseEntity> .Filter;
                    var filter  = builder.Eq(x => x.Id, entity.Id);
                    filter = filter & builder.Where(x => x.GenericAttributes.Any(y => y.Key == prop.Key));
                    var update = Builders <GenericAttributeBaseEntity> .Update
                                 .Set(x => x.GenericAttributes.ElementAt(-1).Value, prop.Value);

                    var result = collection.UpdateManyAsync(filter, update).Result;
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(valueStr))
                {
                    prop = new GenericAttribute
                    {
                        Key     = key,
                        Value   = valueStr,
                        StoreId = storeId,
                    };
                    var updatebuilder = Builders <GenericAttributeBaseEntity> .Update;
                    var update        = updatebuilder.AddToSet(p => p.GenericAttributes, prop);
                    var result        = collection.UpdateOneAsync(new BsonDocument("_id", entity.Id), update).Result;
                }
            }
        }
Beispiel #30
0
        public CustomerDto GetCustomerById(int id, bool showDeleted = false)
        {
            if (id == 0)
            {
                return(null);
            }

            // Here we expect to get two records, one for the first name and one for the last name.
            var customerAttributeMappings = (from customer in _customerRepository.Table          //NoTracking
                                             join attribute in _genericAttributeRepository.Table //NoTracking
                                             on customer.Id equals attribute.EntityId
                                             where customer.Id == id &&
                                             attribute.KeyGroup == "Customer"
                                             select new CustomerAttributeMappingDto
            {
                Attribute = attribute,
                Customer = customer
            }).ToList();

            CustomerDto customerDto = null;

            // This is in case we have first and last names set for the customer.
            if (customerAttributeMappings.Count > 0)
            {
                var customer = customerAttributeMappings.First().Customer;
                // The customer object is the same in all mappings.
                customerDto = customer.ToDto();

                var defaultStoreLanguageId = GetDefaultStoreLangaugeId();

                // If there is no Language Id generic attribute create one with the default language id.
                if (!customerAttributeMappings.Any(cam => cam?.Attribute != null &&
                                                   cam.Attribute.Key.Equals(LANGUAGE_ID, StringComparison.InvariantCultureIgnoreCase)))
                {
                    var languageId = new GenericAttribute
                    {
                        Key   = LANGUAGE_ID,
                        Value = defaultStoreLanguageId.ToString()
                    };

                    var customerAttributeMappingDto = new CustomerAttributeMappingDto
                    {
                        Customer  = customer,
                        Attribute = languageId
                    };

                    customerAttributeMappings.Add(customerAttributeMappingDto);
                }

                foreach (var mapping in customerAttributeMappings)
                {
                    if (!showDeleted && mapping.Customer.Deleted)
                    {
                        continue;
                    }

                    if (mapping.Attribute != null)
                    {
                        if (mapping.Attribute.Key.Equals(FIRST_NAME, StringComparison.InvariantCultureIgnoreCase))
                        {
                            customerDto.FirstName = mapping.Attribute.Value;
                        }
                        else if (mapping.Attribute.Key.Equals(LAST_NAME, StringComparison.InvariantCultureIgnoreCase))
                        {
                            customerDto.LastName = mapping.Attribute.Value;
                        }
                        else if (mapping.Attribute.Key.Equals(LANGUAGE_ID, StringComparison.InvariantCultureIgnoreCase))
                        {
                            customerDto.LanguageId = mapping.Attribute.Value;
                        }
                        else if (mapping.Attribute.Key.Equals(DATE_OF_BIRTH, StringComparison.InvariantCultureIgnoreCase))
                        {
                            customerDto.DateOfBirth = string.IsNullOrEmpty(mapping.Attribute.Value)
                                                          ? (DateTime?)null
                                                          : DateTime.Parse(mapping.Attribute.Value);
                        }
                        else if (mapping.Attribute.Key.Equals(GENDER, StringComparison.InvariantCultureIgnoreCase))
                        {
                            customerDto.Gender = mapping.Attribute.Value;
                        }
                    }
                }
            }
            else
            {
                // This is when we do not have first and last name set.
                var currentCustomer = _customerRepository.Table.FirstOrDefault(customer => customer.Id == id);

                if (currentCustomer != null)
                {
                    if (showDeleted || !currentCustomer.Deleted)
                    {
                        customerDto = currentCustomer.ToDto();
                    }
                }
            }

            SetNewsletterSubscribtionStatus(customerDto);

            return(customerDto);
        }