Exemplo n.º 1
0
        public void OperandTypeConstructor()
        {
            var dutchBelgium = new Locales(this.Session).DutchBelgium;

            new C1Builder(this.Session).WithC1AllorsString("c1A").WithC1AllorsDecimal(10.5M).Build();
            new C1Builder(this.Session).WithC1AllorsString("c1B").WithC1AllorsDecimal(11.5M).Build();

            this.Session.Derive(true);

            var csvFile = new CsvExport("Test");

            csvFile.Columns.Add(new CsvExportPath(M.C1.C1AllorsString));
            csvFile.Columns.Add(new CsvExportPath(M.C1.C1AllorsDecimal));

            var aclMock = new Mock <IAccessControlList>();

            aclMock.Setup(acl => acl.CanRead(It.IsAny <PropertyType>())).Returns(true);
            var acls = new AccessControlListCache(null, (allorsObject, user) => aclMock.Object);

            var extent = this.Session.Extent(M.C1.ObjectType).AddSort(M.C1.C1AllorsString);
            var csv    = csvFile.Write(extent, dutchBelgium, acls);

            Assert.AreEqual(
                @"""C1AllorsString"";""C1AllorsDecimal""
""c1A"";""10,5""
""c1B"";""11,5""".Replace("\r\n", "\n"),
                csv.Replace("\r\n", "\n"));
        }
