Exemple #1
0
        /// <summary>
        /// This is the worker method responsible for actually retrieving resources from the resource
        /// store. This method goes out queries the database by asking for a specific ResourceSet and
        /// Culture and it returns a Hashtable (as IEnumerable) to use as a ResourceSet.
        ///
        /// The ResourceSet manages access to resources via IEnumerable access which is ultimately used
        /// to return resources to the front end.
        ///
        /// Resources are read once and cached into an internal Items field. A ResourceReader instance
        /// is specific to a ResourceSet and Culture combination so there should never be a need to
        /// reload this data, except when explicitly clearing the reader/resourceset (in which case
        /// Items can be set to null via ClearResources()).
        /// </summary>
        /// <returns>An IDictionaryEnumerator of the resources for this reader</returns>
        public IDictionaryEnumerator GetEnumerator()
        {
            if (Items != null)
            {
                return(Items.GetEnumerator());
            }

            lock (_SyncLock)
            {
                // Check again to ensure we still don't have items
                if (Items != null)
                {
                    return(Items.GetEnumerator());
                }

                // DEPENDENCY HERE
                // Here's the only place we really access the database and return
                // a specific ResourceSet for a given ResourceSet Id and Culture
                DbResourceDataManager manager = DbResourceDataManager.CreateDbResourceDataManager();
                Items = manager.GetResourceSet(cultureInfo.Name, baseNameField);
                return(Items.GetEnumerator());
            }
        }
        /// <summary>
        /// Add a new resource to the base resource set
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        public void AddMissingResource(string name, string value, CultureInfo culture = null)
        {
            var manager = DbResourceDataManager.CreateDbResourceDataManager();

            string cultureName = string.Empty;

            if (culture != null)
            {
                cultureName = culture.IetfLanguageTag;
            }

            lock (AddSyncLock)
            {
                // double check if culture neutral version exists
                string item = manager.GetResourceObject(name, BaseName, cultureName) as string;
                if (item != null)
                {
                    return;
                }

                manager.AddResource(name, value, cultureName, BaseName, null);
            }
        }
        public ActionResult ProcessRequest()
        {
            var Request = HttpContext.Request;

            string resourceSet = Request.Query["ResourceSet"];


            string localeId = Request.Query["LocaleId"];

            if (string.IsNullOrEmpty(localeId))
            {
                localeId = "auto";
            }
            string resourceMode = Request.Query["ResourceMode"];

            if (string.IsNullOrEmpty(resourceMode))
            {
                resourceMode = "Resx"; // Resx/ResDb/Auto
            }
            string varname = Request.Query["VarName"];

            if (string.IsNullOrEmpty(varname))
            {
                varname = "resources";
            }

            // 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")
            {
                try
                {
                    // Use ASP.NET Core RequestLocalization Mapping
                    var cultureProvider = HttpContext.Features.Get <IRequestCultureFeature>();
                    if (cultureProvider != null)
                    {
                        localeId = cultureProvider.RequestCulture.UICulture.IetfLanguageTag;
                    }
                    else
                    {
                        localeId = Thread.CurrentThread.CurrentUICulture.IetfLanguageTag;
                    }
                }
                catch
                {
                    localeId = Thread.CurrentThread.CurrentUICulture.IetfLanguageTag;
                }
            }

            Dictionary <string, object> resDict = null;

            resourceMode = string.IsNullOrEmpty(resourceMode) ? "auto" : resourceMode.ToLower();

            ResourceAccessMode mode = ResourceAccessMode.Resx;

            if (resourceMode == "resdb")
            {
                mode = ResourceAccessMode.DbResourceManager;
            }
            else if (resourceMode == "auto")
            {
                mode = DbResourceConfiguration.Current.ResourceAccessMode;
            }


            if (mode == ResourceAccessMode.DbResourceManager)
            {
                var resManager = DbResourceDataManager.CreateDbResourceDataManager(
                    Config.DbResourceDataManagerType);
                resDict = resManager.GetResourceSetNormalizedForLocaleId(localeId, resourceSet);
                if (resDict == null || resDict.Count == 0)
                {
                    mode = ResourceAccessMode.Resx; // try Resx resources from disk instead
                }
            }
            if (mode != ResourceAccessMode.DbResourceManager) // Resx Resources loaded from disk
            {
                string          basePath  = Request.MapPath(DbResourceConfiguration.Current.ResxBaseFolder, basePath: Host.ContentRootPath);
                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);
                }
            }

            // return all resource strings
            resDict = resDict.Where(res => res.Value is string)
                      .ToDictionary(dict => dict.Key, dict => dict.Value);

            string javaScript = SerializeResourceDictionary(resDict, varname);



