This class can be used to export resources from the database to ASP.NET compatible resources (Resx). This class takes all the resources in the database and creates RESX files that match these resources. Please note that it will overrwrite any existing resource files if they already exist, so please use this class with care if you have existing ResX resources. Note this class is primarily ASP.NET specific in that it looks at ASP.NET specific directory structures for ResX imports and strongly typed resource creation.
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest Request = HttpContext.Current.Request;
            HttpResponse Response = HttpContext.Current.Response;

            string resourceSet = Request.Params["ResourceSet"];
            string localeId = Request.Params["LocaleId"] ?? "auto";
            string resourceType = Request.Params["ResourceType"] ?? "Resx";   // Resx/ResDb
            bool includeControls = (Request.Params["IncludeControls"] ?? "") != "";
            string varname = Request.Params["VarName"] ?? "resources";
            string resourceMode = (Request.Params["ResourceMode"] ?? "0");

            // varname is embedded into script so validate to avoid script injection
            // it's gotta be a valid C# and valid JavaScript name
            Match match = Regex.Match(varname, @"^[\w|\d|_|$|@|\.]*$");
            if (match.Length < 1 || match.Groups[0].Value != varname)
                SendErrorResponse("Invalid variable name passed.");

            if (string.IsNullOrEmpty(resourceSet))
                SendErrorResponse("Invalid ResourceSet specified.");

            // pick current UI Culture
            if (localeId == "auto")
                localeId = Thread.CurrentThread.CurrentUICulture.IetfLanguageTag;

            Dictionary<string, object> resDict = null;

            if (string.IsNullOrEmpty(resourceType) || resourceType == "auto")
            {
                if (DbResourceProvider.ProviderLoaded || DbSimpleResourceProvider.ProviderLoaded)
                    resourceType = "resdb";
                else
                    resourceType = "resx";
            }


            if (resourceType.ToLower() == "resdb")
            {                
                // use existing/cached resource manager if previously used
                // so database is accessed only on first hit
                var resManager = DbRes.GetResourceManager(resourceSet);

                DbResXConverter converter = new DbResXConverter(context.Server.MapPath(DbResourceConfiguration.Current.ResxBaseFolder));
                resDict = converter.GetResourcesNormalizedForLocale(resManager, localeId);

                //resDict = manager.GetResourceSetNormalizedForLocaleId(localeId, resourceSet);
                if (resDict == null || resDict.Keys.Count < 1)
                {
                    // try resx instead
                    string resxPath = converter.FormatResourceSetPath(resourceSet);
                    resDict = converter.GetResXResourcesNormalizedForLocale(resxPath, localeId);
                }
            }
            else  // Resx Resources
            {
                string basePath = context.Server.MapPath(DbResourceConfiguration.Current.ResxBaseFolder);
                DbResXConverter converter = new DbResXConverter(basePath);

                resDict = converter.GetCompiledResourcesNormalizedForLocale(resourceSet, 
                    DbResourceConfiguration.Current.ResourceBaseNamespace, 
                    localeId);

                if (resDict == null)
                {
                    // check for .resx disk resources
                    string resxPath = converter.FormatResourceSetPath(resourceSet);
                    resDict = converter.GetResXResourcesNormalizedForLocale(resxPath, localeId);
                }
                else
                    resDict = resDict.OrderBy(kv => kv.Key).ToDictionary(k => k.Key, v => v.Value);
            }


            if (resourceMode == "0" && !includeControls)
            {
                // filter the list to strip out controls (anything that contains a . in the ResourceId 
                // is considered a control value
                resDict = resDict.Where(res => !res.Key.Contains('.') && res.Value is string)
                                 .ToDictionary(dict => dict.Key, dict => dict.Value);
            }
            else
            {
                // return all resource strings
                resDict = resDict.Where(res => res.Value is string)
                           .ToDictionary(dict => dict.Key, dict => dict.Value);
            }

            string javaScript = SerializeResourceDictionary(resDict, varname);


            // client cache
            if (!HttpContext.Current.IsDebuggingEnabled)
            {
                Response.ExpiresAbsolute = DateTime.UtcNow.AddDays(1);                
                Response.AppendHeader("Accept-Ranges", "bytes");
                Response.AppendHeader("Vary", "Accept-Encoding");
                Response.Cache.SetETag("\"" + javaScript.GetHashCode().ToString("x") + "\"");
                Response.Cache.SetLastModified(DateTime.UtcNow);

                // OutputCache settings
                HttpCachePolicy cache = Response.Cache;

                cache.VaryByParams["ResourceSet"] = true;
                cache.VaryByParams["LocaleId"] = true;
                cache.VaryByParams["ResoureType"] = true;
                cache.VaryByParams["IncludeControls"] = true;
                cache.VaryByParams["VarName"] = true;
                cache.VaryByParams["ResourceMode"] = true;
                //cache.SetOmitVaryStar(true);

                DateTime now = DateTime.Now;
                cache.SetCacheability(HttpCacheability.Public);
                cache.SetExpires(now + TimeSpan.FromDays(1));
                cache.SetValidUntilExpires(true);
                cache.SetLastModified(now);
            }

            SendTextOutput(javaScript, "text/javascript");
        }
