Exemplo n.º 1
0
 public void TestIsCheck()
 {
     _dictionaryModel = new DictionaryModel();
     _testModel       = new TestModel(_dictionaryModel);
     _testModel.IsCheck(ConstantWord.ZERO);
     _testModel.IsCheck(ConstantWord.ONE);
 }
Exemplo n.º 2
0
 private async void ShowDictionaryAsync(DictionaryModel @dictionaryModel)
 {
     if (@dictionaryModel != null)
     {
         await NavigationService.NavigateToAsync <ViewDictionaryViewModel>(@dictionaryModel);
     }
 }
Exemplo n.º 3
0
 public void TestGetIndex()
 {
     _dictionaryModel       = new DictionaryModel();
     _testModel             = new TestModel(_dictionaryModel);
     _testModel.SetGetIndex = ConstantWord.ONE;
     Assert.AreEqual(_testModel.GetIndex(), ConstantWord.ONE);
 }
        internal static bool IsValidForNestedStructure(this DictionaryModel model)
        {
            DictionaryModel parentModel = model.GetParentModel();

            if (parentModel == null)
            {
                return(true);
            }

            string[] itemKeyParts       = model.GetItemKey().Split('.');
            string[] parentItemKeyParts = parentModel.GetItemKey().Split('.') ?? new string[0];

            bool equal = itemKeyParts.Length - parentItemKeyParts.Length == 1 && !string.IsNullOrWhiteSpace(itemKeyParts.Last());

            if (!equal)
            {
                return(false);
            }

            if (!parentModel.IsValidForNestedStructure())
            {
                return(false);
            }

            for (int i = 0; i < parentItemKeyParts.Length; i++)
            {
                equal = parentItemKeyParts[i] == itemKeyParts[i];
                if (!equal)
                {
                    break;
                }
            }

            return(equal);
        }
Exemplo n.º 5
0
 /// <summary>
 /// Редактирование города
 /// </summary>
 /// <param name="model">модель с данными</param>
 /// <returns></returns>
 public BaseResponse CityEdit(DictionaryModel model)
 {
     try
     {
         using (var db = new DataContext())
         {
             if (db.Cities.AsNoTracking().Any(x => x.Name == model.Name && x.Id != model.Id))
             {
                 return(new BaseResponse(EnumResponseStatus.ValidationError, "Город с таким наименованием уже существует"));
             }
             var city = db.Cities.FirstOrDefault(x => x.Id == model.Id);
             if (city == null)
             {
                 return(new BaseResponse(EnumResponseStatus.Error, "Город не найден"));
             }
             city.Name = model.Name;
             db.SaveChanges();
             return(new BaseResponse(EnumResponseStatus.Success, "Город успешно изменен"));
         }
     }
     catch (Exception ex)
     {
         return(new BaseResponse(EnumResponseStatus.Exception, ex.Message));
     }
 }