Exemplo n.º 2
0
        public static void SetPieceSymbols(String sLanguage)
        {
            if (sLanguage is null)
            {
                PieceSymbols = default;
            }
            else
            {
                var found = Locales.FirstOrDefault(
                    locale => sLanguage.Equals(locale.Language, StringComparison.InvariantCultureIgnoreCase));
                PieceSymbols = found?.Symbols;

                if (PieceSymbols is null)
                {
                    Parameter[Black].Symbol = "B";
                    Parameter[White].Symbol = "W";
                }
                else
                {
                    Trace.Assert(nSymbols <= PieceSymbols.Length, "Insufficient number of Piece Symbols");
                    Parameter[Black].Symbol = PieceSymbols[vBlack].ToString();
                    Parameter[White].Symbol = PieceSymbols[vWhite].ToString();
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Constructor that takes 3 params.
        /// </summary>
        /// <param name="yourZendeskUrl">Will be formated to "https://yoursite.zendesk.com/api/v2"</param>
        /// <param name="user"></param>
        /// <param name="password">LEAVE BLANK IF USING TOKEN</param>
        /// <param name="apiToken">Optional Param which is used if specified instead of the password</param>
        public ZendeskApi(string yourZendeskUrl, string user, string password = "", string apiToken = "")
        {
            var formattedUrl = GetFormattedZendeskUrl(yourZendeskUrl).AbsoluteUri;

            Tickets             = new Tickets(formattedUrl, user, password, apiToken);
            Attachments         = new Attachments(formattedUrl, user, password, apiToken);
            Views               = new Views(formattedUrl, user, password, apiToken);
            Users               = new Users(formattedUrl, user, password, apiToken);
            Requests            = new Requests.Requests(formattedUrl, user, password, apiToken);
            Groups              = new Groups(formattedUrl, user, password, apiToken);
            CustomAgentRoles    = new CustomAgentRoles(formattedUrl, user, password, apiToken);
            Organizations       = new Organizations(formattedUrl, user, password, apiToken);
            Search              = new Search(formattedUrl, user, password, apiToken);
            Tags                = new Tags(formattedUrl, user, password, apiToken);
            Forums              = new Forums(formattedUrl, user, password, apiToken);
            Categories          = new Categories(formattedUrl, user, password, apiToken);
            Topics              = new Topics(formattedUrl, user, password, apiToken);
            AccountsAndActivity = new AccountsAndActivity(formattedUrl, user, password, apiToken);
            JobStatuses         = new JobStatuses(formattedUrl, user, password, apiToken);
            Locales             = new Locales(formattedUrl, user, password, apiToken);
            Macros              = new Macros(formattedUrl, user, password, apiToken);
            SatisfactionRatings = new SatisfactionRatings(formattedUrl, user, password, apiToken);
            SharingAgreements   = new SharingAgreements(formattedUrl, user, password, apiToken);
            Triggers            = new Triggers(formattedUrl, user, password, apiToken);

            ZendeskUrl = formattedUrl;
        }
Exemplo n.º 4
0
        public void Locale()
        {
            var englishGreatBritain = new Locales(this.Session).EnglishGreatBritain;
            var dutchBelgium        = new Locales(this.Session).DutchBelgium;

            new C1Builder(this.Session).WithC1AllorsString("c1A").WithC1AllorsDecimal(10.5M).Build();
            new C1Builder(this.Session).WithC1AllorsString("c1B").WithC1AllorsDecimal(11.5M).Build();

            this.Session.Derive(true);

            var column1 = new CsvExportPath(M.C1.C1AllorsString);
            var column2 = new CsvExportPath(M.C1.C1AllorsDecimal);

            var export = new CsvExport("Test");

            export.Columns.Add(column1);
            export.Columns.Add(column2);

            var extent = this.Session.Extent(M.C1.ObjectType).AddSort(M.C1.C1AllorsString);

            var user = new Users(this.Session).GetCurrentUser();
            var acls = new AccessControlListCache(user);

            var csvEn = export.Write(extent, englishGreatBritain, acls);
            var csvNl = export.Write(extent, dutchBelgium, acls);

            Assert.AreNotEqual(csvEn, csvNl);
        }
Exemplo n.º 5
0
    public List <Locales> GetEmptyLocales()
    {
        List <Locales> Results = new List <Locales>();

        using (SqlConnection Connection = new SqlConnection(cs))
        {
            using (SqlDataAdapter DAdapter = new SqlDataAdapter("Exec GetEmptyLocales", Connection))
            {
                using (DataSet DS = new DataSet())
                {
                    DAdapter.Fill(DS);

                    if (DS.Tables.Count > 0)
                    {
                        if (DS.Tables[0].Rows.Count > 0)
                        {
                            foreach (DataRow DR in DS.Tables[0].Rows)
                            {
                                Locales Local = new Locales();
                                Local.HashID   = int.Parse(DR["HashID"].ToString());
                                Local.Postcode = DR["Postcode"].ToString();

                                Results.Add(Local);
                            }
                        }
                    }
                }
            }
        }
        return(Results);
    }
Exemplo n.º 6
0
        private void Listar_Vigencias()
        {
            cbx_vigen.Items.Clear();

            /******************************************/
            /*-------    Listamos Vigencias    -------*/
            /******************************************/
            /* Combo Cartas */
            ComboBoxItem item1 = new ComboBoxItem();

            item1.Uid        = "";
            item1.Content    = "[NUEVO REGISTRO]";
            item1.IsSelected = true;
            cbx_vigen.Items.Add(item1);
            DataTable lista_vigen = new DataTable();

            try
            {
                lista_vigen = Locales.Lista_Seguros(_cod_ent, _tipo_ent, sel_tipo);
                foreach (DataRow row in lista_vigen.Rows)
                {
                    ComboBoxItem item = new ComboBoxItem();
                    item.Uid     = row["Id"].ToString();
                    item.Content = " de :" + row["Fec_Ini"].ToString() + " hasta : " + row["Fec_Fin"].ToString();
                    cbx_vigen.Items.Add(item);
                    _ult_seg = row["Id"].ToString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error en Obtener Información de Seguros. " + ex.Message,
                                "Bata - Mensaje De Advertencia", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemplo n.º 7
0
    /// <summary>
    /// This function should be called after the L20n Initialization, but before any translation, if possible.
    /// Even though it's safe to call it at any time during runtime, it is not recommended.
    /// Fonts can't be overriden and an error will be logged if you try.
    /// </summary>
    public static void SetFont(string locale, Font font)
    {
        if (locale == null)
        {
            Debug.LogError("font couldn't be set with the key as a null-value");
            return;
        }

        if (font == null)
        {
            Debug.LogErrorFormat("a null-value can't be used as the font for locale '{0}'", locale);
            return;
        }

        if (!Locales.Contains(locale))
        {
            Debug.LogErrorFormat("can't set font as '{0}' is not a supported local", locale);
            return;
        }

        if (!s_Fonts.ContainsKey(locale))
        {
            s_Fonts.Add(locale, font);
        }
        else
        {
            Debug.LogWarningFormat("locale '{0}' already has a font assigned to it", locale);
        }
    }
        public JsonResult Replicar(int idLocalc, int[] ids)
        {
            TanoNEEntities ctx = new TanoNEEntities();

            Locales acopiar = ctx.Locales.FirstOrDefault(a => a.idLocal == idLocalc);

            foreach (int idlocal in ids)
            {
                List <ProductosLocales> todos = ctx.ProductosLocales.Where(a => a.localId == idlocal).ToList();
                foreach (ProductosLocales prod in todos)
                {
                    ctx.ProductosLocales.Remove(prod);
                }

                if (idlocal != idLocalc)
                {
                    List <ProductosLocales> productos = ctx.ProductosLocales.Where(a => a.localId == acopiar.idLocal).ToList();
                    foreach (ProductosLocales prod in productos)
                    {
                        ProductosLocales pl = new ProductosLocales();
                        pl.Locales   = ctx.Locales.FirstOrDefault(a => a.idLocal == idlocal);
                        pl.Productos = prod.Productos;
                        ctx.ProductosLocales.Add(pl);
                    }
                }
            }

            ctx.SaveChanges();


            return(Json(new { bien = true }, JsonRequestBehavior.DenyGet));
        }
Exemplo n.º 9
0
 public IEnumerable <Tuple <string, MemoryStream> > ReadFiles(string[] names, Locales locales = Locales.enUS)
 {
     for (var i = 0; i < names.Length; i++)
     {
         yield return(Tuple.Create(names[i], ReadFile(names[i], locales)));
     }
 }
Exemplo n.º 10
0
        /// <summary>
        /// Gets locale name.
        /// </summary>
        /// <param name="locale">The locale</param>
        /// <returns>The locale name.</returns>
        private static string GetLocaleName(Locales locale)
        {
            switch (locale)
            {
            case Locales.ArAe: return("ar-AE");

            case Locales.EnUs: return("en-US");

            case Locales.EsEs: return("es-ES");

            case Locales.FrFr: return("fr-FR");

            case Locales.PtPt: return("pt-PT");

            case Locales.NbNo: return("nb-NO");

            case Locales.PlPl: return("pl-PL");

            case Locales.RuRu: return("ru-RU");

            case Locales.ItIt: return("it-IT");

            case Locales.ZhCn: return("zh-CN");

            case Locales.ZhTw: return("zh-TW");

            case Locales.TrTr: return("tr-TR");

            default:
                throw new ArgumentOutOfRangeException("locale");
            }
        }
Exemplo n.º 11
0
 /// <summary>
 /// Gets values for all locales for the current part and returns them as a key => value dictionary
 /// </summary>
 /// <param name="key">Key of which to get values from all locales from</param>
 /// <returns></returns>
 public Dictionary <Locale, String> GetAllFor(String key)
 {
     return(Locales.GetAvailableLocales().ToDictionary(locale => locale, locale => Get(new Qualifier.WithKey(key)
     {
         Locale = locale
     })));
 }
        public void Constructor()
        {
            var dutchBelgium = new Locales(this.Session).DutchBelgium;

            new C1Builder(this.Session).WithC1AllorsString("c1A").WithC1C2One2One(new C2Builder(this.Session).WithC2AllorsString("c2A").Build()).Build();
            new C1Builder(this.Session).WithC1AllorsString("c1B").WithC1C2One2One(new C2Builder(this.Session).WithC2AllorsString("c2B").Build()).Build();

            this.Session.Derive(true);

            var aclMock = new Mock <IAccessControlList>();

            aclMock.Setup(acl => acl.CanRead(It.IsAny <PropertyType>())).Returns(true);
            var acls = new AccessControlListCache(null, (allorsObject, user) => aclMock.Object);

            var export = new CsvExport("Test");

            export.Columns.Add(new CsvExportPath(M.C1.C1AllorsString));
            export.Columns.Add(new CsvExportFunction <C1>("Function", (c1, aclFactory) => CsvExport.Escape("Hello " + c1.C1AllorsString)));

            var extent = this.Session.Extent(M.C1.ObjectType).AddSort(M.C1.C1AllorsString);
            var csv    = export.Write(extent, dutchBelgium, acls);

            Assert.AreEqual(
                @"""C1AllorsString"";""Function""
""c1A"";""Hello c1A""
""c1B"";""Hello c1B""".Replace("\r\n", "\n"),
                csv.Replace("\r\n", "\n"));
        }
        private void Buscar_Locales()
        {
            ComboBoxItem escoger_tipo   = (ComboBoxItem)(cbx_tipo.SelectedValue);
            ComboBoxItem escoger_estado = (ComboBoxItem)(cbx_estado.SelectedValue);

            string _id      = txt_codigo.Text.ToString().Trim();
            string _cod_int = txt_codigo.Text.ToString().Trim();
            string _des     = txt_nombre.Text.ToString().Trim();
            string _tipo    = (escoger_tipo != null) ? escoger_tipo.Uid.ToString().Trim() : ""; //escoger_tipo.Uid.ToString().Trim();
            string _super   = "";                                                               // txt_codigo.Text.ToString().Trim();
            string _arren   = txt_arrend.Text.ToString().Trim();
            string _ubic    = txt_distrit.Text.ToString().Trim();
            string _direc   = ""; // txt_codigo.Text.ToString().Trim();
            string _estado  = (escoger_estado != null) ? escoger_estado.Uid.ToString().Trim() : "";

            try
            {
                dt_grid = Locales.Buscar_Locales(_id, _cod_int, _des, _tipo, _super, _arren, _ubic, _direc, _estado);
                dtg_locales.ItemsSource = dt_grid.DefaultView;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error en Obtener Información de Locales." + ex.Message,
                                "Bata - Mensaje De Advertencia", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Constructor that takes 6 params.
        /// </summary>
        /// <param name="yourZendeskUrl">Will be formated to "https://yoursite.zendesk.com/api/v2"</param>
        /// <param name="user">Email adress of the user</param>
        /// <param name="password">LEAVE BLANK IF USING TOKEN</param>
        /// <param name="apiToken">Used if specified instead of the password</param>
        /// <param name="locale">Locale to use for Help Center requests. Defaults to "en-us" if no value is provided.</param>
        public ZendeskApi(string yourZendeskUrl,
                          string user,
                          string password,
                          string apiToken,
                          string locale,
                          string p_OAuthToken)
        {
            var formattedUrl = GetFormattedZendeskUrl(yourZendeskUrl).AbsoluteUri;

            Tickets             = new Tickets(formattedUrl, user, password, apiToken, p_OAuthToken);
            Attachments         = new Attachments(formattedUrl, user, password, apiToken, p_OAuthToken);
            Brands              = new Brands(formattedUrl, user, password, apiToken, p_OAuthToken);
            Views               = new Views(formattedUrl, user, password, apiToken, p_OAuthToken);
            Users               = new Users(formattedUrl, user, password, apiToken, p_OAuthToken);
            Requests            = new Requests.Requests(formattedUrl, user, password, apiToken, p_OAuthToken);
            Groups              = new Groups(formattedUrl, user, password, apiToken, p_OAuthToken);
            CustomAgentRoles    = new CustomAgentRoles(formattedUrl, user, password, apiToken, p_OAuthToken);
            Organizations       = new Organizations(formattedUrl, user, password, apiToken, p_OAuthToken);
            Search              = new Search(formattedUrl, user, password, apiToken, p_OAuthToken);
            Tags                = new Tags(formattedUrl, user, password, apiToken, p_OAuthToken);
            AccountsAndActivity = new AccountsAndActivity(formattedUrl, user, password, apiToken, p_OAuthToken);
            JobStatuses         = new JobStatuses(formattedUrl, user, password, apiToken, p_OAuthToken);
            Locales             = new Locales(formattedUrl, user, password, apiToken, p_OAuthToken);
            Macros              = new Macros(formattedUrl, user, password, apiToken, p_OAuthToken);
            SatisfactionRatings = new SatisfactionRatings(formattedUrl, user, password, apiToken, p_OAuthToken);
            SharingAgreements   = new SharingAgreements(formattedUrl, user, password, apiToken, p_OAuthToken);
            Triggers            = new Triggers(formattedUrl, user, password, apiToken, p_OAuthToken);
            HelpCenter          = new HelpCenterApi(formattedUrl, user, password, apiToken, locale, p_OAuthToken);
            Voice               = new Voice(formattedUrl, user, password, apiToken, p_OAuthToken);
            Schedules           = new Schedules(formattedUrl, user, password, apiToken, p_OAuthToken);
            Targets             = new Targets(formattedUrl, user, password, apiToken, p_OAuthToken);
            Automations         = new Automations(formattedUrl, user, password, apiToken, p_OAuthToken);

            ZendeskUrl = formattedUrl;
        }
        /// <summary>
        /// Add a Locale to allow support for a specific language.
        /// </summary>
        /// <param name="locale"></param>
        public void AddLocale(Locale locale)
        {
            bool isPsedudoLocale = locale is PseudoLocale;

            if (!isPsedudoLocale)
            {
                var foundLocale = GetLocale(locale.Identifier);
                if (foundLocale != null && !(foundLocale is PseudoLocale))
                {
                    Debug.LogWarning("Ignoring locale. A locale with the same Id has already been added: " + locale.Identifier);
                    return;
                }
            }

            // Insert PseudoLocale's at the end so they are not returned by GetLocale.
            if (isPsedudoLocale)
            {
                m_PseudoLocaleCount++;
                Locales.Add(locale);
            }
            else if (m_PseudoLocaleCount > 0)
            {
                Locales.Insert(0, locale);
            }
            else
            {
                Locales.Add(locale);
            }
        }
Exemplo n.º 16
0
        public static async ValueTask <DirectoryInfo> MoveDirectoryWithStatusAsync(DirectoryInfo directory, string destination)
        {
            var mainWindow = App.Current?.MainWindow;

            if (!(mainWindow is null))
            {
                // UI is loaded, display status window
                if (IsOnSameVolume(directory.FullName, destination))
                {
                    // On same volume, showing a dialog is not necessary
                    directory.MoveTo(destination);
                    return(directory);
                }
                else
                {
                    var op = directory.MoveToByCopyAsync(destination);

                    // Get localized strings
                    string title       = (string)App.Current !.Locales.GetResource("MovingLocation_Title");
                    string description = (string)App.Current !.Locales.GetResource("MovingFiles_Message");

                    // We don't need to evaluate this since we don't allow cancellation
                    await ProgressDialog.Show(title, description, op, mainWindow);

                    return(op.Result);
                }
            }
Exemplo n.º 17
0
        public static Uri GetUri(
            this Locales locale,
            string baseFileName)
        {
            const string Direcotry = @"resources\strings";

            var uri = default(Uri);

            var fileName = string.Format(baseFileName, locale.ToResourcesName());
            var file     = Path.Combine(DirectoryHelper.FindSubDirectory(Direcotry), fileName);

            if (!File.Exists(file))
            {
                // 言語リソースが存在しない場合はENを適用する
                fileName = string.Format(baseFileName, Locales.EN.ToText());
                file     = Path.Combine(DirectoryHelper.FindSubDirectory(Direcotry), fileName);
            }

            if (File.Exists(file))
            {
                uri = new Uri(file, UriKind.Absolute);
            }

            return(uri);
        }
Exemplo n.º 18
0
 public static void ReloadLocaleDictionary <T>(
     this T element,
     Locales locale) where T : FrameworkElement, ILocalizable =>
 element.Resources.MergedDictionaries.Add(new ResourceDictionary()
 {
     Source = locale.GetUri("Strings.SpeSpe.{0}.xaml")
 });
Exemplo n.º 19
0
        public L11n()
        {
            if (!App.Current.Properties.ContainsKey(nameof(_Locale)) || !Locales.IsValid(App.Current.Properties[nameof(_Locale)].ToString()))
            {
                var sysLocaleService = DependencyService.Get <IGetSystemLocale>();
                var sysLocale        = "";

                if (sysLocaleService != null)
                {
                    sysLocale = sysLocaleService.GetLocale();
                }

                if (Locales.IsValid(sysLocale))
                {
                    App.Current.Properties[nameof(_Locale)] = sysLocale;
                }
                else
                {
                    App.Current.Properties[nameof(_Locale)] = Locales.en;
                }
            }

            _Locale = App.Current.Properties[nameof(_Locale)].ToString();

            MinFreeSpaceInit();
        }
Exemplo n.º 20
0
        public IActionResult Pull([FromBody] Model model)
        {
            var acls     = new WorkspaceAccessControlLists(this.allors.Session.GetUser());
            var response = new PullResponseBuilder(acls, this.TreeService);

            var organisationContactRelationship = (OrganisationContactRelationship)this.allors.Session.Instantiate(model.Id);

            response.AddObject("organisationContactRelationship", organisationContactRelationship);

            response.AddObject("contact", organisationContactRelationship.Contact);

            var locales = new Locales(this.allors.Session).Extent();

            response.AddCollection("locales", locales);

            var genders = new GenderTypes(this.allors.Session).Extent();

            response.AddCollection("genders", genders);

            var salutations = new Salutations(this.allors.Session).Extent();

            response.AddCollection("salutations", salutations);

            var contactKinds = new OrganisationContactKinds(this.allors.Session).Extent();

            response.AddCollection("organisationContactKinds", contactKinds);

            return(this.Ok(response.Build()));
        }
Exemplo n.º 21
0
 protected BloomScenario(BloomScenario scenario)
     : base(scenario)
 {
     mName    = scenario.mName;
     mSuccess = scenario.mSuccess;
     mLocale  = scenario.mLocale;
 }
        // Reset Password

        private async Task ForceResetPassword()
        {
            try
            {
                var dialogResult = await _shell.ShowForceResetPasswordDialog(Locales.FirstOrDefault(), Locales.ToList());

                if (dialogResult == null)
                {
                    return;
                }

                var userId = dialogResult.ResetWay == ResetWayType.UserId ? EditViewModel.Id : null;
                var email  = dialogResult.ResetWay == ResetWayType.Email ? EditViewModel.Email : null;
                var phone  = dialogResult.ResetWay == ResetWayType.Phone
                    ? (long.TryParse(EditViewModel.Phone, out var phoneParsed)
                        ? phoneParsed
                        : (long?)null)
                    : null;

                var request = new ForceResetPasswordRequest(
                    email,
                    dialogResult.Locale,
                    phone,
                    userId
                    );
                await _domain0.Client.ForceResetUserPasswordAsync(request);
            }
            catch (Exception e)
            {
                await _shell.HandleException(e, "Failed to Force Reset Password");
            }
        }
Exemplo n.º 23
0
        private void LoadEndpoints(Locales locale)
        {
            using (WebClient wc = new WebClient())
            {
                var html = wc.DownloadString(BaseUrl);

                var mainSearch   = "<script src=\"assets/scripts/main.";
                var vendorSearch = "<script src=\"assets/scripts/vendor.";
                var endSearch    = ".js\"></script>";

                string FindBetween(string str, string start, string end)
                {
                    var startPos = str.IndexOf(start) + start.Length;
                    var endPos   = str.IndexOf(end, startPos);

                    return(str.Substring(startPos, endPos - startPos));
                }

                var mainUrl   = BaseUrl + "assets/scripts/main." + FindBetween(html, mainSearch, endSearch) + ".js";
                var vendorUrl = BaseUrl + "assets/scripts/vendor." + FindBetween(html, vendorSearch, endSearch) + ".js";

                var mainJs   = wc.DownloadString(mainUrl);
                var vendorJs = wc.DownloadString(vendorUrl);

                var json = ".json";

                OperatorsEndpoint = BaseUrl + "assets/data/operators." + FindBetween(mainJs, "assets/data/operators.", json) + json;
                WeaponsEndpoint   = BaseUrl + "assets/data/weapons." + FindBetween(mainJs, "assets/data/weapons.", json) + json;
                SeasonsEndpoint   = BaseUrl + "assets/data/seasons." + FindBetween(mainJs, "assets/data/seasons.", json) + json;

                LocaleEndpoint = BaseUrl + $"assets/locales/locale.{locale.ToStringValue()}." + FindBetween(vendorJs, $"assets/locales/locale.{locale.ToStringValue()}.", json) + json;
            }
        }
        // Change Email & Phone

        private async Task ForceChangePhone()
        {
            var changeData = await _shell.ShowForceChangeDialog(
                EditViewModel.Phone,
                "Phone",
                Locales.FirstOrDefault(),
                Locales.ToList());

            if (changeData != null)
            {
                try
                {
                    var newPhone = long.Parse(changeData.Input);
                    var request  = new ChangePhoneRequest(changeData.Locale, newPhone, EditViewModel.Id.Value);
                    await _domain0.Client.ForceChangePhoneAsync(request);

                    EditViewModel.Phone = changeData.Input;
                    Models.AddOrUpdate(EditModel);
                }
                catch (Exception e)
                {
                    await _shell.HandleException(e, "Failed to Change Phone");
                }
            }
        }
Exemplo n.º 25
0
        public JsonResult Asignar(int idLocal, int[] ids)
        {
            TanoNEEntities ctx = new TanoNEEntities();

            Locales local = ctx.Locales.FirstOrDefault(a => a.idLocal == idLocal);

            List <ProductosLocales> todos = ctx.ProductosLocales.Where(a => a.localId == local.idLocal).ToList();

            foreach (ProductosLocales prod in todos)
            {
                ctx.ProductosLocales.Remove(prod);
            }

            foreach (int idprod in ids)
            {
                ProductosLocales pl = new ProductosLocales();
                pl.Locales   = local;
                pl.Productos = ctx.Productos.FirstOrDefault(a => a.idProducto == idprod);
                ctx.ProductosLocales.Add(pl);
            }

            ctx.SaveChanges();


            return(Json(new { bien = true }, JsonRequestBehavior.DenyGet));
        }
Exemplo n.º 26
0
        /// <summary>
        /// Sets the value for a given qualifier
        /// </summary>
        /// <param name="qualifier">Qualifies the value to be set</param>
        /// <param name="value">The new value to override the old value with</param>
        public void Set(Qualifier.WithKey qualifier, String value)
        {
            var locale = qualifier.Locale ?? Locales.GetCurrentLocale();
            var part   = qualifier.Part ?? Parts.GetCurrentPart();

            Values.SetValue(new Qualifier.Unique(part, locale, qualifier.Key), value);
        }
Exemplo n.º 27
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            _activo_form = true;

            lbl_Titulo.Content = _tipo_ent + " - " + _cod_ent + " - " + _desc_ent;

            /******************************************/
            /*-------Listamos Tipos de Seguros -------*/
            /******************************************/
            DataTable lista_tseg = new DataTable();
            int       contar     = 0;

            lista_tseg = Locales.Lista_TipoSeguros();
            foreach (DataRow row in lista_tseg.Rows)
            {
                ComboBoxItem item = new ComboBoxItem();
                item.Uid     = row["Id"].ToString();
                item.Content = row["descripcion"].ToString();
                contar       = contar + 1;
                if (contar == 1)
                {
                    item.IsSelected = true;
                    sel_tipo        = row["Id"].ToString();
                }
                cbx_tipo.Items.Add(item);
            }

            Listar_Vigencias();

            Limpiar_Campos();

            _ok = false;
        }
Exemplo n.º 28
0
 protected BloomScenario(BloomScenario scenario)
     : base (scenario)
 {
     mName = scenario.mName;
     mSuccess = scenario.mSuccess;
     mLocale = scenario.mLocale;
 }
Exemplo n.º 29
0
        public ZendeskApi(string yourZendeskUrl, string user, string password)
        {
            Tickets             = new Tickets(yourZendeskUrl, user, password);
            Attachments         = new Attachments(yourZendeskUrl, user, password);
            Views               = new Views(yourZendeskUrl, user, password);
            Users               = new Users(yourZendeskUrl, user, password);
            Requests            = new Requests.Requests(yourZendeskUrl, user, password);
            Groups              = new Groups(yourZendeskUrl, user, password);
            CustomAgentRoles    = new CustomAgentRoles(yourZendeskUrl, user, password);
            Organizations       = new Organizations(yourZendeskUrl, user, password);
            Search              = new Search(yourZendeskUrl, user, password);
            Tags                = new Tags(yourZendeskUrl, user, password);
            Forums              = new Forums(yourZendeskUrl, user, password);
            Categories          = new Categories(yourZendeskUrl, user, password);
            Topics              = new Topics(yourZendeskUrl, user, password);
            AccountsAndActivity = new AccountsAndActivity(yourZendeskUrl, user, password);
            JobStatuses         = new JobStatuses(yourZendeskUrl, user, password);
            Locales             = new Locales(yourZendeskUrl, user, password);
            Macros              = new Macros(yourZendeskUrl, user, password);
            SatisfactionRatings = new SatisfactionRatings(yourZendeskUrl, user, password);
            SharingAgreements   = new SharingAgreements(yourZendeskUrl, user, password);
            Triggers            = new Triggers(yourZendeskUrl, user, password);

            ZendeskUrl = yourZendeskUrl;
        }
        public static NonUnifiedGoodBuilder WithSerialisedDefaults(this NonUnifiedGoodBuilder @this, Organisation internalOrganisation)
        {
            var faker = @this.Session.Faker();

            var dutchLocale = new Locales(@this.Session).DutchNetherlands;

            var nonSerialisedProductType = new ProductTypes(@this.Session).FindBy(M.ProductType.Name, "nonSerialisedProductType");

            if (nonSerialisedProductType == null)
            {
                var size = new SerialisedItemCharacteristicTypeBuilder(@this.Session)
                           .WithName("Size")
                           .WithLocalisedName(new LocalisedTextBuilder(@this.Session).WithText("Afmeting").WithLocale(dutchLocale).Build())
                           .Build();

                var weight = new SerialisedItemCharacteristicTypeBuilder(@this.Session)
                             .WithName("Weight")
                             .WithLocalisedName(new LocalisedTextBuilder(@this.Session).WithText("Gewicht").WithLocale(dutchLocale).Build())
                             .WithUnitOfMeasure(new UnitsOfMeasure(@this.Session).Kilogram)
                             .Build();

                nonSerialisedProductType = new ProductTypeBuilder(@this.Session)
                                           .WithName("serialisedProductType")
                                           .WithSerialisedItemCharacteristicType(size)
                                           .WithSerialisedItemCharacteristicType(weight)
                                           .Build();
            }

            @this.WithName(faker.Commerce.ProductName());
            @this.WithPart(new NonUnifiedPartBuilder(@this.Session).WithSerialisedDefaults(internalOrganisation, faker).Build());
            @this.WithDescription(faker.Lorem.Sentence());
            @this.WithComment(faker.Lorem.Sentence());
            @this.WithInternalComment(faker.Lorem.Sentence());
            @this.WithKeywords(faker.Lorem.Sentence());
            @this.WithUnitOfMeasure(new UnitsOfMeasure(@this.Session).Piece);
            @this.WithPrimaryPhoto(new MediaBuilder(@this.Session).WithInDataUri(faker.Image.DataUri(width: 200, height: 56)).Build());
            @this.WithPhoto(new MediaBuilder(@this.Session).WithInDataUri(faker.Image.DataUri(width: 200, height: 56)).Build());
            @this.WithPhoto(new MediaBuilder(@this.Session).WithInDataUri(faker.Image.DataUri(width: 200, height: 56)).Build());
            @this.WithPublicElectronicDocument(new MediaBuilder(@this.Session).WithInFileName("doc1.en.pdf").WithInData(faker.Random.Bytes(1000)).Build());
            @this.WithPrivateElectronicDocument(new MediaBuilder(@this.Session).WithInFileName("doc2.en.pdf").WithInData(faker.Random.Bytes(1000)).Build());
            @this.WithProductIdentification(new SkuIdentificationBuilder(@this.Session).WithDefaults().Build());
            @this.WithProductIdentification(new EanIdentificationBuilder(@this.Session).WithDefaults().Build());
            @this.WithProductIdentification(new ManufacturerIdentificationBuilder(@this.Session).WithDefaults().Build());
            @this.WithVatRegime(faker.Random.ListItem(@this.Session.Extent <VatRegime>()));

            foreach (Locale additionalLocale in @this.Session.GetSingleton().AdditionalLocales)
            {
                @this.WithLocalisedName(new LocalisedTextBuilder(@this.Session).WithText(faker.Lorem.Word()).WithLocale(additionalLocale).Build());
                @this.WithLocalisedDescription(new LocalisedTextBuilder(@this.Session).WithText(faker.Lorem.Sentence()).WithLocale(additionalLocale).Build());
                @this.WithLocalisedComment(new LocalisedTextBuilder(@this.Session).WithText(faker.Lorem.Sentence()).WithLocale(additionalLocale).Build());
                @this.WithLocalisedKeyword(new LocalisedTextBuilder(@this.Session).WithText(faker.Lorem.Sentence()).WithLocale(additionalLocale).Build());

                var localisedDocument = new MediaBuilder(@this.Session).WithInFileName($"doc1.{additionalLocale.Country.IsoCode}.pdf").WithInData(faker.Random.Bytes(1000)).Build();
                @this.WithPublicLocalisedElectronicDocument(new LocalisedMediaBuilder(@this.Session).WithMedia(localisedDocument).WithLocale(additionalLocale).Build());
                @this.WithPrivateLocalisedElectronicDocument(new LocalisedMediaBuilder(@this.Session).WithMedia(localisedDocument).WithLocale(additionalLocale).Build());
            }

            return(@this);
        }
Exemplo n.º 31
0
 private void ObjectInvariant()
 {
     Contract.Invariant(!string.IsNullOrEmpty(AccessToken));
     Contract.Invariant(DefaultLocale != null);
     Contract.Invariant(Locales != null && Locales.Any());
     Contract.Invariant(InactivitySeconds >= SdkInfo.MinInactivitySeconds && InactivitySeconds <= SdkInfo.MaxInactivitySeconds);
     Contract.Invariant(MaxRecoveryTime >= SdkInfo.MinRecoveryExecutionInSeconds);
 }
Exemplo n.º 32
0
 /// <summary>
 /// Parses a locales enum and returns corresponding CultureInfo.
 /// </summary>
 /// <param name="locale">Locales enum</param>
 /// <returns>Parsed CultureInfo, defaults to 'en-US' if locale not found.</returns>
 public static CultureInfo ParseCultureInfo(Locales? locale)
 {
     switch (locale)
     {
         case Locales.SV_SE:
             return new CultureInfo("sv-SE");
         case Locales.EN_US:
         default:
             return new CultureInfo("en-US");
     }
 }
        /// <summary>
        /// Gets localized strings in json representation.
        /// </summary>
        /// <param name="locale">The locale. Supported locales are <see cref="Locales.EnUs"/>, <see cref="Locales.EsEs"/>, 
        /// <see cref="Locales.PtPt"/>, <see cref="Locales.NbNo"/>, <see cref="Locales.PlPl"/>, <see cref="Locales.RuRu"/>,
        /// <see cref="Locales.ArAe"/>, <see cref="Locales.ItIt"/>, <see cref="Locales.ZhCn"/>, <see cref="Locales.ZhTw"/>,
        /// <see cref="Locales.TrTr"/>, <see cref="Locales.FrFr"/>.
        /// </param>
        /// <returns>The localized strings in json representation.</returns>
        public static IHtmlString GetLocalizedStringsJson(Locales locale = Locales.EnUs)
        {
            var resourceName = string.Format(ResourceNameTemplate, GetLocaleName(locale));

            using (Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
            {
                if (resourceStream == null)
                    throw new NullReferenceException(string.Format("Resource {0} not found.", resourceName));

                using (StreamReader reader = new StreamReader(resourceStream, Encoding.UTF8))
                    return new HtmlString(reader.ReadToEnd());
            }
        }
Exemplo n.º 34
0
        /// <summary>
        /// Http GET to change the locale. 
        /// Defaults to EN_US.
        /// </summary>
        /// <param name="locale">Locales enum.</param>
        /// <returns>Redirects to Home.</returns>
        public ActionResult ChangeLocale(Locales? locale)
        {
            string localeName = LocalesExtension.ParseCultureInfo(locale).Name;

            HttpCookie cookie = Request.Cookies["_locale"];
            if (cookie != null)
            {
                cookie.Value = localeName;   // update cookie value
            }
            else
            {
                cookie = new HttpCookie("_locale");
                cookie.Value = localeName;
                cookie.Expires = DateTime.Now.AddYears(1);
            }
            Response.Cookies.Add(cookie);

            return Redirect(Request.UrlReferrer.ToString());
        }
 /// <summary>
 /// Gets locale name.
 /// </summary>
 /// <param name="locale">The locale</param>
 /// <returns>The locale name.</returns>
 private static string GetLocaleName(Locales locale)
 {
     switch (locale)
     {
         case Locales.ArAe: return "ar-AE";
         case Locales.EnUs: return "en-US";
         case Locales.EsEs: return "es-ES";
         case Locales.FrFr: return "fr-FR";
         case Locales.PtPt: return "pt-PT";
         case Locales.NbNo: return "nb-NO";
         case Locales.PlPl: return "pl-PL";
         case Locales.RuRu: return "ru-RU";
         case Locales.ItIt: return "it-IT";
         case Locales.ZhCn: return "zh-CN";
         case Locales.ZhTw: return "zh-TW";
         case Locales.TrTr: return "tr-TR";
         default:
             throw new ArgumentOutOfRangeException("locale");
     }
 }
Exemplo n.º 36
0
 public IEnumerable<Tuple<string, MemoryStream>> ReadFiles(string[] names, Locales locales = Locales.enUS)
 {
     for (var i = 0; i < names.Length; i++)
         yield return Tuple.Create(names[i], ReadFile(names[i], locales));
 }
Exemplo n.º 37
0
 /// <summary>
 /// Add card to collection from JSON (string) parameters.
 /// Adds or updates a card in your collection, based on data passed as parameters.
 /// It is intended to be used to load data from JSON files and store it as cards/locales in your collection.
 /// </summary>
 /// <param name="card">JSON card data for card (mainly strings)</param>
 /// <param name="set">Set which card is related to</param>
 /// <param name="locale">Locale of the texts from the card</param>
 /// <param name="filename">File name of the picture used as background for card</param>
 /// <param name="race">Localized text for card race, if necessary</param>
 /// <param name="useDefault">Use default image if no filename is given</param>
 public void Add(CardJSON card, CardSet set, Locales locale, string filename, string race = "", bool useDefault = true)
 {
     // If card already stored, add new texts only if necessary
     CardItem item;
     if (Cards.TryGetValue(card.Id, out item))
     {
         // If locale is not included, add it
         if (!item.hasLocale(locale))
         {
             item.addLocale(locale, card.Name, card.Text, race);
         }
     }
     else
     // Add new card
     {
         // Take JSON values
         var _type   = General.getCustomCardType(card.Type);
         var _class  = General.getCardClass(card.PlayerClass);
         var _race   = General.getCardRace(card.Race);
         var _rarity = General.getCardRarity(card.Rarity);
         // Create card from them
         item = new CardItem(card.Id, card.Cost, card.Attack, card.Health, card.Durability, _type, _class, _race, set, _rarity, filename, useDefault);
         // Add localized texts
         item.addLocale(locale, card.Name, card.Text, race);
         // Add it to collection
         Cards.Add(card.Id, item);
     }
     // If locale not included in locales, include it
     if (!Languages.ContainsKey(locale))
     {
         Languages.Add(locale, General.getShortLocale(locale));
     }
 }
Exemplo n.º 38
0
 /// <summary>
 /// Assign a default locale for all card.
 /// This can be used to populate data with all text fields from cards in the same locale, in a fast and simple way
 /// </summary>
 /// <param name="locale">new Locale to be used</param>
 public void SetLocale(Locales locale)
 {
     // go for each card in collection and sets the default locale.
     foreach (KeyValuePair<string, CardItem> card in Cards)
     {
         // With this, when you take Name, Text or Race, they will be returned in this locale.
         card.Value.setLocale(locale);
     }
 }
Exemplo n.º 39
0
        public ConcurrentDictionary<ulong, MemoryStream> ReadFiles(byte[] signature, Locales locales = Locales.enUS)
        {
            var files = new ConcurrentDictionary<ulong, MemoryStream>();

            foreach (var entry in rootFile.Entries)
            {
                var rootEntries = rootFile[entry.Key];

                for (var i = 0; i < rootEntries.Length; i++)
                {
                    if ((rootEntries[i].Locales & locales) == locales)
                    {
                        var encodingEntry = encodingFile[rootEntries[i].MD5];

                        if (encodingEntry.Size != 0 && encodingEntry.Keys.Length > 0)
                        {
                            for (var j = 0; j < 0x10; j++)
                            {
                                IndexEntry idxEntry = default(IndexEntry);

                                foreach (var k in encodingEntry.Keys)
                                {
                                    if ((idxEntry = idxFiles[j][k.Slice(0, 9)]).Size != 0)
                                    {
                                        var dataFile = dataFiles[idxEntry.Index];

                                        if (dataFile == null)
                                            throw new InvalidOperationException("Invalid data file.");

                                        var sigBuffer = new byte[signature.Length];
                                        var stream = DataFile.LoadBLTEEntry(idxEntry, dataFile.readStream);

                                        stream?.Read(sigBuffer, 0, sigBuffer.Length);

                                        if (sigBuffer.Compare(signature))
                                            files.TryAdd(entry.Key, stream);
                                    }
                                }

                                if (idxEntry.Size != 0)
                                    break;
                            }

                            for (var j = 0x10; j < idxFiles.Count; j++)
                            {
                                IndexEntry idxEntry = default(IndexEntry);

                                foreach (var k in encodingEntry.Keys)
                                {
                                    if ((idxEntry = idxFiles[j][k]).Size != 0)
                                    {
                                        var sigBuffer = new byte[signature.Length];
                                        var stream = DataFile.LoadBLTEEntry(idxEntry, cdnConfig.DownloadFile(indexFiles[idxEntry.Index], idxEntry));

                                        stream?.Read(sigBuffer, 0, sigBuffer.Length);

                                        if (sigBuffer.Compare(signature))
                                            files.TryAdd(entry.Key, stream);
                                    }
                                }

                                if (idxEntry.Size != 0)
                                    break;
                            }
                        }
                    }
                }
            }

            return files;
        }
Exemplo n.º 40
0
        /// <summary>
        /// Constructor for batch process window.
        /// </summary>
        /// <param name="_lang">Which locale will be used in control texts</param>
        public BatchForm(Locales _lang = Locales.enUS)
        {
            // Do WinForms magic
            InitializeComponent();
            // Initialize languages
            ci  = CultureInfo.CreateSpecificCulture(General.getCultureLocale(_lang));
            res = new ResourceManager("HSCardGenerator.Resources.Texts.Strings", typeof(CustomForm).Assembly);
            // Stop painting
            SuspendLayout();
            // Get main font
            var font = new Font(Fonts.BelweFamily, 9f, FontStyle.Regular);
            // Assign text/button labels
            btImageFolder.Text       = res.GetString("strImageFolder", ci);
            btOpenJSON.Text          = res.GetString("strOpenJSONFile", ci);
            btDestinationFolder.Text = res.GetString("strChooseDestination", ci);
            btBatchProcess.Text      = res.GetString("strCreateCards", ci);
            btBatchCancel.Text       = res.GetString("strCancelProcess", ci);
            lblOutputSize.Text       = res.GetString("strOutputSize", ci);
            lblNoImage.Text          = res.GetString("strNoImage", ci);
            rbCustom.Text            = res.GetString("strCustom", ci);
            // Populate options for no image combobox
            var txt = res.GetString("strNoImageOptions", ci).Split('-');
            cbNoImage.Items.Clear();
            foreach (var str in txt)
            {
                cbNoImage.Items.Add(str);
            }
            // Create custom combobox for locales with flags
            cbLocale.Size     = new Size(126, 30);
            cbLocale.Location = new Point(262, 226);
            cbLocale.Parent   = batchPanel;
            // Create custom progress bar to show text properly
            progressBar.Size     = new Size(220, 24);
            progressBar.Location = new Point(212, 196);
            progressBar.Parent   = batchPanel;
            progressBar.font     = font;
            // Assign font and pointer cursor to buttons
            Button[] btn = new[] { btOpenJSON, btImageFolder, btDestinationFolder, btBatchProcess, btBatchCancel, btBackCollection };
            foreach (var button in btn)
            {
                button.UseCompatibleTextRendering = true;
                button.Font   = font;
                button.Cursor = cursorPointer;

                button.MouseDown += (s, e) => { if (e.Button == MouseButtons.Left) { button.Cursor = cursorPointerDown; } };
                button.MouseUp   += (s, e) => { if (e.Button == MouseButtons.Left) { button.Cursor = cursorPointer; } };
            }
            // Assign pointer cursor to comboboxes
            ComboBox[] cbx = new[] { cbCollection, cbLocale, cbNoImage };
            foreach (var combobox in cbx)
            {
                combobox.Cursor = cursorPointer;

                combobox.MouseDown += (s, e) => { if (e.Button == MouseButtons.Left) { combobox.Cursor = cursorPointerDown; } };
                combobox.MouseUp   += (s, e) => { if (e.Button == MouseButtons.Left) { combobox.Cursor = cursorPointer; } };
            }
            // Assign hand cursor to panels to move form
            Panel[] pnl = new[] { batchPanel, sizePanel };
            foreach (var panel in pnl)
            {
                panel.Cursor     = cursorGrabOff;
                panel.MouseDown += moveFormOnMouseDown;
            }
            // Assign cursor and movement to progressbar
            progressBar.Cursor = cursorGrabOff;
            progressBar.MouseDown += moveFormOnMouseDown;
            // Assign font and cursor to labels
            Label[] lbl = new[] { lblOutputSize, lblX, lblImageFolder, lblJSONFile, lblDestinationFolder, lblNoImage };
            foreach (var label in lbl)
            {
                label.UseCompatibleTextRendering = true;
                label.Font       = font;
                label.TextAlign  = ContentAlignment.MiddleLeft;
                label.MouseDown += moveFormOnMouseDown;
            }
            // Textboxes will only accept numbers
            TextBox[] txtbx = new[] { txtHeight, txtWidth };
            foreach (var textbox in txtbx)
            {
                textbox.KeyPress += (s, e) =>
                {
                    e.Handled = !(char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar) || char.IsPunctuation(e.KeyChar));
                };
            }
            // Assign pointers for radiobuttons
            RadioButton[] rbt = new[] { rbZoom025, rbZoom050, rbZoom075, rbZoom100, rbZoom150, rbZoom200, rbCustom };
            foreach (var radiobutton in rbt)
            {
                // Set cursor and fonts
                radiobutton.UseCompatibleTextRendering = true;
                radiobutton.Cursor = cursorPointer;
                radiobutton.Font   = font;
                // Set events to animate button on click
                radiobutton.MouseDown += (s, e) => { if (e.Button == MouseButtons.Left) { radiobutton.Cursor = cursorPointerDown; } };
                radiobutton.MouseUp   += (s, e) => { if (e.Button == MouseButtons.Left) { radiobutton.Cursor = cursorPointer; } };
                // Make them a radiogroup and do stuff when clicking
                radiobutton.CheckedChanged += (s, e) =>
                {
                    // Check if custom controls must be shown
                    var customVisible = (rbCustom.Checked);
                    // Assign visibility
                    txtWidth.Visible  = customVisible;
                    lblX.Visible      = customVisible;
                    txtHeight.Visible = customVisible;
                };
            }
            // Assign pointers for paintboxes to move form
            PictureBox[] pbx = new[] { pbImage, pbDestination, pbJSON, pbPreview, pbWaitingAnim };
            foreach (var picturebox in pbx)
            {
                picturebox.Cursor     = cursorGrabOff;
                picturebox.MouseDown += moveFormOnMouseDown;
            }
            // Set UI status: first step of process -> ask for a picture folder to take card images from.
            setBatchUIStatus(BatchUIStatus.AskForPictureFolder);
            // Assign events for comboboxes: first, collection
            cbCollection.SelectedIndexChanged += (s, e) =>
            {
                if ((cbCollection.SelectedItem != null) && !feedingComboBoxes)
                {
                    // Take selected card
                    var cardId = ((KeyValuePair<string, string>)cbCollection.SelectedItem).Key;
                    CardItem card;
                    // Show card thumbnail
                    if (loadedCollection.Cards.TryGetValue(cardId, out card))
                    {
                        pbPreview.Image = card.Picture(General.getLocaleFromString((string)cbLocale.SelectedItem), pbPreview.Width, pbPreview.Height);
                    }
                }
            };
            // Then, locales
            cbLocale.SelectedIndexChanged += (s, e) =>
            {
                if ((cbCollection.SelectedItem != null) && !feedingComboBoxes)
                {
                    // Take selected card
                    var cardId = ((KeyValuePair<string, string>)cbCollection.SelectedItem).Key;
                    CardItem card;
                    // Show card thumbnail
                    if (loadedCollection.Cards.TryGetValue(cardId, out card))
                    {
                        pbPreview.Image = card.Picture(General.getLocaleFromString((string)cbLocale.SelectedItem), pbPreview.Width, pbPreview.Height);
                    }
                }
            };
            // Handler to manage event for Image Folder Selection button
            btImageFolder.Click += (s, e) =>
            {
                // User can't create new folders (only open existing ones)
                folderBrowserDialog.ShowNewFolderButton = false;
                // Give user a dialog to choose a folder
                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                {
                    // Store selected path
                    sourcePath = folderBrowserDialog.SelectedPath;
                    // Status for picture
                    showStatusPicture(pbImage, 1);
                    // Show image folder info
                    lblImageFolder.Text    = sourcePath;
                    lblImageFolder.Visible = true;
                    // Go to next step
                    setBatchUIStatus(BatchUIStatus.AskForJSONFile);
                }
            };
            // Handler to manage event for Open JSON File button (output to "console")
            btOpenJSON.Click += (s, e) =>
            {
                // Check if worker working :D
                if (!bgJSONWorker.IsBusy)
                {
                    // Ask for JSON file
                    openFileDialog.DefaultExt = Config.extensionJSON;
                    openFileDialog.Filter     = Config.filterJSON;
                    // Open it and do magic if all is fine
                    if (openFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        // Store value
                        jsonFilename = openFileDialog.FileName;
                        // Hide UI
                        setBatchUIStatus(BatchUIStatus.LoadingJSONFile);
                        // Show status
                        txtConsole.Text += string.Format("> {0}\n", res.GetString("strJSONProcess", ci));
                        var useDefault = (cbNoImage.SelectedIndex == 1);
                        var createCard = (cbNoImage.SelectedIndex != 0);
                        // Pass parameters as objects to bg task
                        object[] bgParameters = new object[] { loadedCollection, useDefault, createCard };
                        bgJSONWorker.RunWorkerAsync(bgParameters);
                    }
                }
            };
            // Handler to manage event for Destination Folder Selection button
            btDestinationFolder.Click += (s, e) =>
            {
                // User can create new folders
                folderBrowserDialog.ShowNewFolderButton = true;
                // Show dialog and check response
                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                {
                    // Store path
                    destinationPath = folderBrowserDialog.SelectedPath;
                    // Show OK status
                    showStatusPicture(pbDestination, 1);
                    // Go to next stage
                    setBatchUIStatus(BatchUIStatus.WaitingForAction);
                    // Show destination folder
                    lblDestinationFolder.Text = destinationPath;
                    lblDestinationFolder.Visible = true;
                }
            };
            // Handler to manage event for Batch Process button
            btBatchProcess.Click += (s, e) =>
            {
                // Check if worker working :D
                if (!bgBatchWorker.IsBusy)
                {
                    // Hide UI
                    btBatchProcess.Enabled   = false;
                    sizePanel.Visible        = false;
                    btBackCollection.Visible = false;
                    // Get zoom value
                    var zoom      = 0.0f;
                    var outWidth  = Config.cardWidth;
                    var outHeight = Config.cardHeight;
                    // based on which radiobutton is checked
                    if (rbZoom025.Checked) zoom = 0.25f;
                    else if (rbZoom050.Checked) zoom = 0.50f;
                    else if (rbZoom075.Checked) zoom = 0.75f;
                    else if (rbZoom100.Checked) zoom = 1.0f;
                    else if (rbZoom150.Checked) zoom = 1.5f;
                    else if (rbZoom200.Checked) zoom = 2.0f;
                    // If custom is checked, take dimensions only if all are fine
                    if (zoom == 0.0f)
                    {
                        if ((txtWidth.Text.Length > 0) && (txtHeight.Text.Length > 0))
                        {
                            outWidth = Convert.ToInt32(txtWidth.Text);
                            outHeight = Convert.ToInt32(txtHeight.Text);
                        }
                    }
                    // Zoom selected? apply zoom scale for main card size
                    else
                    {
                        outWidth = (int)(Config.cardWidth * zoom);
                        outHeight = (int)(Config.cardHeight * zoom);
                    }
                    // Show animations
                    pbWaitingAnim.Visible = true;
                    progressBar.Visible   = true;
                    // Pass parameters as objects to bg task
                    object[] bgParameters = new object[] { loadedCollection, outWidth, outHeight };
                    bgBatchWorker.RunWorkerAsync(bgParameters);
                }
            };
            // Handler to manage event for Cancel Batch Process button
            btBatchCancel.Click += (s, e) =>
            {
                // Doing batch process? cancel
                if (bgBatchWorker.IsBusy)
                {
                    bgBatchWorker.CancelAsync();
                }
                // Reading JSON file? cance
                else if (bgJSONWorker.IsBusy)
                {
                    bgJSONWorker.CancelAsync();
                }
                // Otherwise, go to first step of batch process
                else
                {
                    setBatchUIStatus(BatchUIStatus.AskForPictureFolder);
                }
            };
            // Handler to read JSON data from file in other thread
            bgJSONWorker.DoWork += (s, e) =>
            {
                // Get vars from method parameters
                var sendingWorker = (BackgroundWorker)s;
                var arrObjects    = (object[])e.Argument;
                var aCollection   = (CardItemCollection)arrObjects[0];
                var useDefault    = (bool)arrObjects[1];
                var createCard    = (bool)arrObjects[2];
                // Init internal vars
                int step;     // Cards processed so far
                int percent;  // Percent done
                int socent;   // aux var
                int ncards;   // Cards to process
                // To do stuff according to portrait existence or not
                string portrait;
                bool fileExists;
                // Read all JSON text from file
                var json = File.ReadAllText(jsonFilename);
                // Is a "AllSets.xxXX.json" file? (xxXX-Locale)
                var locale = General.getLocaleFromFilename(jsonFilename);
                if (locale != Locales.unkn)
                {
                    // Get cultureinfo for file locale
                    var cinfo = CultureInfo.CreateSpecificCulture(General.getCultureLocale(locale));
                    // Parse cards file
                    var dict  = JsonConvert.DeserializeObject<Dictionary<string, CardJSON[]>>(json);
                    // Get num. cards to process
                    ncards   = 0;
                    step     = 0;
                    percent  = 0;
                    foreach (KeyValuePair<string, CardJSON[]> kvp in dict)
                    {
                        // Only take into account valid sets
                        if (General.isValidCardSet(General.getCardSet(kvp.Key)))
                        {
                            ncards += kvp.Value.Length;
                        }
                    }
                    bgJSONWorker.ReportProgress(0, string.Format("{0}/{1}", step, ncards));
                    // File as array of sets with cards
                    foreach (KeyValuePair<string, CardJSON[]> kvp in dict)
                    {
                        // If user didn't cancel process
                        if (!sendingWorker.CancellationPending)
                        {
                            // store actual set to speed up things
                            var set = General.getCardSet(kvp.Key);
                            // Got a valid set?
                            if (General.isValidCardSet(set))
                            {
                                // Process all its cards
                                foreach (CardJSON card in kvp.Value)
                                {
                                    // If user didn't cancel process
                                    if (!sendingWorker.CancellationPending)
                                    {
                                        // Card is valid (minion, spell, weapon) and collectible?
                                        if ((General.isValidCardType(General.getMainCardType(card.Type))) && (card.Collectible))
                                        {
                                            // Get card portrait path
                                            portrait   = Path.Combine(sourcePath, card.Id + ".png");
                                            fileExists = File.Exists(portrait);
                                            // If it does not exist, empty filename
                                            if (!fileExists)
                                            {
                                                portrait = "";
                                            }
                                            if (fileExists || createCard)
                                            {
                                                // Take localized race value from JSON
                                                var race = (General.getCardRace(card.Race) != CardRace.None) ? res.GetString("str" + card.Race, cinfo) : "";
                                                // Create card from JSON data
                                                aCollection.Add(card, set, locale, portrait, race, useDefault);
                                            }
                                        }
                                        // Update status
                                        step++;
                                        socent = (int)Math.Floor((double)(step * 100 / ncards));
                                        if (socent > percent)
                                        {
                                            percent = socent;
                                            bgJSONWorker.ReportProgress(percent, string.Format("{0}/{1}", step, ncards));
                                        }
                                    }
                                    else
                                    {
                                        // cancel!
                                        e.Cancel = true;
                                        break;
                                    }
                                }
                            }
                        }
                        else
                        {
                            // cancel!
                            e.Cancel = true;
                            break;
                        }
                    }
                }
                // it must be a "AllSetsAllLanguages.json"
                else
                {
                    // Process all locales: parse full JSON file
                    var dict = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, CardJSON[]>>>(json);
                    // This file will have an array of locales and, for each one, the same as the previous case
                    foreach (KeyValuePair<string, Dictionary<string, CardJSON[]>> local in dict)
                    {
                        // Did user cancel process?
                        if (!sendingWorker.CancellationPending)
                        {
                            // Take locale value now to speed up things
                            locale    = General.getLocaleFromString(local.Key);
                            var cinfo = CultureInfo.CreateSpecificCulture(General.getCultureLocale(locale));
                            // Info
                            txtConsole.Invoke(new MethodInvoker(() => txtConsole.Text += string.Format("> {0} '{1}'...\n", res.GetString("strProcessingLocale", ci), local.Key)));
                            // Get num. cards to process
                            ncards  = 0;
                            step    = 0;
                            percent = 0;
                            bgJSONWorker.ReportProgress(0, string.Format("{0}/{1}", step, ncards));
                            foreach (KeyValuePair<string, CardJSON[]> cards in local.Value)
                            {
                                if (General.isValidCardSet(General.getCardSet(cards.Key)))
                                    ncards += cards.Value.Length;
                            }
                            // For each set of cards...
                            foreach (KeyValuePair<string, CardJSON[]> cards in local.Value)
                            {
                                // store actual set to speed up things
                                var set = General.getCardSet(cards.Key);
                                // Valid set found? process its cards
                                if (General.isValidCardSet(set))
                                {
                                    // For each card...
                                    foreach (CardJSON card in cards.Value)
                                    {
                                        // Did user cancel process?
                                        if (!sendingWorker.CancellationPending)
                                        {
                                            if (General.isValidCardType(General.getMainCardType(card.Type)) && (card.Collectible))
                                            {
                                                // Get card portrait path
                                                portrait = Path.Combine(sourcePath, card.Id + ".png");
                                                fileExists = File.Exists(portrait);
                                                // If it does not exist, empty filename
                                                if (!fileExists)
                                                {
                                                    portrait = "";
                                                }
                                                if (fileExists || createCard)
                                                {
                                                    // Take localized race value from JSON
                                                    var race = (General.getCardRace(card.Race) != CardRace.None) ? res.GetString("str" + card.Race, cinfo) : "";
                                                    // Create card from JSON data
                                                    aCollection.Add(card, set, locale, portrait, race, useDefault);
                                                }
                                            }
                                            // Update status
                                            step++;
                                            socent = (int)Math.Floor((double)(step * 100 / ncards));
                                            if (socent > percent)
                                            {
                                                percent = socent;
                                                bgJSONWorker.ReportProgress(percent, string.Format("{0}/{1}", step, ncards));
                                            }
                                        }
                                        else
                                        {
                                            // cancel!
                                            e.Cancel = true;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            // cancel!
                            e.Cancel = true;
                            break;
                        }
                    }
                }
                // Process finished
                e.Result = string.Format("> {0}\n", res.GetString("strJSONParseSuccess", ci));
            };
            // Handler when finished reading data
            bgJSONWorker.RunWorkerCompleted += (s, e) =>
            {
                // Check if the worker has been canceled or if an error occurred
                if ((!e.Cancelled) && (e.Error == null))
                {
                    // Show return status in console
                    txtConsole.Text += (string)e.Result;
                    // Check if data was readed
                    var cardExists = (loadedCollection.Cards.Count > 0);
                    // Manage collections
                    if (cardExists)
                    {
                        // Populate locales combobox
                        feedingComboBoxes = true;
                        cbLocale.Items.Clear();
                        foreach (var locale in loadedCollection.Languages)
                        {
                            cbLocale.Items.Add((string)locale.Value);
                        }
                        cbLocale.SelectedIndex = 0;
                        // Populate collection combobox with card references, showing name
                        foreach (var kvp in loadedCollection.Cards)
                        {
                            cbCollection.Items.Add(new KeyValuePair<string, string>(kvp.Key, kvp.Value.Name));
                        }
                        cbCollection.ValueMember   = "Key";
                        cbCollection.DisplayMember = "Value";
                        feedingComboBoxes = false;
                        cbCollection.SelectedIndex = 0;
                        // Show JSON file
                        lblJSONFile.Text    = jsonFilename;
                        lblJSONFile.Visible = true;
                        // Set icon to "ok"
                        showStatusPicture(pbJSON, 1);
                        // Enable next step
                        setBatchUIStatus(BatchUIStatus.AskForDestinationFolder);
                    }
                    // Show or hide comboboxes based on result
                    ComboBox[] cbxs = new[] { cbCollection, cbLocale };
                    foreach (var combobox in cbxs)
                    {
                        combobox.Visible = cardExists;
                        combobox.Enabled = cardExists;
                    }
                    // Show info about loaded data
                    txtConsole.Text += string.Format(">" + res.GetString("strStatus", ci) + "\n", loadedCollection.Cards.Count, loadedCollection.Languages.Count); // "> Loaded {0} cards with {1} locales\n"
                }
                else if (e.Cancelled)
                {
                    // User cancelled process? warn
                    txtConsole.Text += string.Format("! {0}\n", res.GetString("strUserCancel", ci));
                    // Clear all
                    loadedCollection.Clear();
                    setBatchUIStatus(BatchUIStatus.AskForJSONFile);
                }
                else
                {
                    // Unknown error? warn
                    txtConsole.Text += string.Format("! {0}\n", res.GetString("strUnknownError", ci));
                    loadedCollection.Clear();
                    setBatchUIStatus(BatchUIStatus.AskForJSONFile);
                }
                // Restore UI status after completion
                pbWaitingAnim.Visible    = false;
                progressBar.Visible      = false;
                btBackCollection.Visible = true;
            };
            // Handler to update progress bar
            bgJSONWorker.ProgressChanged += (s, e) =>
            {
                // Use text from handler (card progress)
                progressBar.text = (string)e.UserState;
                // Store progress (percent value)
                progressBar.Value = e.ProgressPercentage;
            };
            // Handler to write card pictures to disk
            bgBatchWorker.DoWork += (s, e) =>
            {
                var sendingWorker = (BackgroundWorker)s;
                var arrObjects    = (object[])e.Argument;

                var aCollection = (CardItemCollection)arrObjects[0];
                var width       = (int)arrObjects[1];
                var height      = (int)arrObjects[2];

                // Do main stuff from here
                var directoryInfo     = new DirectoryInfo(sourcePath);
                var targetPath        = "";
                var destinationFile   = "";
                int ncards            = aCollection.Cards.Count;
                int percent;
                int socent;
                int step;
                // First of all, we'll create all directories for locales. They will be needed later, so... ^^
                foreach (var loc in aCollection.Languages)
                {
                    // Get directory path
                    targetPath = Path.Combine(destinationPath, loc.Value);
                    // If doesn't exist, create it
                    if (!Directory.Exists(targetPath))
                    {
                        Directory.CreateDirectory(targetPath);
                    }
                }
                // Reset progress counter
                step    = 0;
                percent = 0;
                // Report progress
                txtConsole.Invoke(new MethodInvoker(() => txtConsole.Text += string.Format("> {0}\n", res.GetString("strJSONProcess", ci))));
                bgBatchWorker.ReportProgress(0, string.Format("{0}/{1}", step, ncards));
                // Process all cards
                foreach (var card in aCollection.Cards)
                {
                    // Check if not cancelled
                    if (!sendingWorker.CancellationPending)
                    {
                        // Process all locales
                        foreach (var loc in aCollection.Languages)
                        {
                            // If not cancelled, process locale
                            if (!sendingWorker.CancellationPending)
                            {
                                // Get file path
                                destinationFile = Path.Combine(destinationPath, loc.Value, card.Key + ".png");
                                // Get localized card
                                var cardBitmap = card.Value.Picture(loc.Key, width, height);
                                // Save to file if exists
                                if (cardBitmap != null)
                                {
                                    cardBitmap.Save(destinationFile);
                                    // Free resources
                                    cardBitmap.Dispose();
                                }
                            }
                        }
                        // Update status
                        step++;
                        socent = (int)Math.Floor((double)(step * 100 / ncards));
                        if (socent > percent)
                        {
                            percent = socent;
                            bgBatchWorker.ReportProgress(percent, string.Format("{0}/{1}", step, ncards));
                        }
                    }
                    else
                    {
                        // User cancelled
                        e.Cancel = true;
                        break;
                    }
                }
                // Process finished
                e.Result = string.Format("> {0}\n", res.GetString("strCollectionSuccess", ci));
            };
            // Handler when finished writing card pictures
            bgBatchWorker.RunWorkerCompleted += (s, e) =>
            {
                // Check if the worker has been canceled or if an error occurred
                if ((!e.Cancelled) && (e.Error == null))
                {
                    // Show return status
                    txtConsole.Text += (string)e.Result;
                }
                else if (e.Cancelled)
                {
                    // Process cancelled by user? warn
                    txtConsole.Text += string.Format("! {0}\n", res.GetString("strUserCancel", ci));
                }
                else
                {
                    // Some other stuff? warn
                    txtConsole.Text += string.Format("! {0}\n", res.GetString("strUnknownError", ci));
                }
                // Restore UI status after completion
                pbWaitingAnim.Visible    = false;
                progressBar.Visible      = false;
                btBatchProcess.Enabled   = true;
                sizePanel.Visible        = true;
                btBackCollection.Visible = true;
            };
            // Handler to update progress bar
            bgBatchWorker.ProgressChanged += (s, e) =>
            {
                // Use text from handler (card progress)
                progressBar.text  = (string)e.UserState;
                // Store progress (percent value)
                progressBar.Value = e.ProgressPercentage;
            };
            // Resume painting
            ResumeLayout();
        }
Exemplo n.º 41
0
 /// <summary>
 /// Returns a valid string to use with CultureInfo
 /// </summary>
 /// <param name="lang">language as enum value</param>
 /// <returns></returns>
 public static string getCultureLocale(Locales lang)
 {
     return Config.cultureLocales[(int)lang];
 }
Exemplo n.º 42
0
 /// <summary>
 /// Get locale string from enum value (short form).
 /// Given a *known* locale value, returns a string corresponding to that locale in xxYY format (in example, esES, enGB...).
 /// </summary>
 /// <param name="_locale">Enum with locale</param>
 /// <returns></returns>
 public static string getShortLocale(Locales _locale)
 {
     // Get locale string from array based on its enum as position
     return Config.locales[(int)_locale];
 }
Exemplo n.º 43
0
        public MemoryStream ReadFile(string name, Locales locales = Locales.enUS)
        {
            var hash = lookup3.Hash(name.ToUpperInvariant());

            return ReadFile(rootFile[hash], locales);
        }
Exemplo n.º 44
0
        public IEnumerable<Tuple<ulong, MemoryStream>> ReadFile(Locales locales = Locales.enUS)
        {
            foreach (var entry in rootFile.Entries)
            {
                var rootEntries = rootFile[entry.Key];

                for (var i = 0; i < rootEntries.Length; i++)
                {
                    if ((rootEntries[i].Locales & locales) == locales)
                    {
                        var encodingEntry = encodingFile[rootEntries[i].MD5];

                        if (encodingEntry.Size != 0 && encodingEntry.Keys.Length > 0)
                        {
                            MemoryStream blteStream = null;

                            for (var j = 0; j < 0x10; j++)
                            {
                                IndexEntry idxEntry = default(IndexEntry);

                                foreach (var k in encodingEntry.Keys)
                                {
                                    if ((idxEntry = idxFiles[j][k.Slice(0, 9)]).Size != 0)
                                    {
                                        var dataFile = dataFiles[idxEntry.Index];

                                        if (dataFile == null)
                                            throw new InvalidOperationException("Invalid data file.");

                                        yield return Tuple.Create(entry.Key, blteStream = DataFile.LoadBLTEEntry(idxEntry, dataFile.readStream));
                                    }
                                }

                                if (idxEntry.Size != 0)
                                    break;
                            }

                            if (blteStream == null)
                            {
                                for (var j = 0x10; j < idxFiles.Count; j++)
                                {
                                    IndexEntry idxEntry = default(IndexEntry);

                                    foreach (var k in encodingEntry.Keys)
                                    {
                                        if ((idxEntry = idxFiles[j][k]).Size != 0)
                                            yield return Tuple.Create(entry.Key, DataFile.LoadBLTEEntry(idxEntry, cdnConfig.DownloadFile(indexFiles[idxEntry.Index], idxEntry)));
                                    }

                                    if (idxEntry.Size != 0)
                                        break;
                                }
                            }
                        }
                    }
                }
            }

            //return null;
        }
Exemplo n.º 45
0
        /// <summary>
        /// Main form: Do all magic here :P
        /// </summary>
        public mainForm()
        {
            // Initialize Windows Forms components
            InitializeComponent();
            // Stop painting
            SuspendLayout();
            // Get language from resources
            ci  = CultureInfo.CreateSpecificCulture(General.getCultureLocale(language));
            res = new ResourceManager("HSCardGenerator.Resources.Texts.Strings", typeof(CustomForm).Assembly);
            // Assign strings to cursors
            btCreateCollection.Text = res.GetString("strCreateCollection", ci);
            btCreateCustom.Text     = res.GetString("strCreateCustom", ci);
            // Load fonts from resource into static class
            Fonts.loadFonts();
            // Add them to HTML Renderer (to render texts for card descriptions)
            HtmlRender.AddFontFamily(Fonts.BelweFamily);
            HtmlRender.AddFontFamily(Fonts.FranklinGothicFamily);
            HtmlRender.AddFontFamily(Fonts.EasternCharsFamily);
            // Assign pointer cursor to buttons and manage events to do their animations :3
            Font font    = new Font(Fonts.BelweFamily, 9f, FontStyle.Regular);
            Button[] btn = new[] { btExit, btCreateCustom, btCreateCollection };
            foreach (var button in btn)
            {
                button.UseCompatibleTextRendering = true;
                button.Font   = font;
                button.Cursor = cursorPointer;

                button.MouseDown += (s, e) => { if (e.Button == MouseButtons.Left) { button.Cursor = cursorPointerDown; } };
                button.MouseUp   += (s, e) => { if (e.Button == MouseButtons.Left) { button.Cursor = cursorPointer; } };
            }
            // Assign hand cursor to main panel and add event handlers to make it drag main form for moving ^^
            mainPanel.Cursor = cursorGrabOff;
            mainPanel.MouseDown += (s, e) =>
            {
                if (e.Button == MouseButtons.Left)
                {
                    Cursor = cursorGrabOn;
                    SafeNativeMethods.ReleaseCapture();
                    SafeNativeMethods.SendMessage(Handle, SafeNativeMethods.WM_NCLBUTTONDOWN, (IntPtr)SafeNativeMethods.HT_CAPTION, IntPtr.Zero);
                }
            };
            // Assign event handler to exit button (yep, I know it's easier using IDE, but code won't be reused. So... :)
            btExit.Click += (s, e) =>
            {
                Close();
            };
            // Assign event handler to "create custom card" button (same as above)
            btCreateCustom.Click += (s, e) =>
            {
                // Show Modal CustomForm Window
                using (var custom = new CustomForm(language))
                {
                    custom.ShowDialog();
                }
            };
            // Finally, assign event to "batch create collection" button
            btCreateCollection.Click += (s, e) =>
            {
                // Show Modal BatchForm Window
                using (var batch = new BatchForm(language))
                {
                    batch.ShowDialog();
                }
            };
            // Create custom combobox with flags for locales
            cbLocale.Top    = 4;
            cbLocale.Left   = 520;
            cbLocale.Size   = new Size(50, 30);
            cbLocale.Parent = mainPanel;
            cbLocale.Cursor = cursorPointer;
            // Populate combobox
            foreach (var item in Config.locales)
            {
                cbLocale.Items.Add(item);
            }
            // Assign event handlers: To enhace click experience xD
            cbLocale.MouseDown += (s, e) => { if (e.Button == MouseButtons.Left) { cbLocale.Cursor = cursorPointerDown; } };
            cbLocale.MouseUp   += (s, e) => { if (e.Button == MouseButtons.Left) { cbLocale.Cursor = cursorPointer; } };
            // When selecting a new locale...
            cbLocale.SelectedIndexChanged += (s, e) =>
            {
                // Get it from resources
                language = General.getLocaleFromString((string) cbLocale.Items[cbLocale.SelectedIndex]);
                ci       = CultureInfo.CreateSpecificCulture(General.getCultureLocale(language));
                res      = new ResourceManager("HSCardGenerator.Resources.Texts.Strings", typeof(CustomForm).Assembly);
                // Assign new texts to buttons
                btCreateCollection.Text = res.GetString("strCreateCollection", ci);
                btCreateCustom.Text     = res.GetString("strCreateCustom", ci);
                // Store locale into Settings
                Properties.Settings.Default.Locale = cbLocale.SelectedIndex;
                Properties.Settings.Default.Save();
            };
            // And assign previously stored locale to combobox, to refresh UI
            cbLocale.SelectedIndex = (int)Properties.Settings.Default.Locale;
            // Continue painting
            ResumeLayout();
        }
Exemplo n.º 46
0
        public MemoryStream ReadFile(RootEntry[] rootEntries, Locales locales = Locales.enUS)
        {
            for (var i = 0; i < rootEntries.Length; i++)
            {
                if ((rootEntries[i].Locales & locales) == locales)
                {
                    var encodingEntry = encodingFile[rootEntries[i].MD5];

                    if (encodingEntry.Size != 0 && encodingEntry.Keys.Length > 0)
                    {
                        for (var j = 0; j < 0x10; j++)
                        {
                            IndexEntry idxEntry = default(IndexEntry);

                            foreach (var k in encodingEntry.Keys)
                            {
                                if ((idxEntry = idxFiles[j][k.Slice(0, 9)]).Size != 0)
                                {
                                    var dataFile = dataFiles[idxEntry.Index];

                                    if (dataFile == null)
                                        throw new InvalidOperationException("Invalid data file.");

                                    var ret = DataFile.LoadBLTEEntry(idxEntry, dataFile.readStream);

                                    if (ret == null)
                                        break;

                                    return ret;
                                }
                            }

                            if (idxEntry.Size != 0)
                                break;
                        }

                        // CDN indices
                        for (var j = 0x10; j < idxFiles.Count; j++)
                        {
                            IndexEntry idxEntry = default(IndexEntry);

                            foreach (var k in encodingEntry.Keys)
                            {
                                if ((idxEntry = idxFiles[j][k]).Size != 0)
                                    return DataFile.LoadBLTEEntry(idxEntry, cdnConfig.DownloadFile(indexFiles[idxEntry.Index], idxEntry));
                            }

                            if (idxEntry.Size != 0)
                                break;
                        }
                    }
                }
            }

            return null;
        }