Esempio n. 1
0
        public void createDict(Langs crsLang, Langs natLang, IEnumerable <string> words, CourseMeta.CacheDict res)
        {
            var crsData = getCrsData(crsLang);
            var forms   = crsData.getWordsForms(words.Distinct().OrderBy(w => w));

            crsData.getNatData(natLang).dictForText(forms, res);
        }
Esempio n. 2
0
        public CategoryPathDTO GetCategoryPath(string categoryName, Langs l)
        {
            long            languageId      = Utils.getLanguage(l);
            long            categoryId      = GetCategoryIdByName(categoryName, l);
            CategoryPathDTO categoryPathDTO = new CategoryPathDTO();

            categoryPathDTO.Path       = new List <Tuple <long, Tuple <string, string> > >();
            categoryPathDTO.CategoryId = categoryId;

            while (categoryId != null)
            {
                categoryPathDTO.Path.Add(
                    new Tuple <long, Tuple <string, string> >
                        (categoryId,
                        new Tuple <string, string>(
                            unitOfWork.CategoryRepository.GetByID(categoryId).CategoryDescriptions.
                            Where(c => c.LanguageId == languageId).FirstOrDefault().Name,
                            unitOfWork.CategoryRepository.GetByID(categoryId).CategoryDescriptions.
                            Where(c => c.LanguageId == (long)Langs.English).FirstOrDefault().Name)
                        )
                    );
                if (unitOfWork.CategoryRepository.GetByID(categoryId).ParentId == null)
                {
                    break;
                }
                categoryId = unitOfWork.CategoryRepository.GetByID(categoryId).ParentId.Value;
            }
            categoryPathDTO.Path.Reverse();
            categoryPathDTO.PathStr = ToStringPath(categoryPathDTO);
            return(categoryPathDTO);
        }
Esempio n. 3
0
        public List <ProductSKUDTO> GetDiscountSkus(long Id, Langs l, Currency cu)
        {
            var discount     = _uitOfWork.DiscountRepository.GetByID(Id);
            var discountSkus = discount.DiscountProducts.Select(g => g.ProductSKU).ToList();

            var skusDtos = new List <ProductSKUDTO>();

            foreach (var sku in discountSkus)
            {
                var        skuDto = new ProductSKUDTO();
                ProductDTO dto    = _productService.GetProductSKU(sku.SKUId, l, cu);
                Mapper.Initialize(c => c.CreateMap <ProductDTO, ProductSKUDTO>());
                skuDto    = Mapper.Map <ProductDTO, ProductSKUDTO>(dto);
                skuDto.Id = sku.SKUId;
                if (discount.IsPercentage)
                {
                    skuDto.DiscountPrice = skuDto.OrginalPrice - (skuDto.OrginalPrice * (discount.Value * 0.01));
                }
                else
                {
                    skuDto.DiscountPrice = skuDto.OrginalPrice - discount.Value;
                }
                skusDtos.Add(skuDto);
            }
            return(skusDtos);
        }
Esempio n. 4
0
 public FlattenStyles(string input, string output, XmlDocument xmlCss, SortedSet <string> needHigher, bool noXmlHeader, string decorateStyles)
     : base(input, output, noXmlHeader)
 {
     _needHigher   = needHigher;
     StyleDecorate = decorateStyles;
     MakeRuleIndex(xmlCss);
     IdentifyDisplayBlockRules(xmlCss);
     _xmlCss            = xmlCss;
     Suffix             = string.Empty;
     _stylesheetPresent = false;
     DeclareBefore(XmlNodeType.Attribute, SaveClassLangDir);
     DeclareBefore(XmlNodeType.Element, Program.EntryReporter);
     DeclareBefore(XmlNodeType.Element, SaveSibling);
     DeclareBefore(XmlNodeType.Element, InsertBefore);
     DeclareBefore(XmlNodeType.Element, RemoveExtraStylesheets);
     DeclareBefore(XmlNodeType.EndElement, SetForEnd);
     DeclareBefore(XmlNodeType.Text, TextNode);
     DeclareBefore(XmlNodeType.EntityReference, OtherNode);
     DeclareBefore(XmlNodeType.Whitespace, OtherNode);
     DeclareBefore(XmlNodeType.SignificantWhitespace, OtherNode);
     DeclareBefore(XmlNodeType.CDATA, OtherNode);
     DeclareBeforeEnd(XmlNodeType.EndElement, DivEnds);
     DeclareBeforeEnd(XmlNodeType.EndElement, UnsaveClass);
     DeclareBeforeEnd(XmlNodeType.EndElement, UnsaveLang);
     SpaceClass = "sp";
     Classes.RemoveRange(0, Classes.Count);
     Langs.RemoveRange(0, Langs.Count);
 }
Esempio n. 5
0
        public List <CategoryPathDTO> GetAllPathsByWebsite(WebSites website, Langs l)
        {
            List <CategoryPathDTO> paths = new List <CategoryPathDTO>();

            paths.AddRange(getSubPathCategories((long)website, l));
            return(paths);
        }
Esempio n. 6
0
        private List <ColorValuesDTO> GetProductColors(long productId, Langs l)
        {
            long languageId = Utils.getLanguage(l);
            List <OptionValue> colorOptionValues = unitOfWork.OptionValueRepository.Get(op =>
                                                                                        op.Option.IsColor == true &&
                                                                                        op.ProductId == productId).ToList();

            List <ColorValuesDTO> colorValueDTOs = new List <ColorValuesDTO>();

            foreach (var colorOptionValue in colorOptionValues)
            {
                ColorValuesDTO colorValueDTO = new ColorValuesDTO();
                colorValueDTO.ColorName = colorOptionValue.OptionValueDescriptions.
                                          Where(op => op.LanguageId == languageId).FirstOrDefault().Name;
                colorValueDTO.ColorNameEnglish = colorOptionValue.OptionValueDescriptions.
                                                 Where(op => op.LanguageId == (long)Langs.English).FirstOrDefault().Name;
                colorValueDTO.IsImages = (colorOptionValue.Value == null);
                colorValueDTO.Image    = colorOptionValue.Value ?? colorOptionValue.ImageUrl;
                colorValueDTO.ValueId  = colorOptionValue.ValueId;
                colorValueDTO.OptionId = colorOptionValue.OptionId;
                if (colorOptionValue.Images.FirstOrDefault() != null)
                {
                    colorValueDTO.ProductImage = colorOptionValue.Images.FirstOrDefault().ImageUrl;
                }
                else
                {
                    colorValueDTO.ProductImage = DefaultImages.Product;
                }
                colorValueDTOs.Add(colorValueDTO);
            }
            return(colorValueDTOs);
        }
