Beispiel #1
0
        /// <summary>
        /// Create translation structure at scope of tranlatable object.
        /// </summary>
        /// <param name="translatableObject">Translateable object</param>
        /// <param name="culture">Culture which is used to store translation</param>
        public static void SaveTranslation(this ITranslatable translatableObject, string culture)
        {
            #region validation

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

            if (string.IsNullOrEmpty(culture))
            {
                throw new ArgumentNullException(nameof(culture));
            }

            #endregion

            // create translation structure if not exists
            if (translatableObject.Translations == null)
            {
                translatableObject.Translations = new List <Translation>();
            }

            // check if translation for specified culture already exists
            Translation translation = translatableObject.GetTranslation(culture);
            if (translation == null)
            {
                // create translation for specified culture
                translation = new Translation()
                {
                    Culture = culture
                };
                translatableObject.Translations.Add(translation);
            }

            List <TranslationText> translationTexts = new List <TranslationText>();

            // get all properties with 'translatable' annotation which are of type string
            Type translationType = translatableObject.GetType();
            foreach (PropertyInfo translationProperty in translationType.GetTranslatableProperties())
            {
                translationTexts.Add(new TranslationText()
                {
                    Name = translationProperty.Name,
                    Text = (string)translationProperty.GetValue(translatableObject)
                });
            }

            translation.Texts = translationTexts;

            if (!string.IsNullOrEmpty(Instance.DefaultCulture))
            {
                // reset culture dependend properties to default language
                translatableObject.Translate(Instance.DefaultCulture);
            }
        }