#if NETFULL // 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);
            }
#endif

            return(SendTextOutput(javaScript, "text/javascript; charset=utf-8"));
        }
Exemple #4
0
        /// <summary>
        /// Deletes a resource entry
        /// </summary>
        /// <param name="resourceId">The resource to delete</param>
        /// <param name="lang">The language Id - Be careful:  If empty or null deletes matching keys for all languages</param>
        /// <param name="resourceSet">The resource set to apply</param>
        /// <returns>true or false</returns>
        public bool DeleteResource(string resourceId, string resourceSet = null, string lang = null)
        {
            var db = DbResourceDataManager.CreateDbResourceDataManager();

            return(db.DeleteResource(resourceId, resourceSet: resourceSet, cultureName: lang));
        }
Exemple #5
0
        /// <summary>
        /// Imports an individual ResX Resource file into the database
        /// </summary>
        /// <param name="FileName">Full path to the the ResX file</param>
        /// <param name="ResourceSetName">Name of the file or for local resources the app relative path plus filename (admin/default.aspx or default.aspx)</param>
        /// <param name="LocaleId">Locale Id of the file to import. Use "" for Invariant</param>
        /// <returns></returns>
        public bool ImportResourceFile(string FileName, string ResourceSetName, string LocaleId)
        {
            string FilePath = Path.GetDirectoryName(FileName) + "\\";

            var Data = DbResourceDataManager.CreateDbResourceDataManager();

            XmlDocument dom = new XmlDocument();

            try
            {
                dom.Load(FileName);
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.Message;
                return(false);
            }

            XmlNodeList nodes = dom.DocumentElement.SelectNodes("data");

            foreach (XmlNode Node in nodes)
            {
                string Value; // = Node.ChildNodes[0].InnerText;

                XmlNodeList valueNodes = Node.SelectNodes("value");
                if (valueNodes.Count == 1)
                {
                    Value = valueNodes[0].InnerText;
                }
                else
                {
                    Value = Node.InnerText;
                }

                string Name = Node.Attributes["name"].Value;
                string Type = null;
                if (Node.Attributes["type"] != null)
                {
                    Type = Node.Attributes["type"].Value;
                }

                string  Comment     = null;
                XmlNode commentNode = Node.SelectSingleNode("comment");
                if (commentNode != null)
                {
                    Comment = commentNode.InnerText;
                }


                if (string.IsNullOrEmpty(Type))
                {
                    if (Data.UpdateOrAddResource(Name, Value, LocaleId, ResourceSetName, Comment) == -1)
                    {
                        ErrorMessage = Data.ErrorMessage;
                        return(false);
                    }
                    else
                    {
                        // File based resources are formatted: filename;full type name
                        string[] tokens = Value.Split(';');
                        if (tokens.Length > 0)
                        {
                            string ResFileName = FilePath + tokens[0];
                            if (File.Exists(ResFileName))
                            {
                                // DataManager knows about file resources and can figure type info
                                if (Data.UpdateOrAddResource(Name, ResFileName, LocaleId, ResourceSetName, Comment, true) ==
                                    -1)
                                {
                                    ErrorMessage = Data.ErrorMessage;
                                    return(false);
                                }
                            }
                        }
                    }
                }
            }

            return(true);
        }