Esempio n. 7
0
        public static string[] StemmingWithSQLServer(Langs lang, string phrase)
        {
            var ctx = new FulltextContext();
            var sql = string.Format("SELECT display_term FROM sys.dm_fts_parser('FormsOf(INFLECTIONAL, \"{0}\")', {1}, 0, 1)", phrase.Replace("'", "''") /*https://stackoverflow.com/questions/5528972/how-do-i-convert-a-string-into-safe-sql-string*/, Metas.lang2LCID(lang));

            return(ctx.Set <dm_fts_parser>().FromSql(sql).Select(p => p.display_term).ToArray());
        }
        public List <ColorValuesDTO> GetColorFilters(List <long> productIds, Langs l)
        {
            List <ColorValuesDTO> colors = new List <ColorValuesDTO>();

            IEnumerable <Tuple <string, string> > colorEnglishNamesAndUrls = unitOfWork.OptionValueDescriptionRepository.Get(op =>
                                                                                                                             productIds.Contains(op.ProductId) &&
                                                                                                                             op.OptionValue.Option.IsColor &&
                                                                                                                             op.LanguageId == (long)Langs.English).
                                                                             Select(op =>
                                                                                    new Tuple <string, string>(op.Name,
                                                                                                               op.OptionValue.Value ?? op.OptionValue.ImageUrl)).Distinct();



            for (int i = 0; i < colorEnglishNamesAndUrls.Count(); i++)
            {
                colors.Add(new ColorValuesDTO()
                {
                    ColorName = colorEnglishNamesAndUrls.ElementAt(i).Item1,
                    Image     = colorEnglishNamesAndUrls.ElementAt(i).Item2,
                    IsImages  = colorEnglishNamesAndUrls.ElementAt(i).Item2[0] != '#'
                });
            }
            return(colors);
        }
        public List <SizeValueDTO> GetSizeFilters(List <long> productIds, Langs l)
        {
            IEnumerable <string> sizeEnglishNames = unitOfWork.OptionValueDescriptionRepository.Get(op =>
                                                                                                    productIds.Contains(op.ProductId) &&
                                                                                                    op.OptionValue.Option.IsColor == false &&
                                                                                                    op.LanguageId == (long)Langs.English).
                                                    Select(op => op.Name.ToLower()).Distinct();
            IEnumerable <string> sizeNames = unitOfWork.OptionValueDescriptionRepository.Get(op =>
                                                                                             productIds.Contains(op.ProductId) &&
                                                                                             op.OptionValue.Option.IsColor == false &&
                                                                                             op.LanguageId == (long)Langs.Arabic).
                                             Select(op => op.Name).Distinct();

            List <SizeValueDTO> sizes = new List <SizeValueDTO>();

            for (int i = 0; i < sizeEnglishNames.Count(); i++)
            {
                sizes.Add(new SizeValueDTO()
                {
                    EnglishName = sizeEnglishNames.ElementAt(i),
                    Name        = sizeNames.ElementAt(i)
                });
            }
            return(sizes);
        }
Esempio n. 10
0
        /// <summary>
        /// Adds a command to the list of commands
        /// </summary>
        public void AddCommand(JsonCommand _Command)
        {
            // Item
            ListBoxItem _Item = new ListBoxItem()
            {
                Content = _Command.CommandName,
                Tag     = _Command
            };

            // Event
            _Item.Selected += delegate {
                // Prevent crashing
                if (Directory.Exists(_Command.CommandPath))
                {
                    // Edit title
                    this.Title = string.Format(Langs.Get("profile_window_title"), Profile, _Command.CommandName);

                    // Save selected command
                    if (CurrentBoard != null)
                    {
                        CurrentBoard.SaveCommand();
                    }

                    // Set
                    CurrentBoard = new CommandBoard(_Command, _Item);
                    Utils.EmbedUserControl(CurrentBoard, Grid);
                }
            };

            // Add
            CommandsBox.Items.Add(_Item);
        }
        public CategoryMenuDTO GetCategoryFilters(string categoryName, Langs l)
        {
            long            categoryId      = GetCategoryIdByName(categoryName, l);
            CategoryService categoryService = new CategoryService(unitOfWork);

            return(categoryService.GetCategory(categoryId, l));
        }
Esempio n. 12
0
        public async Task <Weather[]> GetForecastAsync(string city, Units units, Langs lang, SortParam sortBy)
        {
            var reqUrl      = WeatherRequestBuilder.GetForecastUri(city, units, lang);
            var forecastDto = await RestClient.GetAllAsync <ForecastDto>(reqUrl);

            var list = forecastDto.List
                       .Select(dto => new Weather
            {
                City        = city,
                Date        = DateTime.Parse(dto.Day),
                Temperature = dto.Main.Temperature,
                TempMin     = dto.Main.TempMin,
                TempMax     = dto.Main.TempMax,
                Pressure    = dto.Main.Pressure,
                Humidity    = dto.Main.Humidity,
                Wind        = dto.Wind.Speed,
                Clouds      = dto.Clouds.All,
                Description = dto.Weather[0]?.Description
            });
            var orderedList = list;

            if (sortBy != null)
            {
                var propertyInfo = typeof(Weather).GetProperties()
                                   .FirstOrDefault(x => x.Name.EqualsIgnoreCase(sortBy.Field));
                orderedList = sortBy.Asc
                    ? list.OrderBy(x => propertyInfo.GetValue(x, null))
                    : list.OrderByDescending(x => propertyInfo.GetValue(x, null));
            }

            return(orderedList.ToArray());
        }
Esempio n. 13
0
 public Document(string title, Ganres ganre, Langs lang, DateTime publish, string pathToFile, Font font = null, PageSettings pg_settings = null)
 {
     DocumentName    = title;
     Ganre           = ganre;
     Lang            = lang;
     DateOfPublished = publish;
     _pages          = new List <PageContent>();
     if (pg_settings != null)
     {
         DefaultPageSettings = pg_settings;
     }
     else
     {
         DefaultPageSettings.PaperSize    = PaperStandards.GetSizeByName("A5");
         DefaultPageSettings.Landscape    = false;
         DefaultPageSettings.Margins.Left = PrinterUnitConvert.Convert(200, PrinterUnit.TenthsOfAMillimeter, PrinterUnit.Display);
         int short_margin = PrinterUnitConvert.Convert(100, PrinterUnit.TenthsOfAMillimeter, PrinterUnit.Display);
         DefaultPageSettings.Margins.Top = DefaultPageSettings.Margins.Bottom = DefaultPageSettings.Margins.Right = short_margin;
     }
     if (font != null)
     {
         _font = font;
     }
     else
     {
         _font = new Font("Arial", 14);
     }
     _storageReader = new StorageReader(pathToFile);
     _storageReader.eventHandler += OnReadLine;
     _storageReader.read_line();
 }
Esempio n. 14
0
        /// <summary>
        /// Load current profile commands
        /// </summary>
        public static void LoadCommands()
        {
            // Unload gammar
            Recognizer.UnloadAllGrammars();

            // Profile is valid
            if (Profiles.GetProfile() != null)
            {
                // There is commands
                List <JsonCommand> _ProfileCommands = Profiles.GetProfileCommands();
                if (_ProfileCommands.Count() > 0)
                {
                    // Commands
                    Choices _Commands = new Choices();

                    // Add commands
                    _ProfileCommands.ForEach(a => _Commands.Add(a.CommandName));

                    // Add grammar
                    GrammarBuilder _Builder = new GrammarBuilder();
                    _Builder.Append(_Commands);
                    _Builder.Culture = RecognizerInfo.Culture;
                    Grammar _Grammar = new Grammar(_Builder);

                    // Load grammar
                    Recognizer.LoadGrammar(_Grammar);
                }

                Utils.Log(String.Format(Langs.Get("profile_loaded"), Profiles.GetProfile(), _ProfileCommands.Count()));
            }
        }
