public ActionResult Create(ViewCategoryCreate shopCategory) { if (ModelState.IsValid) { // сохранение ShopCategory category = new ShopCategory(); category.Name = shopCategory.Name; if (shopCategory.Alias == null) { category.Alias = Translit.TranslitString(shopCategory.Name); } else { category.Alias = shopCategory.Alias; } category.Description = shopCategory.Description; category.ParentId = shopCategory.SelectedId; db.ShopCategories.Add(category); db.SaveChanges(); return(RedirectToAction("Index")); } // создание выпадающего списка родительских категорий List <ShopCategory> categories = db.ShopCategories.OrderBy(c => c.Name).ToList(); shopCategory.CategoriesList = new SelectList(categories, "Id", "Name", shopCategory.SelectedId); return(View(shopCategory)); }
public static void AddTranslit(Translit translit) { try { using (var myChannelFactory = new ChannelFactory <ITranslitContract>("Server")) { ITranslitContract client = myChannelFactory.CreateChannel(); client.AddTranslit(translit); } } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } }
public ActionResult Edit(ViewCategoryEdit shopCategory) { if (ModelState.IsValid) { // сохранение ShopCategory category = db.ShopCategories.Find(shopCategory.Id);; bool changeName = false; if (category.Name != shopCategory.Name) { category.Name = shopCategory.Name; changeName = true; } if (shopCategory.Alias == null || changeName) { category.Alias = Translit.TranslitString(shopCategory.Name); } else { category.Alias = shopCategory.Alias; } category.Description = shopCategory.Description; category.ParentId = shopCategory.SelectedId; db.Entry(category).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } // создание выпадающего списка родительских категорий shopCategory.CategoriesList = new SelectList(ParentListForCurrentCategory(shopCategory.Id), "Id", "Name", shopCategory.SelectedId); return(View(shopCategory)); }
private void btnTransliterate_Click(object sender, RoutedEventArgs e) { var region = string.IsNullOrEmpty(_player.Nationality) ? _player.Country : _player.Nationality; if (string.IsNullOrEmpty(region)) { if (Translator.Language == "uk") { region = "ua"; } else { region = Translator.Language; } } ; _player.Surname = Translit.Transliterate(region, _player.LocalSurname); _player.FirstName = Translit.Transliterate(region, _player.LocalFirstName); if (string.IsNullOrEmpty(_player.Surname) && !string.IsNullOrEmpty(_player.LocalSurname)) { _player.Surname = BinaryAnalysis.UnidecodeSharp.Unidecoder.Unidecode(_player.LocalSurname); } if (string.IsNullOrEmpty(_player.FirstName) && !string.IsNullOrEmpty(_player.LocalFirstName)) { _player.FirstName = BinaryAnalysis.UnidecodeSharp.Unidecoder.Unidecode(_player.LocalFirstName); } _player.Update(); }
public RowObj(string tIN, string tFirstName, string tSecondName, string tPatronymic, string tstringDate, string tDistrict, string tEducationalInstitution, string tAdressOfEI, string tGroup) { tstringDate = tstringDate.Trim(); tDistrict = tDistrict.Trim(); tIN = tIN.Trim(); tSecondName = tSecondName.Trim(); tFirstName = tFirstName.Trim(); tPatronymic = tPatronymic.Trim(); tEducationalInstitution = tEducationalInstitution.Trim(); tAdressOfEI = tAdressOfEI.Trim(); tGroup = tGroup.Trim(); tIN = Translit.TranslitIN(tIN); tDistrict = Translit.TranslitSOATO(tDistrict); IN = tIN; FirstName = tFirstName; SecondName = tSecondName; Patronymic = tPatronymic; stringDate = tstringDate; District = tDistrict; EducationalInstitution = tEducationalInstitution; AdressOfEI = tAdressOfEI; Group = tGroup; codeSOATO = SOATOnew.GetSOATO(tDistrict); Validtype = Validation.IsValid(tIN, tFirstName, tSecondName, tPatronymic, tstringDate, tDistrict, tEducationalInstitution, tAdressOfEI, tGroup, codeSOATO); }
public static string GenerateLogin(string secondName, string firstName, string patronymic, DateTime birthDate) { return(string.Format("{0}{1}{2}{3}", Translit.RuEn(firstName.ToUpper()[0].ToString()), Translit.RuEn(patronymic.ToUpper()[0].ToString()), Translit.RuEn(secondName.ToUpper()), birthDate.Day.ToString()).ToLower()); }
public void TestingTransliterS2() { string rus = "Строка, в которой используются цифры: 12366; и другие символы: $%! "; string expect = "Stroka, v kotoroiy ispol'zuyutsya cifry: 12366; i drugiie simvoly: $%! "; string actual = Translit.TranslitRusInEng(rus); Assert.AreEqual(expect, actual); }
public void TestingTransliterS1() { string rus = "Привет, меня зовут Саша"; string expect = "Priviet, mienya zovut Sasha"; string actual = Translit.TranslitRusInEng(rus); Assert.AreEqual(expect, actual); }
public static void AddTranslit(Translit translit) { using (var context = new TransliterationDBContext()) { translit.DeleteDatabaseValues(); context.Translits.Add(translit); context.SaveChanges(); } }
public static string Translit(string input, string lang) { Translit translit = translitRU; if (lang.Equals("ua", StringComparison.InvariantCultureIgnoreCase)) { translit = translitUA; } return(translit.Transliterate(input)); }
public ActionResult Edit(ViewBrandEdit model) { if (ModelState.IsValid) { ShopProductsBrand brand = db.ShopProductsBrands.Find(model.Id); brand.Name = model.Name; brand.Alias = Translit.TranslitString(model.Name); db.Entry(brand).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(model)); }
public ActionResult Create(ViewBrandCreate model) { if (ModelState.IsValid) { ShopProductsBrand brand = new ShopProductsBrand { Name = model.Name, Alias = Translit.TranslitString(model.Name) }; db.ShopProductsBrands.Add(brand); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(model)); }
private void btnTransliterate_Click(object sender, RoutedEventArgs e) { string translit = Translit.Transliterate(_countryCode, _club.Name); if (string.IsNullOrEmpty(translit) && !string.IsNullOrEmpty(_club.Name)) { translit = BinaryAnalysis.UnidecodeSharp.Unidecoder.Unidecode(_club.Name); } _club.NameEn = translit; if (!string.IsNullOrEmpty(translit)) { _club.EGDName = translit.Length <= 4 ? translit : translit.Substring(0, 4); } _club.Update(); }
public override bool LoadModel(MassEmail em, EmailTemplateViewModel template, CompanyUser user) { LoadBaseFeature(em, template, user); //this.DateCycle(em, template, (em, template, dt) => { // template.Models.Add(dt, _mailRepo.ReportRepository.EmailWeekInvoice(dt, _companyid,user)); //}); string sql = ReplaceMacro(em.SQLCommand, ExecModel); var attach = new EMailAttachment(); attach.Content = _mailRepo.ProduceFlatCSV(sql).Result; attach.ContentType = "text/csv"; attach.Name = ReplaceMacro(em.Name, ExecModel); attach.Name = Translit.cyr2lat(attach.Name) + ".csv"; template.Attachments.Add(attach); template.JustAttachment = true; //template.Models.Add(dt, _mailRepo.ReportRepository.EmailWeekInvoice(dt, _companyid, user)); return(true); }
private void button2_Click(object sender, EventArgs e) { if (folderBrowserDialog2.ShowDialog() == DialogResult.OK) { try { IEnumerable <FileInfo> filesPaths = Extractor.GetFiles(folderBrowserDialog2.SelectedPath, new[] { "*.mp3", "*.jpg" }); Translit.TranslitFileNames(filesPaths); MessageBox.Show("Слава Богу, ошибок нет! Всё сработало", "", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch { MessageBox.Show("Ошибка в ядре", "Упс", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show("Что то пошло не так", "Упс", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public ActionResult AddTeacher(string teacherFio) { try { tablePrepods prepodObj = new tablePrepods(); prepodObj.Name = teacherFio; contextDB.tablePrepods.Add(prepodObj); contextDB.SaveChanges(); BRSGSTOU.Translit trans = new Translit(); int prepodID = prepodObj.ID; string Login = trans.TranslitFileName(teacherFio); string Parol = trans.GenPassword(teacherFio).Substring(trans.GenPassword(teacherFio).Length / 2); if (Login.Length > 16) { Login = Login.Substring(0, 16); } if (Parol.Length > 8) { Parol = Parol.Substring(0, 8); } int Rol = 2; contextDB.teachersAccounts.Add(new teachersAccounts { Role_ID = Rol, ID_Prepoda = prepodID, Login = Login, Password = Parol }); contextDB.SaveChanges(); ViewBag.Message = "ok"; return(isAdminMetod()); } catch { return(View("Error")); } }
static void Main(string[] args) { try { Translit trans = new Translit(); string testString = "Юрій Корюківка Ярошенко Знам'янка Згорани Розгон Щербухи Гоща Гаращенко "; Console.WriteLine("Оригинал строки:"); Console.WriteLine(testString); Console.WriteLine("Базовое преобразование:"); Console.WriteLine(trans.ukrToLat(testString)); trans["г"] = "g"; trans["Г"] = "G"; Console.WriteLine("Измененное преобразование:"); Console.WriteLine(trans.ukrToLat(testString)); trans.ResetDictionary(); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadKey(); }
public ActionResult Create(ViewProductCreate model) { for (int i = 0; i < model.SelectedCategoriesId.Length; i++) { ShopCategory category = db.ShopCategories.Find(model.SelectedCategoriesId[i]); model.CategoriesSelected.Add(category); } if (ModelState.IsValid) { ShopProduct product = new ShopProduct { Name = model.Name, Alias = Translit.TranslitString(model.Name), Description = model.Description, VendorCode = model.VendorCode, Weight = model.Weight.Value, Proteins = model.Proteins.Value, Fats = model.Fats.Value, Carbohydrates = model.Carbohydrates.Value, Kcal = model.Kcal.Value }; //брэнд if (model.SelectedBrandId.HasValue) { product.ShopProductsBrand = db.ShopProductsBrands.Find(model.SelectedBrandId); } // вкус if (model.SelectedTasteId.HasValue) { product.ShopProductsTaste = db.ShopProductsTastes.Find(model.SelectedTasteId); } // катгории product.ShopCategories = model.CategoriesSelected; if (model.PortionsWeight.HasValue) { product.PortionsWeight = model.PortionsWeight.Value; } if (model.PortionsCount.HasValue) { product.PortionsCount = model.PortionsCount.Value; } product.DateCreation = DateTime.Now; if (model.Price != null) { ShopProductsPrice price = new ShopProductsPrice { Price = decimal.Parse(model.Price), CurrentPrice = true, DateSet = product.DateCreation, }; product.ShopProductsPrices.Add(price); } //сохранение фото товра if (model.PhotoFile != null) { string fileName = Guid.NewGuid().ToString(); string dirPath = HttpContext.Server.MapPath("~/Content/Images/Shop/Products"); product.PhotoName = Image.Save( model.PhotoFile, dirPath, null, fileName); } db.ShopProducts.Add(product); db.SaveChanges(); return(RedirectToAction("Index")); } // все категории model.CategoriesAll = db.ShopCategories.OrderBy(c => c.Name).ToList(); // список вкусов List <ShopProductsTaste> tastes = db.ShopProductsTastes.OrderBy(c => c.Name).ToList(); model.TasteList = new SelectList(tastes, "Id", "Name"); // список брэндов List <ShopProductsBrand> brands = db.ShopProductsBrands.OrderBy(c => c.Name).ToList(); model.BrandList = new SelectList(brands, "Id", "Name"); return(View(model)); }
public ActionResult Edit(ViewProductEdit model) { if (model.SelectedCategoriesId != null) { for (int i = 0; i < model.SelectedCategoriesId.Length; i++) { ShopCategory category = db.ShopCategories.Find(model.SelectedCategoriesId[i]); model.CategoriesSelected.Add(category); } } if (ModelState.IsValid) { ShopProduct product = db.ShopProducts.Include(p => p.ShopCategories).Include(p => p.ShopProductsBrand).Include(p => p.ShopProductsTaste).Where(p => p.Id == model.Id).SingleOrDefault(); product.Name = model.Name; product.Alias = Translit.TranslitString(model.Name); product.Description = model.Description; product.VendorCode = model.VendorCode; product.Weight = model.Weight.Value; product.Proteins = model.Proteins.Value; product.Fats = model.Fats.Value; product.Carbohydrates = model.Carbohydrates.Value; product.Kcal = model.Kcal.Value; //брэнд if (model.SelectedBrandId.HasValue) { product.ShopProductsBrand = db.ShopProductsBrands.Find(model.SelectedBrandId); } else { product.ShopProductsBrand = null; } // вкус if (model.SelectedTasteId.HasValue) { product.ShopProductsTaste = db.ShopProductsTastes.Find(model.SelectedTasteId); } else { product.ShopProductsTaste = null; } // катгории product.ShopCategories = model.CategoriesSelected; if (model.PortionsWeight.HasValue) { product.PortionsWeight = model.PortionsWeight.Value; } else { product.PortionsWeight = 0; } if (model.PortionsCount.HasValue) { product.PortionsCount = model.PortionsCount.Value; } else { product.PortionsCount = 0; } product.DateCreation = DateTime.Now; //сохранение фото товра if (model.PhotoFile != null) { string fileName = Guid.NewGuid().ToString(); string dirPath = HttpContext.Server.MapPath("~/Content/Images/Shop/Products"); product.PhotoName = Image.Save( model.PhotoFile, dirPath, null, fileName); } db.Entry(product).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } // все категории model.CategoriesAll = db.ShopCategories.OrderBy(c => c.Name).ToList(); // список вкусов List <ShopProductsTaste> tastes = db.ShopProductsTastes.OrderBy(c => c.Name).ToList(); model.TasteList = new SelectList(tastes, "Id", "Name"); // список брэндов List <ShopProductsBrand> brands = db.ShopProductsBrands.OrderBy(c => c.Name).ToList(); model.BrandList = new SelectList(brands, "Id", "Name"); return(View(model)); }
protected override void Seed(ShopRosKvartal.Models.ApplicationDbContext context) { var userManager = new ApplicationUserManager(new UserStore <ApplicationUser>(context)); var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context)); //============================================================ //инициализация ролей if (!context.Roles.Any()) { // создание роли var role = new IdentityRole { Name = "Администратор" }; // добавление роли в бд roleManager.Create(role); role = new IdentityRole { Name = "Модератор" }; roleManager.Create(role); role = new IdentityRole { Name = "Покупатель" }; roleManager.Create(role); } //============================================================ //============================================================ //создание админа для пустой БД var admin = userManager.FindByName("Admin"); if (admin == null || !context.Users.Any()) { // создание админа admin = new ApplicationUser { Email = "*****@*****.**", UserName = "******" }; string password = "******"; var result = userManager.Create(admin, password); // если создание пользователя прошло успешно if (result.Succeeded) { var role = roleManager.FindByName("Администратор"); if (role != null) { // добавляем для пользователя роль userManager.AddToRole(admin.Id, role.Name); } else { // создание роли role = new IdentityRole { Name = "Администратор" }; // добавление роли в бд roleManager.Create(role); // добавляем для пользователя роль userManager.AddToRole(admin.Id, role.Name); } } } //============================================================ //============================================================ //инициализация SMTP сервера if (!context.ToolsSMTPSettings.Any()) { ToolsSMTPSetting smtp = new ToolsSMTPSetting(); smtp.EmailFrom = "*****@*****.**"; smtp.UserName = "******"; smtp.Password = "******"; smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.EnableSsl = true; context.ToolsSMTPSettings.Add(smtp); context.SaveChanges(); } //============================================================ //============================================================ //инициализация таблицы полов пользователей if (!context.UserGenders.Any()) { UserGender gender = new UserGender(); gender.Gender = "Мужской"; context.UserGenders.Add(gender); context.SaveChanges(); gender.Gender = "Женский"; context.UserGenders.Add(gender); context.SaveChanges(); } //============================================================ //============================================================ //инициализация таблицы категории if (!context.ShopCategories.Any()) { ShopCategory parent = new ShopCategory(); parent.Name = "Спортивное питание"; parent.Alias = Translit.TranslitString(parent.Name); context.ShopCategories.Add(parent); context.SaveChanges(); //----------------------------------------------- ShopCategory child = new ShopCategory { Name = "Протеины", ParentId = parent.Id }; child.Alias = Translit.TranslitString(child.Name); context.ShopCategories.Add(child); context.SaveChanges(); //----------------------------------------------- child = new ShopCategory { Name = "Гейнеры", ParentId = parent.Id }; child.Alias = Translit.TranslitString(child.Name); context.ShopCategories.Add(child); context.SaveChanges(); } //============================================================ //============================================================ //инициализация таблицы вкус товара if (!context.ShopProductsTastes.Any()) { string[] tastes = { "Ваниль", "Клубника", "Шоколад", "Карамель-ваниль", "Малина-шоколад", "Миндаль-шоколад", "Малина", "Банан", "Вишня", "Абрикос", "Персик", "Апельсин" }; for (int i = 0; i < tastes.Length; i++) { ShopProductsTaste taste = new ShopProductsTaste { Name = tastes[i] }; context.ShopProductsTastes.Add(taste); context.SaveChanges(); } } //============================================================ //============================================================ //инициализация таблицы брэнды if (!context.ShopProductsBrands.Any()) { string[] brands = { "Optimum Nutrition", "Multipower", "BSN", "Dymatize", "MuscleTech", "Weider", "Sponser", "Twinlab", "Gaspari Nutrition", "Universal Nutrition" }; for (int i = 0; i < brands.Length; i++) { ShopProductsBrand brand = new ShopProductsBrand { Name = brands[i], Alias = brands[i].Replace(" ", "-") }; context.ShopProductsBrands.Add(brand); context.SaveChanges(); } } //============================================================ }
/// <summary> /// Получения списка Тегов в содержащихся в файле CSV /// </summary> /// <param name="fileName"></param> /// <returns></returns> public List <TagCSV> GetListTagFromCSV(string fileName) { List <TagCSV> retList = new List <TagCSV>(); StreamReader fileStream = OpenFile(fileName); //debug string fistLine; if (fileStream != null) { //char[] charsToTrim = { '%','"', '/', '\'' }; //не удаляет первый символ "\" //fistLine = fileStream.ReadLine().Trim(charsToTrim); fistLine = fileStream.ReadLine(); fistLine = Regex.Replace(fistLine, "[@,%\\.\"'\\\\]", string.Empty); fistLine = fistLine.Replace("-", "_"); fistLine = fistLine.Replace("/", "_"); //s = s.Replace("\"", "") string[] headerLine = fistLine.Split(';'); string ll; //После удаления ковычек стало работать нормально //for (int i = 0; i < headerLine.Length; i++) //{ // ll=headerLine[i].Remove(0, 1); // headerLine[i] = ll; //} //foreach (string line in headerLine) //{ // //Удаляем первый символ который почему-то "\" // ll= line.Remove(0, 1); // line = ll; //} ////string[] headerLine = fileStream.ReadLine().Split(';'); string nameTagTemp; int columnTimeStamp; int columnValue; for (int i = 0; i < headerLine.Length; i++) { if (headerLine[i].IndexOf("Time") != -1) { columnTimeStamp = i; nameTagTemp = headerLine[i].Remove(headerLine[i].IndexOf("Time")).Trim(); for (int j = 0; j < headerLine.Length; j++) { if ((headerLine[j].IndexOf(nameTagTemp) != -1) && (headerLine[j].IndexOf("ValueY") != -1)) { columnValue = j; TagCSV tagCSV = new TagCSV() { TagNameRus = nameTagTemp, TagName = Translit.GetTranslit(nameTagTemp), TimeStampColumn = columnTimeStamp, ValueColumn = columnValue }; retList.Add(tagCSV); } } } } } return(retList); }
public void AddTranslit(Translit translit) { EntityWrapper.AddTranslit(translit); }
public static void AddTranslit(Translit translit) { TranslitServiceWrapper.AddTranslit(translit); }
/// <summary> /// Преобразует латинский текст в кириллистический, в указанном формате. /// </summary> /// <param name="Text"></param> /// <param name="Type">Формат преобразования</param> /// <returns></returns> public static String ToCyrillic(String Text, TranslitType Type = TranslitType.ISO) { return(Translit.ToCyrillic(Text, Type)); }