Exemple #6
0
        /// <summary>
        /// Generates Resx Files for standard non-Web Resource files
        /// based on the BasePhysicalPath
        /// </summary>
        /// <param name="outputPath">
        /// Optional output path where resources are generated.
        /// If not specified the value is inferred for an ASP.NET Web app.
        /// </param>
        /// <returns></returns>
        public bool GenerateResXFiles()
        {
            var data = DbResourceDataManager.CreateDbResourceDataManager();

            // Retrieve all resources for a ResourceSet for all cultures
            // The data is ordered by ResourceSet, LocaleId and resource ID as each
            // ResourceSet or Locale changes a new file is written
            var resources = data.GetAllResources();

            if (resources == null)
            {
                return(false);
            }

            string lastSet    = "";
            string lastLocale = "@!";

            //// Load the document schema
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(ResXDocumentTemplate);

            XmlWriter xWriter     = null;
            var       xmlSettings = new XmlWriterSettings();

            //// Make sure we use fragment syntax so there's no validation
            //// otherwise loading the original string will fail
            xmlSettings.ConformanceLevel = ConformanceLevel.Document;
            xmlSettings.IndentChars      = "   ";
            xmlSettings.Indent           = true;

            foreach (var res in resources)
            {
                res.LocaleId = res.LocaleId.ToLower();
                string stringValue = res.Value as string;

                // Create a new output file if the resource set or locale changes
                if (res.ResourceSet != lastSet || res.LocaleId != lastLocale)
                {
                    if (xWriter != null)
                    {
                        xWriter.WriteEndElement();
                        xWriter.Close();
                    }

                    string localizedExtension = ".resx";
                    if (res.LocaleId != "")
                    {
                        localizedExtension = "." + res.LocaleId + ".resx";
                    }

                    string fullFileName = FormatResourceSetPath(res.ResourceSet) + localizedExtension;

                    XmlTextWriter writer = new XmlTextWriter(fullFileName, Encoding.UTF8);
                    writer.Indentation = 3;
                    writer.IndentChar  = ' ';
                    writer.Formatting  = Formatting.Indented;
                    xWriter            = writer;

                    xWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
                    xWriter.WriteStartElement("root");

                    // Write out the schema
                    doc.DocumentElement.ChildNodes[0].WriteTo(xWriter);

                    // Write out the leading resheader elements
                    XmlNodeList Nodes = doc.DocumentElement.SelectNodes("resheader");
                    foreach (XmlNode Node in Nodes)
                    {
                        Node.WriteTo(xWriter);
                    }

                    lastSet    = res.ResourceSet;
                    lastLocale = res.LocaleId;
                }

                if (string.IsNullOrEmpty(res.Type))  // plain string value
                {
                    //<data name="LinkButton1Resource1.Text" xml:space="preserve">
                    //    <value>LinkButton</value>
                    //</data>
                    xWriter.WriteStartElement("data");
                    xWriter.WriteAttributeString("name", res.ResourceId);
                    xWriter.WriteAttributeString("xml", "space", null, "preserve");
                    xWriter.WriteElementString("value", stringValue);
                    if (!string.IsNullOrEmpty(res.Comment))
                    {
                        xWriter.WriteElementString("comment", res.Comment);
                    }
                    xWriter.WriteEndElement(); // data
                }
                // File Resources get written to disk
                else if (res.Type == "FileResource")
                {
                    string ResourceFilePath = FormatResourceSetPath(res.ResourceSet);
                    string ResourcePath     = new FileInfo(ResourceFilePath).DirectoryName;

                    if (stringValue.IndexOf("System.String") > -1)
                    {
                        string[] Tokens = stringValue.Split(';');
                        Encoding Encode = Encoding.Default;
                        try
                        {
                            if (Tokens.Length == 3)
                            {
                                Encode = Encoding.GetEncoding(Tokens[2]);
                            }

                            // Write out the file to disk
                            File.WriteAllText(ResourcePath + "\\" + res.FileName, res.TextFile, Encode);
                        }
                        catch
                        {
                        }
                    }
                    else
                    {
                        File.WriteAllBytes(ResourcePath + "\\" + res.FileName, res.BinFile);
                    }

                    //<data name="Scratch" type="System.Resources.ResXFileRef, System.Windows.Forms">
                    //  <value>Scratch.txt;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252</value>
                    //</data>
                    xWriter.WriteStartElement("data");
                    xWriter.WriteAttributeString("name", res.ResourceId);
                    xWriter.WriteAttributeString("type", "System.Resources.ResXFileRef, System.Windows.Forms");

                    // values are already formatted in the database
                    xWriter.WriteElementString("value", stringValue);
                    if (!string.IsNullOrEmpty(res.Comment))
                    {
                        xWriter.WriteElementString("comment", res.Comment);
                    }

                    xWriter.WriteEndElement(); // data
                }
            } // foreach dr

            if (xWriter != null)
            {
                xWriter.WriteEndElement();
                //xWriter.WriteRaw("\r\n</root>");
                xWriter.Close();
            }

            return(true);
        }