Exemple #2
0
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest  Request  = HttpContext.Current.Request;
            HttpResponse Response = HttpContext.Current.Response;

            string resourceSet     = Request.Params["ResourceSet"];
            string localeId        = Request.Params["LocaleId"] ?? "";
            string resourceType    = Request.Params["ResourceType"] ?? "Resx"; // Resx/ResDb
            bool   includeControls = (Request.Params["IncludeControls"] ?? "") != "";
            string varname         = Request.Params["VarName"] ?? "resources";
            string resourceMode    = (Request.Params["ResourceMode"] ?? "0");

            // varname is embedded into script so validate to avoid script injection
            // it's gotta be a valid C# and valid JavaScript name
            Match match = Regex.Match(varname, @"^[\w|\d|_|$|@|\.]*$");

            if (match.Length < 1 || match.Groups[0].Value != varname)
            {
                SendErrorResponse("Invalid variable name passed.");
            }

            if (string.IsNullOrEmpty(resourceSet))
            {
                SendErrorResponse("Invalid ResourceSet specified.");
            }

            Dictionary <string, object> resDict = null;

            if (resourceType.ToLower() == "resdb")
            {
                DbResourceDataManager manager = new DbResourceDataManager();
                resDict = manager.GetResourceSetNormalizedForLocaleId(localeId, resourceSet) as Dictionary <string, object>;
            }
            else  // Resx Resources
            {
                DbResXConverter converter = new DbResXConverter();
                // must figure out the path
                string resxPath = null;
                //if (DbResourceConfiguration.Current.ResxExportProjectType == GlobalizationResxExportProjectTypes.WebForms)
                //    resxPath = converter.FormatWebResourceSetPath(resourceSet, (resourceMode == "0") );
                //else
                resxPath = converter.FormatResourceSetPath(resourceSet);

                resDict = converter.GetResXResourcesNormalizedForLocale(resxPath, localeId) as Dictionary <string, object>;
            }


            if (resourceMode == "0" && !includeControls)
            {
                // filter the list to strip out controls (anything that contains a . in the ResourceId
                // is considered a control value
                resDict = resDict.Where(res => !res.Key.Contains('.') && res.Value is string)
                          .ToDictionary(dict => dict.Key, dict => dict.Value);
            }
            else
            {
                // return all resource strings
                resDict = resDict.Where(res => res.Value is string)
                          .ToDictionary(dict => dict.Key, dict => dict.Value);
            }

            string javaScript = SerializeResourceDictionary(resDict, varname);


            // client cache
            if (!HttpContext.Current.IsDebuggingEnabled)
            {
                Response.ExpiresAbsolute = DateTime.UtcNow.AddDays(30);
                Response.Cache.SetLastModified(DateTime.UtcNow);
                Response.AppendHeader("Accept-Ranges", "bytes");
                Response.AppendHeader("Vary", "Accept-Encoding");
                Response.Cache.SetETag("\"" + javaScript.GetHashCode().ToString("x") + "\"");
                Response.Cache.SetLastModified(DateTime.UtcNow);
            }

            // OutputCache settings
            HttpCachePolicy cache = Response.Cache;

            cache.VaryByParams["LocaleId"]        = true;
            cache.VaryByParams["ResoureType"]     = true;
            cache.VaryByParams["IncludeControls"] = true;
            cache.VaryByParams["VarName"]         = true;
            cache.VaryByParams["ResourceMode"]    = true;
            //cache.SetOmitVaryStar(true);

            DateTime now = DateTime.Now;

            cache.SetCacheability(HttpCacheability.Public);
            cache.SetExpires(now + TimeSpan.FromDays(10));
            cache.SetValidUntilExpires(true);
            cache.SetLastModified(now);

            SendTextOutput(javaScript, "application/javascript");
        }
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest  Request  = HttpContext.Current.Request;
            HttpResponse Response = HttpContext.Current.Response;

            string resourceSet     = Request.Params["ResourceSet"];
            string localeId        = Request.Params["LocaleId"] ?? "auto";
            string resourceType    = Request.Params["ResourceType"] ?? "Resx"; // Resx/ResDb
            bool   includeControls = (Request.Params["IncludeControls"] ?? "") != "";
            string varname         = Request.Params["VarName"] ?? "resources";
            string resourceMode    = (Request.Params["ResourceMode"] ?? "0");

            // varname is embedded into script so validate to avoid script injection
            // it's gotta be a valid C# and valid JavaScript name
            Match match = Regex.Match(varname, @"^[\w|\d|_|$|@|\.]*$");

            if (match.Length < 1 || match.Groups[0].Value != varname)
            {
                SendErrorResponse("Invalid variable name passed.");
            }

            if (string.IsNullOrEmpty(resourceSet))
            {
                SendErrorResponse("Invalid ResourceSet specified.");
            }

            // pick current UI Culture
            if (localeId == "auto")
            {
                localeId = Thread.CurrentThread.CurrentUICulture.IetfLanguageTag;
            }

            Dictionary <string, object> resDict = null;

            if (string.IsNullOrEmpty(resourceType) || resourceType == "auto")
            {
                if (DbResourceProvider.ProviderLoaded || DbSimpleResourceProvider.ProviderLoaded)
                {
                    resourceType = "resdb";
                }
                else
                {
                    resourceType = "resx";
                }
            }


            if (resourceType.ToLower() == "resdb")
            {
                // use existing/cached resource manager if previously used
                // so database is accessed only on first hit
                var resManager = DbRes.GetResourceManager(resourceSet);

                DbResXConverter converter = new DbResXConverter(context.Server.MapPath(DbResourceConfiguration.Current.ResxBaseFolder));
                resDict = converter.GetResourcesNormalizedForLocale(resManager, localeId);

                //resDict = manager.GetResourceSetNormalizedForLocaleId(localeId, resourceSet);
                if (resDict == null || resDict.Keys.Count < 1)
                {
                    // try resx instead
                    string resxPath = converter.FormatResourceSetPath(resourceSet);
                    resDict = converter.GetResXResourcesNormalizedForLocale(resxPath, localeId);
                }
            }
            else  // Resx Resources
            {
                string          basePath  = context.Server.MapPath(DbResourceConfiguration.Current.ResxBaseFolder);
                DbResXConverter converter = new DbResXConverter(basePath);

                resDict = converter.GetCompiledResourcesNormalizedForLocale(resourceSet,
                                                                            DbResourceConfiguration.Current.ResourceBaseNamespace,
                                                                            localeId);

                if (resDict == null)
                {
                    // check for .resx disk resources
                    string resxPath = converter.FormatResourceSetPath(resourceSet);
                    resDict = converter.GetResXResourcesNormalizedForLocale(resxPath, localeId);
                }
                else
                {
                    resDict = resDict.OrderBy(kv => kv.Key).ToDictionary(k => k.Key, v => v.Value);
                }
            }


            if (resourceMode == "0" && !includeControls)
            {
                // filter the list to strip out controls (anything that contains a . in the ResourceId
                // is considered a control value
                resDict = resDict.Where(res => !res.Key.Contains('.') && res.Value is string)
                          .ToDictionary(dict => dict.Key, dict => dict.Value);
            }
            else
            {
                // return all resource strings
                resDict = resDict.Where(res => res.Value is string)
                          .ToDictionary(dict => dict.Key, dict => dict.Value);
            }

            string javaScript = SerializeResourceDictionary(resDict, varname);


            // client cache
            if (!HttpContext.Current.IsDebuggingEnabled)
            {
                Response.ExpiresAbsolute = DateTime.UtcNow.AddDays(1);
                Response.AppendHeader("Accept-Ranges", "bytes");
                Response.AppendHeader("Vary", "Accept-Encoding");
                Response.Cache.SetETag("\"" + javaScript.GetHashCode().ToString("x") + "\"");
                Response.Cache.SetLastModified(DateTime.UtcNow);

                // OutputCache settings
                HttpCachePolicy cache = Response.Cache;

                cache.VaryByParams["ResourceSet"]     = true;
                cache.VaryByParams["LocaleId"]        = true;
                cache.VaryByParams["ResoureType"]     = true;
                cache.VaryByParams["IncludeControls"] = true;
                cache.VaryByParams["VarName"]         = true;
                cache.VaryByParams["ResourceMode"]    = true;
                //cache.SetOmitVaryStar(true);

                DateTime now = DateTime.Now;
                cache.SetCacheability(HttpCacheability.Public);
                cache.SetExpires(now + TimeSpan.FromDays(1));
                cache.SetValidUntilExpires(true);
                cache.SetLastModified(now);
            }

            SendTextOutput(javaScript, "text/javascript");
        }
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest Request = HttpContext.Current.Request;
            HttpResponse Response = HttpContext.Current.Response;

            string resourceSet = Request.Params["ResourceSet"];
            string localeId = Request.Params["LocaleId"] ?? "";
            string resourceType = Request.Params["ResourceType"] ?? "Resx";   // Resx/ResDb
            bool includeControls = (Request.Params["IncludeControls"] ?? "") != "";
            string varname = Request.Params["VarName"] ?? "localRes";
            string resourceMode = (Request.Params["ResourceMode"] ?? "0");

            // varname is embedded into script so validate to avoid script injection
            // it's gotta be a valid C# and valid JavaScript name
            Match match = Regex.Match(varname, @"^[\w|\d|_|$|@]*$");
            if (match.Length < 1 || match.Groups[0].Value != varname)
                this.SendErrorResponse("Invalid variable name passed.");

            if (string.IsNullOrEmpty(resourceSet))
                this.SendErrorResponse("Invalid ResourceSet specified.");

            Dictionary<string, object> resDict = null;

            if (resourceType.ToLower() == "resdb")
            {
                DbResourceDataManager manager = new DbResourceDataManager();
                resDict = manager.GetResourceSetNormalizedForLocaleId(localeId, resourceSet) as Dictionary<string, object>;
            }
            else  // Resx Resources
            {
                DbResXConverter converter = new DbResXConverter();
                // must figure out the path
                string resxPath = null;
                if (DbResourceConfiguration.Current.ProjectType == GlobalizationProjectTypes.WebForms)
                    resxPath = converter.FormatWebResourceSetPath(resourceSet, (resourceMode == "0") );
                else
                    resxPath = converter.FormatResourceSetPath(resourceSet);

                resDict = converter.GetResXResourcesNormalizedForLocale(resxPath, localeId) as Dictionary<string, object>;
            }


            if (resourceMode == "0" && !includeControls)
            {
                // filter the list to strip out controls (anything that contains a . in the ResourceId 
                // is considered a control value
                resDict = resDict.Where(res => !res.Key.Contains('.') && res.Value is string)
                                 .ToDictionary(dict => dict.Key, dict => dict.Value);
            }
            else
            {
                // return all resource strings
                resDict = resDict.Where(res => res.Value is string)
                           .ToDictionary(dict => dict.Key, dict => dict.Value);
            }

            string javaScript = this.SerializeResourceDictionary(resDict, varname);


            // client cache
            if (!HttpContext.Current.IsDebuggingEnabled)
            {                
                Response.ExpiresAbsolute = DateTime.UtcNow.AddDays(30);
                Response.Cache.SetLastModified(DateTime.UtcNow);
                Response.AppendHeader("Accept-Ranges", "bytes");
                Response.AppendHeader("Vary", "Accept-Encoding");
                //Response.Cache.SetETag("\"" + javaScript.GetHashCode().ToString("x") + "\"");
            }

            // OutputCache settings
            HttpCachePolicy cache = Response.Cache;

            cache.VaryByParams["LocaleId"] = true;
            cache.VaryByParams["ResoureType"] = true;
            cache.VaryByParams["IncludeControls"] = true;
            cache.VaryByParams["VarName"] = true;
            cache.VaryByParams["ResourceMode"] = true;           
            cache.SetOmitVaryStar(true);

            DateTime now = DateTime.Now;
            cache.SetCacheability(HttpCacheability.Public);

            cache.SetExpires(now + TimeSpan.FromDays(365.0));
            cache.SetValidUntilExpires(true);
            cache.SetLastModified(now);

            this.SendTextOutput(javaScript, "application/javascript");
        }
        protected void btnImport_Click(object sender, EventArgs e)
        {
#if OnlineDemo
        this.ErrorDisplay.ShowError(WebUtils.LRes("FeatureDisabled"));
        return;
#endif

            DbResXConverter Converter = new DbResXConverter(Context.Request.PhysicalApplicationPath);            
            
            bool res = false;

            if (DbResourceConfiguration.Current.ResxExportProjectType == GlobalizationResxExportProjectTypes.WebForms)
                res = Converter.ImportWebResources();
            else
                res = Converter.ImportWinResources(Server.MapPath("~/"));       

            if (res)
                ErrorDisplay.ShowMessage(WebUtils.LRes("ResourceImportComplete"));
            else
                ErrorDisplay.ShowError(WebUtils.LRes("ResourceImportFailed"));

            lstResourceIds.ClearSelection();
            lstResourceSet.ClearSelection();

            GetResourceSet();
        }
        protected void btnExportResources_Click(object sender, EventArgs e)
        {
#if OnlineDemo
        this.ErrorDisplay.ShowError(WebUtils.LRes("FeatureDisabled"));
        return;
#endif

            DbResXConverter Exporter = new DbResXConverter(Context.Request.PhysicalApplicationPath);

            if (DbResourceConfiguration.Current.ResxExportProjectType == GlobalizationResxExportProjectTypes.WebForms)
            {
                if (!Exporter.GenerateLocalWebResourceResXFiles())
                {
                    ErrorDisplay.ShowError(WebUtils.LRes("ResourceGenerationFailed"));
                    return;
                }
                if (!Exporter.GenerateGlobalWebResourceResXFiles())
                {
                    ErrorDisplay.ShowError(WebUtils.LRes("ResourceGenerationFailed"));
                    return;
                }
            }
            else
            {
                if (!Exporter.GenerateResXFiles())
                {
                    ErrorDisplay.ShowError(WebUtils.LRes("ResourceGenerationFailed"));
                    return;
                }
            }

            ErrorDisplay.ShowMessage(WebUtils.LRes("ResourceGenerationComplete"));
        }