예제 #1
0
        public ActionResult ImportXml(int id, FormCollection form, ImportModeFlags mode, bool updateTouched)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageLanguages))
            {
                return(AccessDeniedView());
            }

            var language = _languageService.GetLanguageById(id);

            if (language == null)
            {
                //No language found with the specified id
                return(RedirectToAction("List"));
            }

            //set page timeout to 5 minutes
            this.Server.ScriptTimeout = 300;

            try
            {
                var file = Request.Files["importxmlfile"];
                if (file != null && file.ContentLength > 0)
                {
                    using (var sr = new StreamReader(file.InputStream, Encoding.UTF8))
                    {
                        string content = sr.ReadToEnd();
                        _localizationService.ImportResourcesFromXml(language, content, mode: mode, updateTouchedResources: updateTouched);
                    }
                }
                else
                {
                    NotifyError(_localizationService.GetResource("Admin.Common.UploadFile"));
                    return(RedirectToAction("Edit", new { id = language.Id }));
                }

                NotifySuccess(_localizationService.GetResource("Admin.Configuration.Languages.Imported"));
                return(RedirectToAction("Edit", new { id = language.Id }));
            }
            catch (Exception exc)
            {
                NotifyError(exc);
                return(RedirectToAction("Edit", new { id = language.Id }));
            }
        }
        /// <summary>
        /// Imports language resources from XML file. This method commits to db.
        /// </summary>
        /// <param name="language">Language</param>
        /// <param name="xmlDocument">XML document</param>
        /// <param name="rootKey">Prefix for resource key name</param>
        /// <param name="mode">Specifies whether resources should be inserted or updated (or both)</param>
        /// <param name="updateTouchedResources">Specifies whether user touched resources should also be updated</param>
        /// <returns>The number of processed (added or updated) resource entries</returns>
        public static Task <int> ImportResourcesFromXmlAsync(this IXmlResourceManager manager,
                                                             Language language,
                                                             string xml,
                                                             string rootKey              = null,
                                                             bool sourceIsPlugin         = false,
                                                             ImportModeFlags mode        = ImportModeFlags.Insert | ImportModeFlags.Update,
                                                             bool updateTouchedResources = false)
        {
            if (string.IsNullOrEmpty(xml))
            {
                return(Task.FromResult(0));
            }

            var xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(xml);

            return(manager.ImportResourcesFromXmlAsync(language, xmlDoc, rootKey, sourceIsPlugin, mode, updateTouchedResources));
        }
        public ActionResult ImportXml(int id, FormCollection form, ImportModeFlags mode, bool updateTouched)
        {
            if (!_services.Permissions.Authorize(StandardPermissionProvider.ManageLanguages))
            {
                return(AccessDeniedView());
            }

            var language = _languageService.GetLanguageById(id);

            if (language == null)
            {
                return(RedirectToAction("List"));
            }

            //set page timeout to 5 minutes
            this.Server.ScriptTimeout = 300;

            try
            {
                var file = Request.Files["importxmlfile"];
                if (file != null && file.ContentLength > 0)
                {
                    _services.Localization.ImportResourcesFromXml(language, file.InputStream.AsString(), mode: mode, updateTouchedResources: updateTouched);
                }
                else
                {
                    NotifyError(T("Admin.Common.UploadFile"));
                    return(RedirectToAction("Edit", new { id = language.Id }));
                }

                NotifySuccess(T("Admin.Configuration.Languages.Imported"));
                return(RedirectToAction("Edit", new { id = language.Id }));
            }
            catch (Exception exc)
            {
                NotifyError(exc);
                return(RedirectToAction("Edit", new { id = language.Id }));
            }
        }
예제 #4
0
        /// <summary>
        /// Import language resources from XML file
        /// </summary>
        /// <param name="language">Language</param>
        /// <param name="xml">XML</param>
        public static void ImportResourcesFromXml(this ILocalizationService service,
                                                  Language language,
                                                  string xml,
                                                  string rootKey              = null,
                                                  bool sourceIsPlugin         = false,
                                                  ImportModeFlags mode        = ImportModeFlags.Insert | ImportModeFlags.Update,
                                                  bool updateTouchedResources = false)
        {
            if (language == null)
            {
                throw new ArgumentNullException(nameof(language));
            }

            if (String.IsNullOrEmpty(xml))
            {
                return;
            }

            var xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(xml);

            service.ImportResourcesFromXml(language, xmlDoc, rootKey, sourceIsPlugin, mode, updateTouchedResources);
        }