Exemple #7
0
        /// <summary>
        /// Dumps resources from the DbResourceProvider database
        /// out to Resx resources in an ASP.NET application
        /// creating the appropriate APP_LOCAL_RESOURCES/APP_GLOBAL_RESOURCES
        /// folders and resx files.
        /// IMPORTANT: will overwrite existing files
        /// </summary>
        /// <param name="localResources"></param>
        /// <returns></returns>
        protected bool GenerateWebResourceResXFiles(bool localResources)
        {
            var data = DbResourceDataManager.CreateDbResourceDataManager();

            // Retrieve all resources for a ResourceSet for all cultures
            // The data is ordered by ResourceSet, LocaleId and resource ID as each
            // ResourceSet or Locale changes a new file is written
            var resources = data.GetAllResources(localResources: localResources, applyValueConverters: true);

            if (resources == null)
            {
                return(false);
            }

            string LastSet    = "";
            string LastLocale = "@!";

            // Load the document schema
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(ResXDocumentTemplate);

            XmlWriter         xWriter     = null;
            XmlWriterSettings XmlSettings = new XmlWriterSettings();

            //// Make sure we use fragment syntax so there's no validation
            //// otherwise loading the original string will fail
            XmlSettings.ConformanceLevel = ConformanceLevel.Document;
            XmlSettings.IndentChars      = "   ";
            XmlSettings.Indent           = true;

            foreach (var res in resources)
            {
                // Read into vars for easier usage below
                string ResourceId = res.ResourceId;
                string Value      = res.Value as string;
                string Comment    = res.Comment;

                string Type      = res.Type;
                string TextFile  = res.TextFile;
                byte[] BinFile   = res.BinFile;
                string FileName  = res.FileName;
                int    ValueType = res.ValueType;

                string ResourceSet = res.ResourceSet;

                string LocaleId = res.LocaleId;
                LocaleId = LocaleId.ToLower();

                // Create a new output file if the resource set or locale changes
                if (string.Compare(ResourceSet, LastSet, StringComparison.OrdinalIgnoreCase) != 0 ||
                    string.Compare(LocaleId, LastLocale, StringComparison.OrdinalIgnoreCase) != 0)
                {
                    if (xWriter != null)
                    {
                        //xWriter.WriteRaw("\r\n</root>");
                        xWriter.WriteEndElement();
                        xWriter.Close();
                    }

                    string Loc = ".resx";
                    if (LocaleId != "")
                    {
                        Loc = "." + LocaleId + ".resx";
                    }

                    //xWriter = XmlWriter.Create( this.FormatResourceSetPath(ResourceSet,LocalResources) + Loc,XmlSettings) ;
                    string        resourceFilename = FormatWebResourceSetPath(ResourceSet, localResources) + Loc;
                    XmlTextWriter Writer           = new XmlTextWriter(resourceFilename, Encoding.UTF8);
                    Writer.Indentation = 3;
                    Writer.IndentChar  = ' ';
                    Writer.Formatting  = Formatting.Indented;
                    xWriter            = Writer;

                    xWriter.WriteStartElement("root");

                    // Write out the schema
                    doc.DocumentElement.ChildNodes[0].WriteTo(xWriter);

                    // Write out the leading resheader elements
                    XmlNodeList Nodes = doc.DocumentElement.SelectNodes("resheader");
                    foreach (XmlNode Node in Nodes)
                    {
                        Node.WriteTo(xWriter);
                    }

                    LastSet    = ResourceSet;
                    LastLocale = LocaleId;
                }

                if (string.IsNullOrEmpty(Type)) // plain string value
                {
                    //<data name="LinkButton1Resource1.Text" xml:space="preserve">
                    //    <value>LinkButton</value>
                    //</data>
                    xWriter.WriteStartElement("data");
                    xWriter.WriteAttributeString("name", ResourceId);
                    xWriter.WriteAttributeString("xml", "space", null, "preserve");
                    xWriter.WriteElementString("value", Value);
                    if (!string.IsNullOrEmpty(Comment))
                    {
                        xWriter.WriteElementString("comment", Comment);
                    }
                    xWriter.WriteEndElement(); // data
                }
                // File Resources get written to disk
                else if (Type == "FileResource")
                {
                    string resourceFilenname = FormatWebResourceSetPath(ResourceSet, localResources);
                    string resourcePath      = new FileInfo(resourceFilenname).DirectoryName;

                    if (Value.IndexOf("System.String") > -1)
                    {
                        string[] Tokens = Value.Split(';');
                        Encoding Encode = Encoding.Default;
                        try
                        {
                            if (Tokens.Length == 3)
                            {
                                Encode = Encoding.GetEncoding(Tokens[2]);
                            }

                            // Write out the file to disk

                            File.WriteAllText(Path.Combine(resourcePath, FileName), TextFile, Encode);
                        }
                        catch (Exception ex)
                        {
                            string msg = ex.Message;
                        }
                    }
                    else
                    {
                        File.WriteAllBytes(Path.Combine(resourcePath, FileName), BinFile);
                    }

                    //<data name="Scratch" type="System.Resources.ResXFileRef, System.Windows.Forms">
                    //  <value>Scratch.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252</value>
                    //</data>
                    xWriter.WriteStartElement("data");
                    xWriter.WriteAttributeString("name", ResourceId);
                    xWriter.WriteAttributeString("type", "System.Resources.ResXFileRef, System.Windows.Forms");

                    // values are already formatted in the database
                    xWriter.WriteElementString("value", Value);
                    if (!string.IsNullOrEmpty(Comment))
                    {
                        xWriter.WriteElementString("comment", Comment);
                    }

                    xWriter.WriteEndElement(); // data
                }
            } // foreach dr

            if (xWriter != null)
            {
                xWriter.WriteEndElement();
                //xWriter.WriteRaw("\r\n</root>");
                xWriter.Close();
            }

            return(true);
        }