Exemplo n.º 6
0
        /// <summary>
        /// 更新和新增字典
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public DictionaryModel InsertOrUpdateDictionary(DictionaryModel input)
        {
            if (_DictionaryCase.GetAll().Any(p => p.Id != input.Id && p.Name == input.Name))
            {
                throw new UserFriendlyException("名为【" + input.Name + "】的对象已存在!");
            }
            if (input.Id == input.ParentId)
            {
                throw new UserFriendlyException("名为【" + input.Name + "】的对象已不能做自身的上级!");
            }
            //父级类型要和自身类型一样
            if (input.DictionaryTypeId != null && input.ParentId != null)
            {
                if (_DictionaryCase.Get((long)input.ParentId).DictionaryTypeId != input.DictionaryTypeId)
                {
                    throw new UserFriendlyException("操作失败!名为【" + input.Name + "】的对象类型和父级的类型不相同!");
                }
            }
            //var entObj =input.MapTo<Dictionary>();
            var type = _DictionaryCase.GetAll().FirstOrDefault(a => a.Id == input.Id) ?? new Dictionary();

            type = Fun.ClassToCopy(input, type, (new string[] { "Id" }).ToList());
            var resObj = _DictionaryCase.InsertOrUpdate(type);

            if (resObj == null)
            {
                throw new UserFriendlyException("新增或更新失败!");
            }
            else
            {
                return(resObj.MapTo <DictionaryModel>());
            }
        }
        public static string Format(this DictionaryModel model, CultureInfo culture, int count, params object[] args)
        {
            string dictionaryValue = model.ToString(culture);

            string[] pluralizedValues = dictionaryValue.Split('|').Select(x => x.Trim()).ToArray();
            if (pluralizedValues.Length <= 1)
            {
                return(dictionaryValue);
            }

            IPluralizationRule pluralizationRule =
                Current.Factory.GetAllInstances <IPluralizationRule>().SingleOrDefault(x => x.Cultures.Contains(culture))
                ?? new DefaultPluralizationRule();

            int index = pluralizationRule.GetChoiceIndex(count, pluralizedValues.Length);

            if (index >= pluralizedValues.Length)
            {
                return(dictionaryValue);
            }

            dictionaryValue = pluralizedValues[index]
                              .Replace("{n}", count.ToString())
                              .Replace("{count}", count.ToString());

            return(string.Format(dictionaryValue, args));
        }
Exemplo n.º 8
0
 public void TestSetQuestionNumericUpDown()
 {
     _dictionaryModel = new DictionaryModel();
     _testModel       = new TestModel(_dictionaryModel);
     _testModel.SetQuestionNumericUpDown(ConstantWord.ONE);
     Assert.AreEqual(_testModel.GetChangeQuestionNumber(), ConstantWord.ONE);
 }
Exemplo n.º 9
0
        public ActionResult UploadDirectlyUnsigned(string userId)
        {
            if (userId == null)
            {
                return(NotFound());
            }
            if (!TrueUser(userId))
            {
                return(StatusCode(401));
            }
            var preset = "sample_" + _cloudinary.Api.SignParameters(new SortedDictionary <string, object>()
            {
                { "api_key", _cloudinary.Api.Account.ApiKey }
            })
                         .Substring(0, 10);
            var result = _cloudinary.CreateUploadPreset(new UploadPresetParams()
            {
                Name = preset, Unsigned = true, Folder = "preset_folder"
            }
                                                        );

            var model = new DictionaryModel(_cloudinary, new Dictionary <string, string>()
            {
                { "unsigned", "true" },
                { "preset", preset }
            });

            return(PartialView("UploadDirectly", model));
        }
Exemplo n.º 10
0
        public DictionaryView Render(DictionaryModel source)
        {
            var links = new List <LinkView>
            {
                LinkRenderer.RenderOrReRoute(source.Links, "GetDictionaryById", RelTypes.Self, new { id = source.Id }),
                LinkRenderer.RenderOrReRoute(source.Links, "GetWords", RelTypes.Index, new { id = source.Id }),
                LinkRenderer.RenderOrReRoute(source.Links, "SearchDictionary", RelTypes.Search, new { id = source.Id }),
            };

            if (source.Links != null)
            {
                links.AddRange(source.Links
                               .Where(l => l.Rel == RelTypes.Download)
                               .Select(downloadLink => LinkRenderer.RenderOrReRoute(source.Links, "DownloadDictionary", RelTypes.Download, new { id = source.Id, format = downloadLink.Type })));
            }

            var indexes = new List <LinkView>(_indexes.Select(i => LinkRenderer.RenderOrReRoute(source.Indexes, "GetWordsListStartWith", i,
                                                                                                new { id = source.Id, startingWith = i })));

            var result = source.Map <DictionaryModel, DictionaryView>();

            result.Links   = links;
            result.Indexes = indexes;
            return(result);
        }