Esempio n. 15
0
        internal void change_User_Lang(Langs newlang, int userid)
        {
            try
            {
                //change cached
                var cachedUsr = MainParams.cashedUsers.Find(user => user.user_id == userid);
                if (cachedUsr == null)
                {
                    cachedUsr = MainParams.datebase.FindUserInDb(userid);
                }

                cachedUsr.current_Lang = newlang;
                cachedUsr.user_culture = (newlang == Langs.En ? CultureInfo.InvariantCulture :
                                          (newlang == Langs.Farsi ? CultureInfo.GetCultureInfo("fa-IR") : CultureInfo.GetCultureInfo("ru-RU")));
                //change db
                using (FCatsBotEntities Context = new FCatsBotEntities())
                {
                    var dbUser = Context.users.FirstOrDefault(uss => uss.user_id == userid);

                    dbUser.user_lang_var = (newlang == Langs.En ? "en" : (newlang == Langs.Farsi ? "farsi": "ru"));
                    Context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                MainParams.nlog.Debug("***NewLogs; DATABASE change_User_Lang!!! ;EX=;" + ex.Message + ";Source=" + ex.Source + ";stack=" + ex.StackTrace + ";e.inner=" + ex.InnerException);
                MainParams.nlog.Debug(ex);
            }
        }
Esempio n. 16
0
        public CategoryMenuDTO GetRandomCategory(Langs l, WebSites w)
        {
            long   languageId = Utils.getLanguage(l);
            var    list       = unitOfWork.CategoryRepository.Get(c => true).AsEnumerable().Where(c => (long)getWebsite(c.Id) == (long)w);
            Random random     = new Random();
            long   seed       = random.Next();

            list = list.OrderBy(s => (~(s.Id & seed)) & (s.Id | seed)); // ^ seed);
            if (!list.Any())
            {
                return(null);
            }
            var first = list.First();

            Mapper.Initialize(cfg => cfg.CreateMap <Category, CategoryMenuDTO>()
                              .ForMember(dest => dest.EnglishName, opt =>
                                         opt.MapFrom(src => src.CategoryDescriptions.Where(dsc => dsc.LanguageId == (long)Langs.English).FirstOrDefault().Name)
                                         )
                              .ForMember(dest => dest.Name, opt =>
                                         opt.MapFrom(src => src.CategoryDescriptions.Where(dsc => dsc.LanguageId == (long)l).FirstOrDefault().Name))
                              .ForMember(dest => dest.ImageUrl, opt =>
                                         opt.MapFrom(src => src.ImageUrl ?? DefaultImages.Category)
                                         ).ForMember(dest => dest.Banner, opt =>
                                                     opt.MapFrom(src => src.Banner ?? DefaultImages.Banner)
                                                     )
                              );

            //CategoryMenuDTO menuCategoryDTO = Mapper.Map<Category, CategoryMenuDTO>(first);
            CategoryMenuDTO menuCategoryDTO = Mapper.Map <Category, CategoryMenuDTO>(first, opt =>
                                                                                     opt.AfterMap((src, dest) => dest.Name = src.CategoryDescriptions.Where(dsc => dsc.LanguageId == (long)l).FirstOrDefault().Name));

            return(menuCategoryDTO);
        }
Esempio n. 17
0
 public static void jsMinify(string dplUrl, string dest, Langs lng = Langs.no) {
   var files = FileSources.pathsFromDpl(dplUrl, lng).ToArray();
   var destFn = FileSources.pathFromUrl(dest);
   var res = jsMinify(files);
   File.WriteAllText(destFn, res);
   Trace.TraceInformation("Minified JS: " + destFn);
 }
Esempio n. 18
0
        public Form1()
        {
            InitializeComponent();

            #region BW SETTINGS
            bwDecrypt.DoWork                    += bwDecrypt_DoWork;
            bwDecrypt.ProgressChanged           += bwDecrypt_ProgressChanged;
            bwDecrypt.RunWorkerCompleted        += bwDecrypt_RunWorkerCompleted;
            bwDecrypt.WorkerReportsProgress      = true;
            bwDecrypt.WorkerSupportsCancellation = true;

            bwEncrypt.DoWork                    += bwEncrypt_DoWork;
            bwEncrypt.ProgressChanged           += bwEncrypt_ProgressChanged;
            bwEncrypt.RunWorkerCompleted        += bwEncrypt_RunWorkerCompleted;
            bwEncrypt.WorkerReportsProgress      = true;
            bwEncrypt.WorkerSupportsCancellation = true;
            #endregion

            aes = new AESCrypting(false);
            jtf = new JsonsToPaths();

            rbFile.Checked       = true;
            rbDontDelete.Checked = true;
            btnStop.Enabled      = false;

            tt = new TranslateText();
            TranslateFromList(tt.TranslateToTable(Langs.lang_eng));
            lang = Langs.lang_eng;

            files = new List <string>();

            txbConfirm.ForeColor = Color.Gray;
            txbPass.ForeColor    = Color.Gray;
        }
Esempio n. 19
0
 public static Tuple <double, String> getCurrency(Currency c, Langs l, double amount)
 {
     //if (c == Currency.Dollar)
     if (false)
     {
         amount = Math.Round(amount / 3.75, 2);
         if (l == Langs.English)
         {
             return(new Tuple <double, string>(amount, "$"));
             //return new Tuple<double, string>(amount, amount.ToString("C", CultureInfo.CreateSpecificCulture("en-US")));
         }
         else
         {
             return(new Tuple <double, string>(amount, "$"));
             //return new Tuple<double, string>(amount, amount.ToString("C", CultureInfo.CreateSpecificCulture("en-US")));
         }
     }
     else
     {
         //amount*=3.75;
         if (l == Langs.English)
         {
             //return new Tuple<double, string>(amount, amount.ToString("C", CultureInfo.CreateSpecificCulture("ar-SA")));
             return(new Tuple <double, string>(amount, "SAR"));
         }
         else
         {
             return(new Tuple <double, string>(amount, "ريال"));
             //return new Tuple<double, string>(amount, amount.ToString("C", CultureInfo.CreateSpecificCulture("ar-SA")));
         }
     }
 }
Esempio n. 20
0
 public static string getCurrencyName(Currency c, Langs l)
 {
     if (c == Currency.Dollar)
     {
         if (l == Langs.English)
         {
             return("$");
         }
         else
         {
             return("$");
         }
     }
     else
     {
         if (l == Langs.English)
         {
             return("SAR");
         }
         else
         {
             return("ريال");
         }
     }
 }
Esempio n. 21
0
        public override async Task Execute(Message message, TelegramBotClient client, ApplicationContext context, TelegramMarkupsService markups)
        {
            if (Langs.Contains(message.Text))
            {
                await SetLanguage(message, client, context, markups);

                return;
            }

            var chat = message.Chat;
            var user = context.Users.FirstOrDefault(usr => usr.TelegramId == chat.Id); // Finding user in database

            // If user not registered
            if (user == null)
            {
                return;
            }

            if (ChooseLang == null)
            {
                ChooseLang = await context.Lines.FindAsync("chooseLang");
            }
            var chooseLang = ChooseLang.GetTranslate(user.Lang);

            await client.SendTextMessageAsync(user.TelegramId, chooseLang, replyMarkup : markups.GetLanguageMarkup());
        }
Esempio n. 22
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Name,DisplayName,Priority")] Langs langs)
        {
            if (id != langs.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(langs);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!LangsExists(langs.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(langs));
        }
Esempio n. 23
0
        private static long RunSort(Programmers programmer, Langs lang, sortAlgos algo, string pathToInput)
        {
            var watch = System.Diagnostics.Stopwatch.StartNew();

            //String command = programPath + "\" " + NameFromAlgo(algo) + " " + pathToInput;

            Process process = new Process();

            process.StartInfo.FileName = GetProgramPath(programmer, lang);
            if (programmer == Programmers.Andrew)
            {
                process.StartInfo.Arguments = GetOptionalFirstArg(programmer, lang) + " " + NameFromAlgo(programmer, algo) + " " + pathToInput;
            }
            else
            {
                process.StartInfo.Arguments = GetOptionalFirstArg(programmer, lang) + " " + pathToInput + " " + NameFromAlgo(programmer, algo);
            }
            process.Start();

            /*ProcessStartInfo cmdsi = new ProcessStartInfo("cmd.exe");
             * cmdsi.Arguments = command;
             * Process cmd = Process.Start(cmdsi);*/

            process.WaitForExit();

            watch.Stop();
            long elapsedMs = watch.ElapsedMilliseconds;

            return(elapsedMs);
        }
Esempio n. 24
0
        public override async Task <bool> Contains(Message message, ApplicationContext context)
        {
            if (message.Type != MessageType.Text)
            {
                return(false);
            }

            var chat = message.Chat;
            var user = context.Users.FirstOrDefault(usr => usr.TelegramId == chat.Id); // Finding user in database

            // If user not registered
            if (user == null)
            {
                return(false);
            }

            if (Name == null)
            {
                Name = await context.Lines.FindAsync("changeLanguage");
            }

            if (Langs.Count == 0)
            {
                foreach (UserLang lang in Enum.GetValues(typeof(UserLang)))
                {
                    Langs.Add(lang.ToString());
                }
            }
            return(Name.Contains(message.Text) || Langs.Contains(message.Text));
        }
Esempio n. 25
0
        private OrderItemDTO GetOrderItemById(long orderItemId, Langs
                                              l, Currency cu)
        {
            OrderItem    orderItem    = unitOfWork.OrderItemRepository.GetByID(orderItemId);
            OrderItemDTO orderItemDTO = new OrderItemDTO();

            orderItemDTO.Id       = orderItem.Id;
            orderItemDTO.ImageUrl = orderItem.ImageUrl;
            orderItemDTO.Name     = orderItem.Name;


            if (l == Langs.English)
            {
                orderItemDTO.ColorEnglish = orderItem.ColorEnglish;
                orderItemDTO.SizeEnglish  = orderItem.SizeEnglish;
            }
            else
            {
                orderItemDTO.ColorEnglish = orderItem.ColorArabic;
                orderItemDTO.SizeEnglish  = orderItem.SizeArabic;
            }



            orderItemDTO.OrderId      = orderItem.OrderId;
            orderItemDTO.Quantity     = orderItem.Quantity;
            orderItemDTO.TotalPrice   = Utils.getCurrency(cu, l, orderItem.TotalPrice).Item1;
            orderItemDTO.UnitPrice    = Utils.getCurrency(cu, l, orderItem.UnitPrice).Item1;
            orderItemDTO.CurrencyName = Utils.getCurrencyName(cu, l);
            orderItemDTO.SKU          = orderItem.SKU;
            return(orderItemDTO);
        }
Esempio n. 26
0
        private static string GetOptionalFirstArg(Programmers programmer, Langs lang)
        {
            switch (lang)
            {
            case Langs.Java:
                if (programmer == Programmers.Andrew)
                {
                    return(andrewCodePath + "Main" + "\"");
                }
                else
                {
                    return(codyCodePath + "Program" + "\"");
                }

            case Langs.Python:
                if (programmer == Programmers.Andrew)
                {
                    return(andrewCodePath + "Sort.py" + "\"");
                }
                else
                {
                    return(codyCodePath + "sort.py" + "\"");
                }
            }

            return("");
        }
Esempio n. 27
0
 private string GetMethodName(long methodId, Langs l)
 {
     return(unitOfWork.ShippingBillingMethodRepository.
            GetByID(methodId).
            ShippingBillingMethodDescriptions.
            Where(c => c.LanguageId == (long)l).FirstOrDefault().Name);
 }
Esempio n. 28
0
 private void BtnAttackTargetDummyClick(object sender, EventArgs e)
 {
     if (ObjectManager.InGame)
     {
         Langs.Load();
         if (ObjectManager.MyPlayer.IsValid && Langs.TrainingDummy(ObjectManager.MyPlayer.Target.Name))
         {
             if (_killDummy == null || !_killDummy.IsAlive)
             {
                 KeyHelper.LoadKeys();
                 BarMapper.MapBars();
                 if (CombatEngine.StartOk)
                 {
                     CombatEngine.BotStarted();
                 }
                 else
                 {
                     Logging.Write(LogType.Warning, "CustomClass returned false on StartOk not starting");
                     return;
                 }
                 _killDummy              = new Thread(KillTheDummy);
                 _killDummy.Name         = "KillDummy";
                 _killDummy.IsBackground = true;
                 _killDummy.Start();
             }
             BtnAttackTargetDummy.Enabled = false;
         }
         else
         {
             Logging.Write("Please target a Training dummy ingame");
         }
     }
 }
Esempio n. 29
0
    //musi funkcne odpovidat d:\LMCom\rew\Web4\JsLib\Controls\Dict\Dict.ts, wordsForDesignTime
    public static IEnumerable <string> wordsForDesignTime(string sent, Langs crsLang)
    {
        if (string.IsNullOrEmpty(sent))
        {
            yield break;
        }
        sent = sent.ToLower();
        if (crsLang == Langs.ru_ru)
        {
            sent = normalizeRussian(sent);
        }
        List <char> word = new List <char>();

        for (int i = 0; i <= sent.Length; i++)
        {
            char ch = i < sent.Length ? sent[i] : ' '; var isWord = isWordChar(ch);
            if (isWord)
            {
                word.Add(ch);
            }
            else if (word.Count > 0 && !isWord)
            {
                yield return(new String(word.ToArray())); word.Clear();
            }
        }
    }
Esempio n. 30
0
        private void Install()
        {
            // Stop timer
            Timer.Stop();

            try {
                // Extract files
                ZipFile.ExtractToDirectory(Reference.TempUpdateZip, Reference.TempUpdatePath);
                // Check files
                if (File.Exists(Reference.TempUpdateFile))
                {
                    // Start setup
                    Process _Update = new Process();
                    _Update.StartInfo.FileName  = Reference.TempUpdateFile;
                    _Update.StartInfo.Arguments = String.Format(" /sp- /silent /nocancel /norestart /closeapplications /restartapplications /dir=\"{0}\"", Reference.AppPath);
                    _Update.Start();
                }
                else
                {
                    MessageBox.Show(Langs.Get("update_install_error"), Reference.AppName, MessageBoxButton.OK, MessageBoxImage.Error);
                    Utils.CloseApplication();
                }
            } catch {
                MessageBox.Show(Langs.Get("update_install_error"), Reference.AppName, MessageBoxButton.OK, MessageBoxImage.Error);
            } finally {
                Utils.CloseApplication();
            }
        }
Esempio n. 31
0
        public CategoryMenuDTO GetAll(Langs l, WebSites w)
        {
            CategoryMenuDTO ctmDTO = GetAll(l);

            ctmDTO.SubCategories =
                ctmDTO.SubCategories.AsEnumerable().Where(c => c.Id == (long)w).FirstOrDefault().SubCategories;
            return(ctmDTO);
        }
Esempio n. 32
0
 public static Dir Load(Langs lang, bool forceScan = false) {
   var fn = string.Format(@"{0}RwTTS\{1}\map.xml", Machines.rootPath, lang);
   if (File.Exists(fn) && !forceScan) { var res = XmlUtils.FileToObject<Dir>(fn); res.selfPath = fn; return res; }
   LowUtils.AdjustFileDir(fn);
   return new Dir() {
     lang = lang,
     Items = new DirectoryInfo(Path.GetDirectoryName(fn)).GetFiles("*.xml", SearchOption.AllDirectories).Where(f => f.Name.ToLower() != "map.xml").Select(f => XmlUtils.FileToObject<DirItem>(f.FullName)).ToList(),
     selfPath = fn,
   };
 }
Esempio n. 33
0
        public async Task<IEnumerable<Template>> GetTemplates(string code, string appCode, MsgTypes? msgType = null, Langs? lang = null) {
            var cond = new TemplateSearchCondition() {
                AllowPage = false,
                AppCode = appCode,
                Code = code,
                Lang = lang,
                MsgType = msgType
            };

            return await this.TemplateBiz.Value.Search(cond);
        }
Esempio n. 34
0
 string decode(Langs lng) {
   switch (lng) {
     case Langs.en_gb: return "English";
     case Langs.de_de: return "German";
     case Langs.fr_fr: return "French";
     case Langs.sp_sp: return "Spanish";
     case Langs.it_it: return "Italian";
     case Langs.pt_pt: return "Portuguese";
     default: throw new NotImplementedException();
   }
 }
Esempio n. 35
0
 static Sentence insert(TradosDB db, string name, string srcText, Langs srcLang, string transText, Langs transLang) {
   TradosDT.Sentence sent = new TradosDT.Sentence();
   db.Sentences.Add(sent);
   sent.Name = name;
   sent.SrcLang = (short)srcLang;
   sent.SrcText = srcText;
   sent.TransLang = (short)transLang;
   sent.TransText = transText;
   //sent.TransText = sent.TransText.Replace("\r\n", crlfCode);
   sent.finish();
   return sent;
 }
Esempio n. 36
0
 public static filter indexPartFilter(bool isJS, servConfig.Apps app, servConfig.SkinIds skin, servConfig.Brands brand, Langs lang, bool isMin) {
   return new filter {
     apps = new servConfig.Apps[] { app },
     langs = new Langs[] { lang },
     allBrendMasks = new string[] { isJS ? brendJSMask : brendCSSMask },
     allSkinMasks = new string[] { isJS ? skinJSMask : skinCSSMask },
     allBrands = new string[] { brand.ToString() },
     allSkins = new string[] { skin.ToString() },
     allFixs = isJS
       ? (!isMin ? new string[] { "js", "js{loc}" } : new string[] { "jsmin", "js{loc}min" })
       : (!isMin ? new string[] { "css" } : new string[] { "cssmin" })
   };
 }
Esempio n. 37
0
 public static void writeFile(string dir, string fn, Langs Key, string Value, bool incRJson = false) {
   string destFn = dir + (Key == Langs.no ? null : Key.ToString().Replace('_', '-') + "\\") + fn;
   LowUtils.AdjustFileDir(destFn);
   File.WriteAllText(destFn, Value);
   string value = Value;
   if (incRJson) {
     destFn = destFn.Replace(".json", ".rjson");
     value = Noesis.Lib.JSON2RJSON(Value);
     File.WriteAllText(destFn, value);
   }
   using (Stream msOut = File.OpenWrite(destFn + ".gzip")) {
     using (GZipStream gzip = new GZipStream(msOut, CompressionMode.Compress))
     using (StreamWriter wrg = new StreamWriter(gzip))
       wrg.Write(value);
   }
 }
Esempio n. 38
0
        public async Task<Template> GetByCode(string code, string appCode, MsgTypes msgType, Langs? lang) {
            code = code.ToUpper().Trim();
            appCode = appCode.ToUpper();

            using (var db = new Entities()) {
                var query = db.Templates.Where(t =>
                    !t.IsDeleted
                    && t.Code.ToUpper() == code
                    && t.AppCode.ToUpper() == appCode
                    && t.MsgType == msgType
                    && ((lang != null && t.Lang == lang.Value) || (lang == null && t.IsDefault))
                    );

                return await query.FirstOrDefaultAsync();
            }
        }
Esempio n. 39
0
 static string resxFileName(string fn, Langs lang) {
   return fn.Replace(".resx", "." + lang.ToString().Replace('_', '-') + ".resx");
 }
Esempio n. 40
0
    public static IEnumerable<exportCmlItem> ExportXmlItems(LocPageGroup grp, Langs transLang, List<LocCommand> filter) {
      Langs srcLang = LocCfg.Instance().findPageGroup(grp).FindSrcLang(transLang);
      TradosDT.TradosDB db = TradosDT.TradosDB.getTradosContext(false);
      foreach (TradosDT.Page pg in db.Pages.Where(p => p.PageGroup == (short)grp))
        foreach (exportCmlItem item in ExportXmlItems(db, pg, srcLang, transLang, filter))
          yield return item;

    }
Esempio n. 41
0
 public static Sentence insert(TradosDB db, int pageId, string name, string srcText, Langs srcLang, string transText, Langs transLang) {
   var sent = insert(db, name, srcText, srcLang, transText, transLang); sent.PageId = pageId; return sent;
 }
Esempio n. 42
0
 public static void cancelOper2(LocPageGroup group, Langs transLang) {
   TradosDT.TradosDB db = TradosDT.TradosDB.getTradosContext();
   foreach (int pageId in db.Pages.Where(p => p.PageGroup == (short)group).Select(p => p.Id))
     db.Sentences.RemoveRange(db.Sentences.Where(s2 => s2.PageId == pageId && s2.TransLang == (short)transLang));
   db.SaveChanges();
 }
Esempio n. 43
0
 public static Stream LocalizeXmlLow(string fn, Langs lng) { return LocalizeXmlLow(fn, lng, true); }
Esempio n. 44
0
 static string dataPath(Langs lang, LocPageGroup grp) {
   if (grp.ToString().IndexOf("EA") == 0) {
     string prefix = "http://test.langmaster.cz/";
     switch (lang) {
       case Langs.cs_cz: return prefix + "eduauthornew/";
       default:
         string lng = lang.ToString().Substring(3);
         return prefix + "com" + lng + "/";
     }
   } else {
     return "http://test.langmaster.cz/lmcom/com/" + lang.ToString().Replace('_', '-') + "/";
   }
 }
Esempio n. 45
0
 static void modifyDownloads(XElement root, CourseIds prodUrl, string id, Langs[] lngs, CSLocalize.LangItems li, StringBuilder sb) {
   foreach (XElement el in root.Elements().Where(el => el.Name == "GroupSubName" || el.Name == "DesktopName" || el.Name == "AppName")) {
     sb.Length = 0;
     foreach (Langs lng in lngs) {
       if (sb.Length > 0) sb.Append("~~°°^^");
       string l = lng.ToString().Replace('_', '-');
       //if (l == "es-es") l = "sp-sp";
       sb.Append(l);
       if (l == "sp-sp") l = "es-es";
       sb.Append('=');
       string val = li.GetString(id + "." + el.Name, new System.Globalization.CultureInfo(l), "*** missing translation ***");
       //Nemodifikuj AppName a DesktopName:
       if (!prodUrl.ToString().Contains("Berlitz")) {
         if (el.Name == "DesktopName") val += " (LANGMaster.com)";
         else if (el.Name == "AppName") val = "LANGMaster.com: " + val;
       }
       sb.Append(val);
     }
     el.Value = sb.ToString();
   }
 }
Esempio n. 46
0
 public static void decodeLangs(string langs, out Langs srcLang, out Langs transLang) {
   string[] parts = langs.Split(new string[] { "=>" }, StringSplitOptions.RemoveEmptyEntries);
   srcLang = (Langs)Enum.Parse(typeof(Langs), parts[0]);
   transLang = (Langs)Enum.Parse(typeof(Langs), parts[1]);
 }
Esempio n. 47
0
 public IEnumerable<GroupSrcLang> SrcLangForDestLang(Langs transLang) {
   //return Enumerable.Empty <GroupSrcLang>();
   var res = Groups.Where(g => g.TransDef != null).
     Select(gs => gs.TransDef.Where(td => td.Trans == transLang).Select(td => new GroupSrcLang() { Group = gs.Group, TransDef = td }).SingleOrDefault()).
     Where(r => r != null).ToArray();
   var def = Groups.Select(gs => TransDef.Where(td => td.Trans == transLang).Select(td => new GroupSrcLang() { Group = gs.Group, TransDef = td }).SingleOrDefault()).
     Where(r => r != null);
   return res.Concat(def.Where(dg => !res.Any(rg => rg.Group == dg.Group)));
 }
Esempio n. 48
0
 /// <summary>
 /// Pro grupu vrati zdrojovy jazyk k jazyku prekladu. Chyba je-li transLang=TransLang
 /// </summary>
 public Langs FindSrcLang(Langs transLang) {
   if (transLang == PrimaryLang) throw new Exception("Špatně vybarný jazyk: jazyk zdroje je roven jazyku překladu");
   LocCfgTransDef res = null;
   if (TransDef != null)
     res = TransDef.Where(d => d.Trans == transLang).FirstOrDefault();
   if (res != null) return res.Src;
   res = LocCfg.Instance().TransDef.Where(d => d.Trans == transLang).FirstOrDefault();
   if (res != null) return res.Src;
   throw new Exception("Missing TransDef item in LocCfg for lang: " + transLang.ToString());
 }
Esempio n. 49
0
    static XElement LocalizeXml(string virtualFn, Langs lang, bool removeForceTrans) {
      if (lang == Langs.sp_sp) lang = Langs.es_es;
      XElement root = fileToXml(virtualFn);
      //string dir = Path.GetDirectoryName(fn);
      //string name = Path.GetFileName(fn).Replace(".aspx.lmdata", null);
      string outFn = resxFileName(resxFileName(virtualFn), lang); // dir + @"\App_LocalResources\" + name + "." + lang.ToString().Replace('_', '-') + ".resx";
      //LM16
      //var cfg = NewEATradosLib.HackEx();
      //if (cfg != null && cfg.courseId != CourseIds.EnglishE && !File.Exists(outFn) && lang == Langs.cs_cz) {
      //  outFn = outFn.Replace("cs-cz.", "");
      //}

      if (File.Exists(outFn)) {
        //setUniqueIds(root); //jednoznacne ocislovani uzlu (je jedna ciselna rada pro kazdy tagName) 
        LocFileType fileType = getFileType(virtualFn);
        //Vyhod (**) zavorky
        string f = CSLocalize.transFinal(File.ReadAllText(outFn));
        XElement res = XElement.Parse(f);
        foreach (XAttribute attr in transAttributes(root))
          attr.Value = getResxValue(getResxId(attr), res, outFn);// res.Descendants("value").Where(el => (string)el.Parent.Attribute("name") == id).Select(e => e.Value).Single();
        List<XNode> delNodes = new List<XNode>();
        //kazdy TRANS tag muze mit nekolik souvislych useku k prekladu 
        foreach (List<XNode> src in transFragments(root)) {
          //Preklad do XML fragmentu:
          string id = getResxId(src[0].Parent, fileType);
          XElement newNodes = XElement.Parse(@"<root xmlns=""" + html.NamespaceName + @""">" + getResxValue(id, res, outFn) + "</root>", LoadOptions.PreserveWhitespace);
          src[0].AddAfterSelf(newNodes.Nodes());
          delNodes.AddRange(src);
        }
        //}
        delNodes.Remove<XNode>();
      }
      //Vyhod trans, notrans tagy
      foreach (XElement el in root.Descendants().Where(el => el.Name == html + "trans" || el.Name == html + "notrans" || el.Name == html + "transhelp").ToArray()) {
        if (el.Nodes().Any())
          el.AddAfterSelf(el.Nodes());
        el.Remove();
      }
      //Vyhod transhelp tagy
      foreach (XElement el in root.Descendants().Where(el => el.Name == html + "transhelp"))
        el.Remove();
      //Vyhod force_trans attribute
      if (removeForceTrans) foreach (XAttribute attr in root.DescendantsAndSelf().SelectMany(el => el.Attributes("force_trans")))
          attr.Remove();
      //XXX1
      if (oldToNewTransform!=null) oldToNewTransform(root);
      return root;
    }
Esempio n. 50
0
 public static XElement LocalizeXml(string fn, Langs lang) { return LocalizeXml(fn, lang, true); }
Esempio n. 51
0
 static Stream LocalizeXmlLow(string fn, Langs lng, bool removeForceTrans) {
   Stream str = new MemoryStream();
   LocalizeXmlLow(fn, lng, str, removeForceTrans);
   return str;
 }
Esempio n. 52
0
 public static Lookup insert(TradosDB db, string srcText, Langs srcLang, string transText, Langs transLang) {
   Lookup res = new Lookup(); db.Lookups.Add(res);
   res.finish(srcText, srcLang, transText, transLang);
   return res;
 }
Esempio n. 53
0
 public void finish(string srcText, Langs srcLang, string transText, Langs transLang) {
   SrcText = srcText; SrcLang = (short)srcLang; TransText = transText; TransLang = (short)transLang;
   finish();
 }
Esempio n. 54
0
    /// <summary>
    /// Import RESX souboru do databaze
    /// </summary>
    //public static IEnumerable<string> oper1(LocPageGroup grp) {
    //  LocCfgPageGroupFilter group = LocCfg.Instance().findPageGroup(grp);
    //  //RESX soubory 
    //  List<string> files = getFiles(new LocPageGroup[] { grp }).Where(s => hasResxFile(s)).Select(s => resxFileName(s)).ToList();
    //  if (File.Exists(group.GlobalResourcePath)) files.Add(group.GlobalResourcePath);
    //  if (File.Exists(group.GlobalResourcePathJS)) files.Add(group.GlobalResourcePathJS);
    //  //vsechny stranky grupy k vymazani
    //  List<int> deletePageIds = TradosDT.TradosDB.getTradosContext(false).Pages.Where(p => p.PageGroup == (short)grp).Select(p => p.Id).ToList();
    //  foreach (string fn in files.Where(f => File.Exists(f))) {
    //    TradosDT.TradosDB db = TradosDT.TradosDB.getTradosContext();
        
    //    //Adjustace stranky
    //    TradosDT.Page page = db.Pages.Where(pg => pg.FileName == fn).SingleOrDefault();
    //    if (page == null) { //nova stranka
    //      page = new TradosDT.Page();
    //      db.Pages.Add(page);
    //    } else { //stranka existuje: vymaz vety
    //      //odstran stranku ze stranek k vymazani
    //      deletePageIds.Remove(page.Id);
    //      //Vymazani vsech vet ke strance:
    //      TradosDT.TradosDB pomDb = TradosDT.TradosDB.getTradosContext();
    //      pomDb.CommandTimeout = 1000000;
    //      pomDb.ExecuteCommand("DELETE FROM Sentence WHERE pageid={0} and srclang={1}", page.Id, (short)Langs.no);
    //    }
    //    page.FileName = fn.ToLowerInvariant();
    //    page.PageGroup = (short)grp;
    //    page.SeeUrl = computeSeeUrl(group, page.FileName);
    //    page.Langs = group.fingLangFilter(fn);
    //    db.SaveChanges();
    //    StringBuilder sb = new StringBuilder();
    //    //Vety z resource:
    //    using (ResXResourceReader rdr = new ResXResourceReader(fn))
    //      foreach (System.Collections.DictionaryEntry de in rdr) {
    //        TradosDT.Sentence.insert(db, page.Id, (string)de.Key, null, Langs.no, normalizeXmlText(((string)de.Value).Replace("&nbsp;", "$nbsp;"), sb), group.PrimaryLang);
    //      }
    //    db.SaveChanges();
    //    //Odstraneni (**) zavorek ve zdrojovych resx
    //    string f = StringUtils.FileToString(fn);
    //    f = CSLocalize.transFinal(f);
    //    StringUtils.StringToFile(f, fn);

    //    yield return fn;
    //  }
    //  //Vymaz stranky pro neexistujici soubory
    //  TradosDT.TradosDB delDb = TradosDT.TradosDB.getTradosContext();
    //  foreach (int id in deletePageIds) {
    //    delDb.ExecuteCommand("DELETE FROM Sentence WHERE pageid={0}", id);
    //    delDb.ExecuteCommand("DELETE FROM Pages WHERE id={0}", id);
    //  }
    //}

    public static void oper2(LocPageGroup group, Langs transLang, bool adjustStrong) {
      TradosDT.TradosDB db = TradosDT.TradosDB.getTradosContext();
      if (db.Locks.Where(l => l.Locked && group == (LocPageGroup)l.PageGroup && l.Lang == (short)transLang).Any())
        throw new Exception("Jedna Skupin souborů a Jazyka ja zablokována (locked). Nejdříve odblokujte na unlock.aspx stránce.");
      TradosLib.tradosOper2_forLang(group, transLang, adjustStrong);
    }
Esempio n. 55
0
 public static void AutoTranslate(LocPageGroup grp, Langs transLang, StringBuilder log) {
   List<LocCommand> filter = new List<LocCommand>(); filter.Add(LocCommand.OK);
   StringBuilder sb = new StringBuilder();
   foreach (exportCmlItem item in ExportXmlItems(grp, transLang, filter)) {
     TradosDT.TradosDB db = TradosDT.TradosDB.getTradosContext();
     TradosDT.Sentence sent = db.Sentences.Where(s => s.Id == item.Id).Single();
     string srcText = item.NewSrcText;
     string transText = item.TransText;
     if (!checkTrans(item.Id, ref srcText, ref transText, sb, log)) continue;
     string oldTransText = sent.TransText;
     sent.SrcText = srcText;
     sent.TransText = transText;
     sent.finish();
     RefreshLookup(db, sent, excelTextToXmlText(item.oldSrcText, log), oldTransText, sb, log);
     db.SaveChanges();
   }
 }
Esempio n. 56
0
    /// <summary>
    /// vrati vety k prekladu, v excel kodovani
    /// </summary>
    public static IEnumerable<exportCmlItem> ExportXmlItems(TradosDT.TradosDB db, TradosDT.Page pg, Langs srcLang, Langs transLang, List<LocCommand> filter) {
      StringBuilder sb = new StringBuilder();

      /*var s1 =
        (from Trados.Sentence s in db.Sentences.Where(s => s.PageId == pg.Id && s.TransLang == (short)transLang)
         let newSrc = db.Sentences.Where(s2 => s2.PageId == s.PageId && s2.TransLang == s.SrcLang && s2.Name == s.Name).Select(s2 => new { s2.TransText, s2.TransHash, s2.Id }).Single()
         select new {
           sent = s,
           newSrcText = newSrc.TransText,
           newSrcId = newSrc==null ? -1 : newSrc.Id,
           lookups = db.Lookups.Where(l => l.SrcLang == (short)srcLang && l.TransLang == (short)transLang && l.SrcHash == newSrc.TransHash).
             Select(l => new { l.SrcText, l.TransText })
         }).ToArray();
      if (s1 == null) yield break;*/

      var sentSrcTexts =
        (from TradosDT.Sentence s in db.Sentences.Where(s => s.PageId == pg.Id && s.TransLang == (short)transLang)
         //let newSrc = db.Sentences.Where(s2 => s2.PageId == s.PageId && s2.TransLang == s.SrcLang && s2.Name == s.Name).Select(s2 => new { s2.TransText, s2.TransHash, s2.Id }).Single()
         let newSrc = db.Sentences.Where(s2 => s2.PageId == s.PageId && s2.TransLang == s.SrcLang && s2.Name == s.Name).Select(s2 => new { s2.TransText, s2.TransHash, s2.Id }).First()
         select new {
           sent = s,
           newSrcText = newSrc.TransText,
           newSrcId = newSrc == null ? -1 : newSrc.Id,
           lookups = db.Lookups.Where(l => l.SrcLang == (short)srcLang && l.TransLang == (short)transLang && l.SrcHash == newSrc.TransHash).
             Select(l => new { l.SrcText, l.TransText })
         }).ToArray();
      //Cyklus pres sentence k prekladu (obohacene o text zdrojove sentence)
      foreach (var sentSrcText in sentSrcTexts) {
        string oldSrcText = xmlToExcel(sentSrcText.sent.SrcText, sb);
        string newSrcText = xmlToExcel(sentSrcText.newSrcText, sb);
        LocCommand actCmd = excelFlag(oldSrcText, newSrcText);
        if (actCmd == LocCommand.NONE) continue; //Zdroj je prazdny, neni co prekladat
        //Lookup zaznam: exact match na SrcText
        string[] lkp = sentSrcText.lookups.Where(l => l.SrcText == sentSrcText.newSrcText).Select(l => l.TransText).Distinct().ToArray();
        //lookup zaznam existuje: zmena TRANS nebo CHANGE na OK commandu pro pripad unique exact match v lookup
        if ((actCmd == LocCommand.TRANS || actCmd == LocCommand.CHANGE) && lkp != null && lkp.Length > 0)
          actCmd = lkp.Length == 1 ? LocCommand.OK : LocCommand.CHOICE;
        if (filter != null && filter.IndexOf(actCmd) < 0) continue;
        //Spocitej TransText:
        string transTxt;
        if (actCmd == LocCommand.TRANS)  //predpripravi text s NOTRANS prvky
          transTxt = transXmlToExcel(sentSrcText.sent.TransText, sentSrcText.newSrcText, sb);
        else if (actCmd == LocCommand.OK)  //predpripravi text s NOTRANS prvky
          transTxt = xmlToExcel(lkp[0], sb);
        else if (actCmd == LocCommand.CHOICE) { //nabidne volbu z puvodniho prekladu a vsech lookups
          sb.Length = 0;
          if (!string.IsNullOrEmpty(sentSrcText.sent.TransText)) sb.Append(sentSrcText.sent.TransText + crlfCode + "=============" + crlfCode);
          foreach (string ls in lkp.Where(s => s != sentSrcText.sent.TransText))
            sb.Append(ls + crlfCode + "=============" + crlfCode);
          transTxt = xmlToExcel(sb.ToString(), sb);
        } else //puvodni TRANS text (pro done nebo change)
          transTxt = xmlToExcel(sentSrcText.sent.TransText, sb);
        //return
        yield return new exportCmlItem(
          pg.SeeUrl,
          sentSrcText.sent.Id,
          sentSrcText.sent.Name,
          actCmd,
          transTxt,
          oldSrcText,
          newSrcText,
          sentSrcText.newSrcId);
      }
    }
Esempio n. 57
0
 public static void oper3(LocPageGroup group, Langs transLang, bool doLock, List<LocCommand> commands, Stream str) {
   TradosDT.TradosDB db = TradosDT.TradosDB.getTradosContext();
   TradosDT.Lock lck = new TradosDT.Lock(); db.Locks.Add(lck);
   lck.Created = DateTime.UtcNow;
   lck.Lang = (short)transLang;
   lck.PageGroup = (short)group;
   lck.Locked = doLock;
   db.SaveChanges();
   TradosLib.ExportXml(group, transLang, str, commands);
 }
Esempio n. 58
0
 public static void LocalizeXmlLow(string fn, Langs lng, Stream str, bool removeForceTrans) {
   XElement el = LocalizeXml(fn, lng, removeForceTrans);
   //force xmlns:
   foreach (XAttribute attr in el.Attributes().Where(a => a.Name.Namespace == xmlns || a.Name.LocalName == "xmlns").ToArray())
     attr.Remove();
   el.Add(new XAttribute(xmlns + "lm", "lm"), new XAttribute("xmlns", "htmlPassivePage"));
   byte[] data = Encoding.UTF8.GetBytes(el.ToString(SaveOptions.DisableFormatting));
   str.Write(data, 0, data.Length);
 }
Esempio n. 59
0
 public static void oper4(string fileContent, bool ignoreSentNotExist, Langs srcLang, Langs destLang, StringBuilder log) {
   TradosDT.Sentence sent = null;
   if (ignoreSentNotExist) {
     sent = new TradosDT.Sentence();
     sent.SrcLang = (short)srcLang;
     sent.TransLang = (short)destLang;
   }
   TradosLib.ImportXml(fileContent, sent, log);
 }
Esempio n. 60
0
 public static int ExportXml(LocPageGroup grp, Langs transLang, Stream xml, List<LocCommand> filter) {
   XElement pattern = XElement.Load(HostingEnvironment.ApplicationPhysicalPath + "app_data/TradosExcelPattern.xml", LoadOptions.PreserveWhitespace);
   XNamespace ad = "urn:schemas-microsoft-com:office:spreadsheet";
   XNamespace ss = "urn:schemas-microsoft-com:office:spreadsheet";
   XElement insertPoint = pattern.Descendants(ad + "Row").Single();
   Langs srcLang = LocCfg.Instance().findPageGroup(grp).FindSrcLang(transLang);
   int cnt = 0;
   foreach (var itemGroup in ExportXmlItems(grp, transLang, filter).GroupBy(it => it.SeeUrl)) {
     bool headerOK = false; //ridi pripravu prave jednoho radku s URL adresou na grupu
     foreach (exportCmlItem item in itemGroup) {
       if (!headerOK) {
         headerOK = true;
         insertPoint.AddAfterSelf(
           new XElement(ad + "Row",
             string.IsNullOrEmpty(itemGroup.Key)/*!isUrl(itemGroup.Key)*/ ? null : new XElement(ad + "Cell",
               new XAttribute(ss + "Index", 2),
               new XAttribute(ss + "StyleID", "s71"),
               new XAttribute(ss + "HRef", dataPath(itemGroup.Key, transLang, grp)),
               new XElement(ad + "Data",
                 new XAttribute(ss + "Type", "String"),
                 "GOTO Translation"
               )
             ),
             string.IsNullOrEmpty(itemGroup.Key)/*!isUrl(itemGroup.Key)*/ ? null : new XElement(ad + "Cell",
               new XAttribute(ss + "Index", 3),
               new XAttribute(ss + "StyleID", "s71"),
               new XAttribute(ss + "HRef", dataPath(itemGroup.Key, srcLang, grp)),
               new XElement(ad + "Data",
                 new XAttribute(ss + "Type", "String"),
                 "GOTO Source"
               )
             ),
             new XElement(ad + "Cell",
               new XAttribute(ss + "Index", 4),
           //new XAttribute(ss + "StyleID", "s71"),
               new XElement(ad + "Data",
                 new XAttribute(ss + "Type", "String"),
                 itemGroup.Key
               )
             )
           )
         );
         insertPoint = (XElement)insertPoint.NextNode;
       }
       cnt++;
       insertPoint.AddAfterSelf(
         new XElement(ad + "Row",
         //new XAttribute(ss + "AutoFitHeight", 1),
           new XElement(ad + "Cell",
             new XElement(ad + "Data",
               new XAttribute(ss + "Type", "String"),
               item.actCmd.ToString()
             )
           ),
           new XElement(ad + "Cell",
             new XElement(ad + "Data",
               new XAttribute(ss + "Type", "String"),
               HttpUtility.HtmlDecode(item.TransText)
             )
           ),
           new XElement(ad + "Cell",
             new XElement(ad + "Data",
               new XAttribute(ss + "Type", "String"),
               HttpUtility.HtmlDecode(item.NewSrcText)
             )
           ),
           new XElement(ad + "Cell",
             new XElement(ad + "Data",
               new XAttribute(ss + "Type", "String"),
               HttpUtility.HtmlDecode(item.OldSrcText)
             )
           ),
           new XElement(ad + "Cell",
             new XElement(ad + "Data",
               new XAttribute(ss + "Type", "Number"),
               item.Id
             )
           )
         )
       );
       insertPoint = (XElement)insertPoint.NextNode;
     }
   }
   string output = pattern.ToString(SaveOptions.DisableFormatting);
   output = @"<?xml version=""1.0""?><?mso-application progid=""Excel.Sheet""?>" + output.Replace(crlfCode, "&#10;");
   byte[] outputByte = Encoding.UTF8.GetBytes(output);
   xml.Write(outputByte, 0, outputByte.Length);
   return cnt;
 }