Exemple #8
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"] ?? "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")
            {
                var manager = DbResourceDataManager.CreateDbResourceDataManager();
                resDict = manager.GetResourceSetNormalizedForLocaleId(localeId, resourceSet);
                if (resDict == null || resDict.Keys.Count < 1)
                {
                    // try resx instead
                    DbResXConverter converter = new DbResXConverter(context.Server.MapPath(DbResourceConfiguration.Current.ResxBaseFolder));
                    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 #9
0
        /// <summary>
        /// Internal lookup method that handles retrieving a resource
        /// by its resource id and culture. Realistically this method
        /// is always called with the culture being null or empty
        /// but the routine handles resource fallback in case the
        /// code is manually called.
        /// </summary>
        /// <param name="resourceKey"></param>
        /// <param name="cultureName"></param>
        /// <returns></returns>
        object GetObjectInternal(string resourceKey, string cultureName)
        {
            IDictionary resources = GetResourceCache(cultureName);

            object value = null;

            if (resources != null)
            {
                value = resources[resourceKey];
            }

            // If we're at a specific culture (en-Us) and there's no value fall back
            // to the generic culture (en)
            if (value == null && cultureName.Length > 3)
            {
                // try again with the 2 letter locale
                return(GetObjectInternal(resourceKey, cultureName.Substring(0, 2)));
            }

            // If the value is still null get the invariant value
            if (value == null)
            {
                resources = GetResourceCache("");
                if (resources != null)
                {
                    value = resources[resourceKey];
                }
            }

            // If the value is still null and we're at the invariant culture
            // let's add a marker that the value is missing
            // this also allows the pre-compiler to work and never return null
            if (value == null)
            {
                // No entry there
                value = resourceKey;

                // DEPENDENCY HERE (#2): using DbResourceConfiguration and DbResourceDataManager to optionally
                //                           add missing resource keys

                // Add a key in the repository at least for the Invariant culture
                // Something's referencing but nothing's there
                if (DbResourceConfiguration.Current.AddMissingResources)
                {
                    lock (_SyncLock)
                    {
                        if (resources[resourceKey] == null)
                        {
                            var data = DbResourceDataManager.CreateDbResourceDataManager();
                            if (!data.ResourceExists(resourceKey, "", _ResourceSetName))
                            {
                                data.AddResource(resourceKey, resourceKey, "",
                                                 _ResourceSetName, null);
                            }

                            // add to current invariant resource set
                            resources.Add(resourceKey, resourceKey);
                        }
                    }
                }
            }

            return(value);
        }