예제 #5
0
        public async Task <ActionResult> ImportXml(int id, FormCollection form, ImportModeFlags mode, bool updateTouched, int?availableLanguageSetId)
        {
            var language = _languageService.GetLanguageById(id);

            if (language == null)
            {
                return(RedirectToAction("List"));
            }

            // Set page timeout to 5 minutes
            Server.ScriptTimeout = 300;

            string tempFilePath = null;

            try
            {
                var file = Request.Files["importxmlfile"];
                if (file != null && file.ContentLength > 0)
                {
                    _services.Localization.ImportResourcesFromXml(language, file.InputStream.AsString(), mode: mode, updateTouchedResources: updateTouched);

                    NotifySuccess(T("Admin.Configuration.Languages.Imported"));
                }
                else if ((availableLanguageSetId ?? 0) != 0)
                {
                    var checkResult = await CheckAvailableResources();

                    var availableResources = checkResult.Resources.First(x => x.Id == availableLanguageSetId.Value);

                    tempFilePath = await DownloadAvailableResources(availableResources.DownloadUrl, _services.StoreContext.CurrentStore.Url);

                    var xmlDoc = new XmlDocument();
                    xmlDoc.Load(tempFilePath);

                    _services.Localization.ImportResourcesFromXml(language, xmlDoc, null, false, mode, updateTouched);

                    var str = JsonConvert.SerializeObject(new LastResourcesImportInfo
                    {
                        TranslatedPercentage = availableResources.TranslatedPercentage,
                        ImportedOn           = DateTime.UtcNow
                    });
                    _genericAttributeService.SaveAttribute(language, "LastResourcesImportInfo", str);

                    NotifySuccess(T("Admin.Configuration.Languages.Imported"));
                }
                else
                {
                    NotifyError(T("Admin.Configuration.Languages.UploadFileOrSelectLanguage"));
                }
            }
            catch (Exception exception)
            {
                NotifyError(exception);
                Logger.ErrorsAll(exception);
            }
            finally
            {
                FileSystemHelper.DeleteFile(tempFilePath);
            }

            return(RedirectToAction("Edit", new { id = language.Id }));
        }