Exemplo n.º 11
0
        protected Dictionary DictionaryModelToEntity(DictionaryModel model)
        {
            Dictionary dictionay = new Dictionary();

            if (model.Type != DictionaryType.FirstCommentType)
            {
                dictionay.FirstSystemName = model.Type.GetDescription();
                if (model.Type == DictionaryType.DesignCommentType)
                {
                    dictionay.SecondSystemName = DictionaryService.value;
                    dictionay.ParentId         = model.ParentId;
                }
            }
            else
            {
                if (model.BaseCommentType.Value == BaseCommentType.DesignCommentType)
                {
                    dictionay.FirstSystemName  = DictionaryService.designCommentType;
                    dictionay.SecondSystemName = DictionaryService.category;
                }
                else
                {
                    dictionay.FirstSystemName = DictionaryService.integralityCommentType;
                }
            }

            dictionay.DisplayName = model.DisplayName;
            dictionay.ExtraValue1 = model.ExtraValue1;
            dictionay.ExtraValue2 = model.ExtraValue2;
            dictionay.ExtraValue3 = model.ExtraValue3;
            return(dictionay);
        }
        /// <summary>
        /// Writes a constructor, that calls the base <see cref="DictionaryModel"/>'s constructor with the ItemKey
        /// </summary>
        /// <param name="model"></param>
        private void WriteConstructor(DictionaryModel model)
        {
            string itemKey   = model.GenerateCodeItemKey(_config.UseNestedStructure);
            string className = itemKey.ToCodeString(true).ToPascalCase();

            WriteLine($"public _{className}() : base(\"{model.GetItemKey()}\") {{}}");
        }
        protected DictionaryModel Create(string itemKey, DictionaryModel parent, Func <CultureInfo, string> valueResolver)
        {
            DictionaryModelWrapper parentModel = parent as DictionaryModelWrapper;

            // Get the dictionary item from Umbraco. Otherwise crete a new.
            IDictionaryItem dictionaryItem = _localizationService.GetDictionaryItemByKey(itemKey) ??
                                             _localizationService.CreateDictionaryItemWithIdentity(itemKey,
                                                                                                   parentModel?.Key);

            // Create the model
            DictionaryModelWrapper model = new DictionaryModelWrapper(dictionaryItem, parentModel);

            // If no value resolver are provided, then return the model
            if (valueResolver == null)
            {
                return(model);
            }

            // A save indicator
            bool save = false;

            // Iterate through all languages
            foreach (ILanguage language in Languages)
            {
                IDictionaryTranslation translation =
                    dictionaryItem.Translations.SingleOrDefault(x => x.Language == language);
                // If the dictionary translation already has a value, then don't change it
                if (!string.IsNullOrEmpty(translation?.Value))
                {
                    continue;
                }

                // Get the culture specific default value from the value resolver
                string value = valueResolver(language.CultureInfo);
                // If there is no value, then do nothing
                if (value == null)
                {
                    continue;
                }

                // Add the value to the Umbraco dictionary item
                _localizationService.AddOrUpdateDictionaryValue(dictionaryItem, language, value);
                // Indicate that a value has been added to the dictionary, and ensure save
                save = true;

                // Log the addition
                Log.Information(
                    $"Adding '{language}' value:'{value}' for dictionary item: '{dictionaryItem.ItemKey}'");
            }

            // Save the dictionary item
            if (save)
            {
                _localizationService.Save(dictionaryItem);
            }

            // Return the model
            return(model);
        }
Exemplo n.º 14
0
        public async void GetData()
        {
            RootObject = await _restService.GetData();

            var bidsArr = RootObject.bids;
            var asksArr = RootObject.asks;

            int bidsArrRows = bidsArr.GetUpperBound(0) + 1;
            int asksArrRows = asksArr.GetUpperBound(0) + 1;

            var listBids = new List <DictionaryModel>();
            var listAsks = new List <DictionaryModel>();

            for (int i = 0; i < bidsArrRows; i++)
            {
                for (int j = 0; j < 1; j++)
                {
                    var dictionaryBidsModel = new DictionaryModel();
                    dictionaryBidsModel.DictionaryKey   = Math.Round(Convert.ToDouble(bidsArr[i, 0]), 3);
                    dictionaryBidsModel.DictionaryValue = Convert.ToDouble(bidsArr[i, 1]);
                    dictionaryBidsModel.Total           = dictionaryBidsModel.DictionaryKey * dictionaryBidsModel.DictionaryValue;
                    listBids.Add(dictionaryBidsModel);
                }
            }
            var groupedBidsByPrace = listBids.GroupBy(u => u.DictionaryKey)
                                     .Select(group => new { DictionaryKey = group.Key, list = group.ToList() })
                                     .ToList();

            for (int i = 0; i < asksArrRows; i++)
            {
                for (int j = 0; j < 1; j++)
                {
                    var dictionaryAsksModel = new DictionaryModel();
                    dictionaryAsksModel.DictionaryKey   = Math.Round(Convert.ToDouble(asksArr[i, 0]), 3);
                    dictionaryAsksModel.DictionaryValue = Convert.ToDouble(asksArr[i, 1]);
                    dictionaryAsksModel.Total           = dictionaryAsksModel.DictionaryKey * dictionaryAsksModel.DictionaryValue;
                    listAsks.Add(dictionaryAsksModel);
                }
            }
            var groupedAsksByPrace = listAsks.GroupBy(u => u.DictionaryKey)
                                     .Select(group => new { DictionaryKey = group.Key, list = group.ToList() })
                                     .ToList();

            var resultGrouped = groupedBidsByPrace.Concat(groupedAsksByPrace);

            ResponceList = listBids.Concat(listAsks).ToList();
            var totalList = new List <double>();

            foreach (var item in resultGrouped)
            {
                foreach (var i in item.list)
                {
                    totalList.Add(i.DictionaryKey * i.DictionaryValue);
                    TotalVolume += i.DictionaryValue;
                }
            }

            TotalSum = totalList.ToArray().Sum();
        }
        /// <summary>
        /// Writes a collection of models
        /// </summary>
        /// <param name="models">The models to build</param>
        private void WriteDictionaries(params DictionaryModel[] models)
        {
            if (models == null)
            {
                return;
            }

            // Iterate through all models
            for (int i = 0; i < models.Length; i++)
            {
                DictionaryModel model = models[i];
                // Write a start region directive
                WriteLine($"#region {model.GetItemKey()}");

                // Create a list of action starting the the action to build the model itself
                List <Action <DictionaryModel> > parentModelActions =
                    new List <Action <DictionaryModel> > {
                    m => WriteContentModel(model)
                };

                if (model.RenderParentModel(_config.UseNestedStructure))
                {
                    // Get the parent model
                    DictionaryModel parentModel = model.GetParentModel();
                    // Loop through all parent models
                    while (parentModel != null)
                    {
                        // Prevent access to modified closure, so creating a local variable
                        // https://www.jetbrains.com/help/resharper/2020.1/AccessToModifiedClosure.html
                        DictionaryModel localParentModel = parentModel;

                        // The last added action is the child action to this action
                        Action <DictionaryModel> childAction = parentModelActions.Last();
                        // Generate the class name
                        string itemKey   = localParentModel.GenerateCodeItemKey(_config.UseNestedStructure);
                        string className = itemKey.ToCodeString(true).ToPascalCase();
                        // Add the action to the list
                        parentModelActions.Add(m => WritePartialClass($"_{className}", childAction, localParentModel));

                        // Get the next parent model
                        parentModel = parentModel.GetParentModel();
                    }
                }

                // Get the root action.
                Action <DictionaryModel> rootAction = parentModelActions.Last();
                // Execute the root action, to start building the nested class structure
                rootAction(model);

                // Write a end region directive
                WriteLine("#endregion");

                // If not the last model, add an empty line
                if (i < models.Length - 1)
                {
                    _builder.AppendLine();
                }
            }
        }
Exemplo n.º 16
0
        public ActionResult ProductTagUpdate(DictionaryModel model)
        {
            var response = model.Id == 0
                ? _productService.ProductTagAdd(model)
                : _productService.ProductTagEdit(model);

            return(Json(response));
        }
        public DictionaryModel GetDictionaryData(string userId, string dictionaryName)
        {
            var filter = Builders <DictionaryModel> .Filter.Eq("_id", userId + dictionaryName);

            DictionaryModel dictionary = collection.Find(filter).FirstOrDefault();

            return(dictionary);
        }