예제 #6
0
        public virtual int ImportResourcesFromXml(
            Language language,
            XmlDocument xmlDocument,
            string rootKey              = null,
            bool sourceIsPlugin         = false,
            ImportModeFlags mode        = ImportModeFlags.Insert | ImportModeFlags.Update,
            bool updateTouchedResources = false)
        {
            using (var scope = new DbContextScope(autoDetectChanges: false, proxyCreation: false, validateOnSave: false, autoCommit: false, forceNoTracking: true, hooksEnabled: false))
            {
                var toAdd    = new List <LocaleStringResource>();
                var toUpdate = new List <LocaleStringResource>();
                var nodes    = xmlDocument.SelectNodes(@"//Language/LocaleResource");

                var resources = language.LocaleStringResources.ToDictionarySafe(x => x.ResourceName, StringComparer.OrdinalIgnoreCase);

                LocaleStringResource resource;

                foreach (var xel in nodes.Cast <XmlElement>())
                {
                    string name      = xel.GetAttribute("Name").TrimSafe();
                    string value     = "";
                    var    valueNode = xel.SelectSingleNode("Value");
                    if (valueNode != null)
                    {
                        value = valueNode.InnerText;
                    }

                    if (String.IsNullOrEmpty(name))
                    {
                        continue;
                    }

                    if (rootKey.HasValue())
                    {
                        if (!xel.GetAttributeText("AppendRootKey").IsCaseInsensitiveEqual("false"))
                        {
                            name = "{0}.{1}".FormatWith(rootKey, name);
                        }
                    }

                    resource = null;

                    // do not use "Insert"/"Update" methods because they clear cache
                    // let's bulk insert
                    //var resource = language.LocaleStringResources.Where(x => x.ResourceName.Equals(name, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
                    if (resources.TryGetValue(name, out resource))
                    {
                        if (mode.HasFlag(ImportModeFlags.Update))
                        {
                            if (updateTouchedResources || !resource.IsTouched.GetValueOrDefault())
                            {
                                if (value != resource.ResourceValue)
                                {
                                    resource.ResourceValue = value;
                                    resource.IsTouched     = null;
                                    toUpdate.Add(resource);
                                }
                            }
                        }
                    }
                    else
                    {
                        if (mode.HasFlag(ImportModeFlags.Insert))
                        {
                            toAdd.Add(
                                new LocaleStringResource
                            {
                                LanguageId    = language.Id,
                                ResourceName  = name,
                                ResourceValue = value,
                                IsFromPlugin  = sourceIsPlugin
                            });
                        }
                    }
                }

                //_lsrRepository.AutoCommitEnabled = true;

                if (toAdd.Any() || toUpdate.Any())
                {
                    var segmentKeys = new HashSet <string>();

                    toAdd.Each(x => segmentKeys.Add(GetSegmentKeyPart(x.ResourceName)));
                    toUpdate.Each(x => segmentKeys.Add(GetSegmentKeyPart(x.ResourceName)));

                    _lsrRepository.InsertRange(toAdd);
                    toAdd.Clear();

                    _lsrRepository.UpdateRange(toUpdate);
                    toUpdate.Clear();

                    int num = _lsrRepository.Context.SaveChanges();

                    // clear cache
                    foreach (var segmentKey in segmentKeys)
                    {
                        ClearCacheSegment(segmentKey, language.Id);
                    }

                    return(num);
                }

                return(0);
            }
        }
        /// <summary>
        /// Import language resources from XML file
        /// </summary>
        /// <param name="language">Language</param>
        /// <param name="xmlDocument">XML document</param>
        /// <param name="rootKey">Prefix for resource key name</param>
        public virtual void ImportResourcesFromXml(
            Language language,
            XmlDocument xmlDocument,
            string rootKey              = null,
            bool sourceIsPlugin         = false,
            ImportModeFlags mode        = ImportModeFlags.Insert | ImportModeFlags.Update,
            bool updateTouchedResources = false)
        {
            using (var scope = new DbContextScope(autoDetectChanges: false, proxyCreation: false, validateOnSave: false, autoCommit: false))
            {
                var toAdd    = new List <LocaleStringResource>();
                var toUpdate = new List <LocaleStringResource>();
                var nodes    = xmlDocument.SelectNodes(@"//Language/LocaleResource");

                foreach (var xel in nodes.Cast <XmlElement>())
                {
                    string name      = xel.GetAttribute("Name").TrimSafe();
                    string value     = "";
                    var    valueNode = xel.SelectSingleNode("Value");
                    if (valueNode != null)
                    {
                        value = valueNode.InnerText;
                    }

                    if (String.IsNullOrEmpty(name))
                    {
                        continue;
                    }

                    if (rootKey.HasValue())
                    {
                        if (!xel.GetAttributeText("AppendRootKey").IsCaseInsensitiveEqual("false"))
                        {
                            name = "{0}.{1}".FormatWith(rootKey, name);
                        }
                    }

                    // do not use "Insert"/"Update" methods because they clear cache
                    // let's bulk insert
                    var resource = language.LocaleStringResources.Where(x => x.ResourceName.Equals(name, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
                    if (resource != null)
                    {
                        if (mode.HasFlag(ImportModeFlags.Update))
                        {
                            if (updateTouchedResources || !resource.IsTouched.GetValueOrDefault())
                            {
                                resource.ResourceValue = value;
                                resource.IsTouched     = null;
                                toUpdate.Add(resource);
                            }
                        }
                    }
                    else
                    {
                        if (mode.HasFlag(ImportModeFlags.Insert))
                        {
                            toAdd.Add(
                                new LocaleStringResource()
                            {
                                LanguageId    = language.Id,
                                ResourceName  = name,
                                ResourceValue = value,
                                IsFromPlugin  = sourceIsPlugin
                            });
                        }
                    }
                }

                _lsrRepository.AutoCommitEnabled = true;
                _lsrRepository.InsertRange(toAdd, 500);
                toAdd.Clear();

                _lsrRepository.UpdateRange(toUpdate);
                toUpdate.Clear();

                //clear cache
                _cacheManager.RemoveByPattern(LOCALESTRINGRESOURCES_PATTERN_KEY);
            }
        }
예제 #8
0
        public ActionResult ImportXml(int id, FormCollection form, ImportModeFlags mode, bool updateTouched)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageLanguages))
                return AccessDeniedView();

            var language = _languageService.GetLanguageById(id);
            if (language == null)
                return RedirectToAction("List");

            //set page timeout to 5 minutes
            this.Server.ScriptTimeout = 300;

            try
            {
                var file = Request.Files["importxmlfile"];
                if (file != null && file.ContentLength > 0)
                {
                    _localizationService.ImportResourcesFromXml(language, file.InputStream.AsString(), mode: mode, updateTouchedResources: updateTouched);
                }
                else
                {
                    NotifyError(_localizationService.GetResource("Admin.Common.UploadFile"));
                    return RedirectToAction("Edit", new { id = language.Id });
                }

                NotifySuccess(_localizationService.GetResource("Admin.Configuration.Languages.Imported"));
                return RedirectToAction("Edit", new { id = language.Id });
            }
            catch (Exception exc)
            {
                NotifyError(exc);
                return RedirectToAction("Edit", new { id = language.Id });
            }
        }