Exemplo n.º 18
0
 public void Initialize()
 {
     _dictionaryModel   = new DictionaryModel();
     _testModel         = new TestModel(_dictionaryModel);
     _presentationModel = new PresentationModel(_testModel);
     _target1           = new PrivateObject(_testModel);
     _target2           = new PrivateObject(_presentationModel);
 }
Exemplo n.º 19
0
 public void TestReadTextTopic()
 {
     _dictionaryModel = new DictionaryModel();
     _testModel       = new TestModel(_dictionaryModel);
     _targetOne       = new PrivateObject(_testModel);
     _targetOne.SetFieldOrProperty(ConstantWord.BE_QUESTION_NUMBER, ConstantWord.TWO);
     _testModel.ReadTextTopic(ConstantWord.ZERO);
 }
Exemplo n.º 20
0
        public ActionResult CityUpdate(DictionaryModel model)
        {
            var response = model.Id == 0
                ? _sitePageSevice.CityAdd(model)
                : _sitePageSevice.CityEdit(model);

            return(Json(response));
        }
Exemplo n.º 21
0
        public void TestGetWordListLength()
        {
            DictionaryModel file = new DictionaryModel();
            List <Word>     data = new List <Word>();

            data = file.ReadFile(ConstantWord.TEST_ONE);
            Assert.AreEqual(data.Count, ConstantWord.EIGHT);
        }
Exemplo n.º 22
0
        /// <summary> 幫忙初始化 </summary>
        private void InitializeFunction()
        {
            DictionaryModel dictionaryModel = new DictionaryModel();

            _testModel = new TestModel(dictionaryModel);
            _targetOne = new PrivateObject(dictionaryModel);
            _targetTwo = new PrivateObject(_testModel);
        }
Exemplo n.º 23
0
        public void when_loading_xaml_then_sets_bound_data_to_complex_model()
        {
            // Get Xaml from somewhere (i.e. VS)
            var xaml = @"<ContentPage xmlns='http://xamarin.com/schemas/2014/forms'
			 xmlns:x='http://schemas.microsoft.com/winfx/2009/xaml'>
	<Label Text='{Binding Address.Phone.Prefix, Mode=TwoWay}' VerticalOptions='Center' HorizontalOptions='Center' />
</ContentPage> ";

            // Get dummy data from somewhere (i.e. VS)
            var model = new DictionaryModel(new Dictionary <string, object>
            {
                { "Name", "Xamarin" },
                { "Address", new Dictionary <string, object>
                  {
                      { "Street", "Camila" },
                      { "Phone", new Dictionary <string, object>
                                        {
                                            { "Prefix", "+54" },
                                            { "Area", "11" },
                                        } },
                  } }
            });

            // Create empty container page for the XAML
            //		TODO: ensure the root element in the Xaml is actually a ContentPage?
            var view = new ContentPage();

            // Set binding context to dummy data
            view.BindingContext = model;

            // Load the Xaml into the View
            //		TODO: this method is internal in XF.Xaml
            view.LoadFromXaml(xaml);

            // Grab the new label control added to the view via Xaml
            var label = view.Content as Label;

            Assert.NotNull(label);

            // UI properly bound to underlying model!
            Assert.Equal("+54", label.Text);

            // Change the label text via the control
            label.Text = "+1";

            // Underlying model is updated!
            dynamic data = model;

            Assert.NotNull((object)data.Address);
            Assert.NotNull((object)data.Address.Phone);
            Assert.NotNull((object)data.Address.Phone.Prefix);
            Assert.Equal("+1", (string)data.Address.Phone.Prefix);

            // Change underlying data model
            data.Address.Phone.Prefix = "+54";

            Assert.Equal("+54", label.Text);
        }
Exemplo n.º 24
0
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task <bool> AddAsync(DictionaryModel model)
        {
            using (var conn = MySqlHelper.GetConnection())
            {
                var result = await conn.InsertAsync <string, DictionaryModel>(model);

                return(!string.IsNullOrWhiteSpace(result));
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task <bool> UpdateAsync(DictionaryModel model)
        {
            using (var conn = MySqlHelper.GetConnection())
            {
                var result = await conn.UpdateAsync(model);

                return(result > 0);
            }
        }
        public ActionResult UploadDirectly()
        {
            var model = new DictionaryModel(m_cloudinary, new Dictionary <string, string>()
            {
                { "unsigned", "false" }
            });

            return(PartialView("UploadDirectly", model));
        }
Exemplo n.º 27
0
        public bool Add(DictionaryModel model, Guid userID, DateTime dt)
        {
            int iCount = new DictionaryDA().Add(model.DicCode, model.EN_Name, model.CHS_Name, model.CHT_Name
                                                , model.ParentCode, model.Remark, model.Index
                                                , model.IsDisable, userID, dt
                                                , model.Extend1, model.Extend2, model.Extend3, model.Extend4);

            return(iCount > 0 ? true : false);
        }
Exemplo n.º 28
0
        public DictionaryModel ReadDictionaryById(DictionaryTypesEnum type, long?id, string lang)
        {
            if (id != null)
            {
                string query = "";
                switch (type)
                {
                case DictionaryTypesEnum.Positions:
                    query = $@"
                            select p.IdPosition as Id, t.Name as Name
                            from Positions p
                            join PositionTranslations t on p.IdPosition = t.IdPosition 
                            join Languages l on t.IdLanguage = l.IdLanguage
                            where p.IdPosition = {id} and l.code = '{lang}'
                        ";
                    break;

                case DictionaryTypesEnum.Ward:
                    query = $@"
                            select p.IdWard as Id, t.Name as Name
                            from Wards p
                            join WardTranslations t on p.IdWard = t.IdWard 
                            join Languages l on t.IdLanguage = l.IdLanguage
                            where p.IdWard = {id} and l.code = '{lang}'
                        ";
                    break;

                case DictionaryTypesEnum.Priorities:
                    query = $@"
                            select p.IdPriority as Id, t.Name as Name
                            from Priorities p
                            join PriorityTranslations t on p.IdPriority = t.IdPriority
                            join Languages l on t.IdLanguage = l.IdLanguage
                            where p.IdPriority = {id} and l.code = '{lang}'
                        ";
                    break;

                case DictionaryTypesEnum.Status:
                    query = $@"
                            select p.IdStatus as Id, t.Name as Name
                            from Status p
                            join StatusTranslations t on p.IdStatus = t.IdStatus
                            join Languages l on t.IdLanguage = l.IdLanguage
                            where p.IdStatus = {id} and l.code = '{lang}'
                        ";
                    break;
                }
                DictionaryModel model = BaseDAO.SelectFirst(query, ReadDictionaryModel);
                model.Type = type;
                return(model);
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// 数据字典
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Dictionary <string, object> GetBaseData(DictionaryModel model)
        {
            Dictionary <string, object> dic = new Dictionary <string, object>();
            var areaList    = _Db.Db().Queryable <tax_dictionary>().Where(n => n.ParentCode == model.areaCode).Select(m => new { value = m.Code, text = m.Name }).ToList();
            var companyList = _Db.Db().Queryable <tax_dictionary>().Where(n => n.ParentCode == model.companyCode).Select(m => new { value = m.Code, text = m.Name }).ToList();

            dic.Add("areaList", areaList);
            dic.Add("companyList", companyList);
            return(dic);
        }
Exemplo n.º 30
0
        public DictionaryModel GetByID(string code)
        {
            DictionaryModel model = new DictionaryModel();

            code = string.IsNullOrEmpty(code) ? string.Empty : code;
            DataSet ds = new DictionaryDA().Get(code);

            model = ds.ToList <DictionaryModel>().FirstOrDefault();
            return(model);
        }
 public ActionResult Index(DictionaryModel model)
 {
     return this.View(model);
 }
 public ActionResult Hidden(DictionaryModel model)
 {
     return this.View(model);
 }