/// <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 (this.Items != null) return this.Items.GetEnumerator(); lock (_SyncLock) { // Check again to ensure we still don't have items if (this.Items != null) return this.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 = new DbResourceDataManager(); this.Items = Manager.GetResourceSet(this.cultureInfo.Name, this.baseNameField); return this.Items.GetEnumerator(); } }
/// <summary> /// Creates strongly typed classes from all global resources in the current application /// from the active DbResourceManager. One class is created which contains each of the /// resource classes. Classnames are not necessarily named with /// /// Uses the default DbResourceConfiguration.Current settings for connecting /// to the database. /// </summary> /// <param name="Namespace">Optional namespace for the generated file</param> /// <param name="FileName">Output class file. .cs or .vb determines code language</param> /// <returns>Generated class as a string</returns> public string CreateClassFromAllDatabaseResources(string Namespace, string FileName) { bool IsVb = this.IsFileVb(FileName); DbResourceDataManager man = new DbResourceDataManager(); DataTable Resources = man.GetAllResourceSets(ResourceListingTypes.GlobalResourcesOnly); StringBuilder sbClasses = new StringBuilder(); foreach (DataRow row in Resources.Rows) { string ResourceSet = row["resourceset"] as string; string Class = this.CreateClassFromDatabaseResource(ResourceSet, null, CultureInfo.InvariantCulture.TextInfo.ToTitleCase(ResourceSet), null); sbClasses.Append(Class); } string Output = this.CreateNameSpaceWrapper(Namespace, IsVb, sbClasses.ToString()); File.WriteAllText(FileName, Output ); return Output; }
/// <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) + "\\"; DbResourceDataManager Data = new DbResourceDataManager(); XmlDocument Dom = new XmlDocument(); try { Dom.Load(FileName); } catch (Exception ex) { this.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)) Data.UpdateOrAdd(Name, Value, LocaleId, ResourceSetName,Comment); 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 Data.UpdateOrAdd(Name, ResFileName, LocaleId, ResourceSetName, Comment,true); } } } return true; }
/// <summary> /// Generates Resx Files for standard non-Web Resource files /// based on the BasePhysicalPath /// </summary> /// <returns></returns> public bool GenerateResXFiles() { DbResourceDataManager Data = new DbResourceDataManager(); // 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 DataTable dtResources = Data.GetAllResources(); if (dtResources == 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 (DataRow dr in dtResources.Rows) { // Read into vars for easier usage below string ResourceId = dr["ResourceId"] as string; string Value = dr["Value"] as string; string Comment = dr["Comment"] as string; string Type = dr["Type"] as string; string TextFile = dr["TextFile"] as string; byte[] BinFile = dr["BinFile"] as byte[]; string FileName = dr["FileName"] as string; string ResourceSet = dr["ResourceSet"] as string; //ResourceSet = ResourceSet.ToLower(); string LocaleId = dr["LocaleId"] as string; LocaleId = LocaleId.ToLower(); // Create a new output file if the resource set or locale changes if (ResourceSet != LastSet || LocaleId != LastLocale) { if (xWriter != null) { //xWriter.WriteRaw("\r\n</root>"); xWriter.WriteEndElement(); xWriter.Close(); } string localizedExtension = ".resx"; if (LocaleId != "") localizedExtension = "." + LocaleId + ".resx"; //xWriter = XmlWriter.Create( this.FormatResourceSetPath(ResourceSet,LocalResources) + Loc,XmlSettings) ; XmlTextWriter Writer = new XmlTextWriter(this.FormatResourceSetPath(ResourceSet) + localizedExtension,Encoding.UTF8); Writer.Indentation = 3; Writer.IndentChar = ' '; Writer.Formatting = Formatting.Indented; xWriter = Writer as XmlWriter; 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 (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 ResourceFilePath = this.FormatResourceSetPath(ResourceSet); string ResourcePath = new FileInfo(ResourceFilePath).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(ResourcePath + "\\" + FileName, TextFile, Encode); } catch { } } else { File.WriteAllBytes(ResourcePath + "\\" + FileName, 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", 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; }
private static void AddResourceToStore(string key, object value, string resourceSet, IServiceProvider serviceProvider) { // Use custom data manager to write the values into the database DbResourceDataManager Manager = new DbResourceDataManager(); if (Manager.UpdateOrAdd(key, value, "", resourceSet, null) == -1) throw new InvalidOperationException("Resource update error: " + Manager.ErrorMessage); }
/// <summary> /// Writes a resource either creating or updating an existing resource /// </summary> /// <param name="resourceId"></param> /// <param name="value"></param> /// <param name="lang"></param> /// <param name="resourceSet"></param> /// <returns></returns> public static bool WriteResource(string resourceId, string value = null, string lang = null, string resourceSet = null) { if (lang == null) lang = string.Empty; if (resourceSet == null) resourceSet = string.Empty; if (value == null) value = resourceId; var db = new DbResourceDataManager(); return db.UpdateOrAdd(resourceId, value, lang, resourceSet, null) > -1; }
/// <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 = null; else 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 = null; else 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 = new DbResourceDataManager(); if (!data.ResourceExists(resourceKey,"",_ResourceSetName)) data.AddResource(resourceKey, resourceKey,"", _ResourceSetName, null); // add to current invariant resource set resources.Add(resourceKey, resourceKey); } } } } return value; }
/// <summary> /// Generates the Database resources for a given form /// </summary> /// <param name="ParentControl"></param> /// <param name="ResourcePrefix"></param> public void AddResourceToResourceFile(Control ParentControl, string ResourcePrefix, string ResourceSet) { if (ResourcePrefix == null) ResourcePrefix = "Resource1"; if (ResourceSet == null) ResourceSet = this.Context.Request.ApplicationPath + this.Parent.TemplateControl.AppRelativeVirtualPath.Replace("~", ""); DbResourceDataManager Data = new DbResourceDataManager(); List<LocalizableProperty> ResourceList = this.GetAllLocalizableControls(ParentControl); foreach (LocalizableProperty Resource in ResourceList) { string ResourceKey = Resource.ControlId + ResourcePrefix + "." + Resource.Property; if (!Data.ResourceExists(ResourceKey, "", ResourceSet)) Data.AddResource(ResourceKey, Resource.Value, "", ResourceSet,null); } }
/// <summary> /// Writes all resources out to the resource store. Optional flag that /// allows deleting all resources for a given culture and basename first /// so that you get 'clean set' of resource with no orphaned values. /// </summary> /// <param name="DeleteAllRowsFirst"></param> public void Generate(bool DeleteAllRowsFirst) { // DEPENDENCY HERE DbResourceDataManager Data = new DbResourceDataManager(); Data.GenerateResources(resourceList, this.cultureInfo.Name, this.baseName, DeleteAllRowsFirst); }
/// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="value"></param> public void AddMissingResource(string name, string value) { DbResourceDataManager man = new DbResourceDataManager(); // double check if it exists if (man.GetResourceObject(name, this.BaseName, string.Empty) != null) return; man.AddResource(name, value, string.Empty, this.BaseName, null); }
/// <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) { DbResourceDataManager manager = new DbResourceDataManager(); 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 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 btnFileUpload_Click(object sender, EventArgs e) { #if OnlineDemo this.ErrorDisplay.ShowError(WebUtils.LRes("FeatureDisabled")); return; #endif if (!FileUpload.HasFile) return; //FileInfo fi = new FileInfo(this.FileUpload.FileName); string Extension = Path.GetExtension(FileUpload.FileName).TrimStart('.'); // fi.Extension.TrimStart('.'); string Filter = ",bmp,ico,gif,jpg,png,css,js,txt,wav,mp3,"; if (Filter.IndexOf("," + Extension + ",") == -1) { ErrorDisplay.ShowError(WebUtils.LRes("InvalidFileUploaded")); return; } string FilePath = Server.MapPath(FileUpload.FileName); File.WriteAllBytes(FilePath, FileUpload.FileBytes); string ResourceId = txtNewResourceId.Text; // *** Try to add the file DbResourceDataManager Data = new DbResourceDataManager(); if (Data.UpdateOrAdd(ResourceId, FilePath, txtNewLanguage.Text, ResourceSet, null, true) == -1) ErrorDisplay.ShowError(WebUtils.LRes("ResourceUpdateFailed") + "<br/>" + Data.ErrorMessage); else ErrorDisplay.ShowMessage(WebUtils.LRes("ResourceUpdated")); File.Delete(FilePath); lstResourceIds.Items.Add(ResourceId); lstResourceIds.SelectedValue = ResourceId; }
/// <summary> /// The main method to retrieve a specific resource key. The provider /// internally handles resource fallback based on the ResourceSet implementation. /// </summary> /// <param name="ResourceKey"></param> /// <param name="culture"></param> /// <returns></returns> object IResourceProvider.GetObject(string ResourceKey, CultureInfo culture) { object value = this.ResourceManager.GetObject(ResourceKey, culture); // 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 && (culture == null || culture == CultureInfo.InvariantCulture) ) { // No entry there value = ""; if (DbResourceConfiguration.Current.AddMissingResources) { // Add invariant resource DbResourceDataManager Data = new DbResourceDataManager(); if (!Data.ResourceExists(ResourceKey,"",this._className)) Data.UpdateOrAdd(ResourceKey,"*** Missing","",this._className,null); } } return value; }
/// <summary> /// The main method to retrieve a specific resource key. The provider /// internally handles resource fallback based on the ResourceSet implementation. /// </summary> /// <param name="resourceKey"></param> /// <param name="culture"></param> /// <returns></returns> object IResourceProvider.GetObject(string resourceKey, CultureInfo culture) { object value = ResourceManager.GetObject(resourceKey, culture); // 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 && (culture == null || culture == CultureInfo.InvariantCulture) ) { // No entry there value = resourceKey; if (DbResourceConfiguration.Current.AddMissingResources) { lock (_SyncLock) { value = ResourceManager.GetObject(resourceKey, culture); if (value == null) { // Add invariant resource DbResourceDataManager data = new DbResourceDataManager(); if (!data.ResourceExists(resourceKey, "", _className)) data.AddResource(resourceKey, resourceKey, "", _className, null); value = resourceKey; } } } } return value; }
/// <summary> /// Manages caching of the Resource Sets. Once loaded the values are loaded from the /// cache only. /// </summary> /// <param name="cultureName"></param> /// <returns></returns> private IDictionary GetResourceCache(string cultureName) { if (cultureName == null) cultureName = ""; if (_resourceCache == null) _resourceCache = new ListDictionary(); IDictionary Resources = _resourceCache[cultureName] as IDictionary; if (Resources == null) { // DEPENDENCY HERE (#1): Using DbResourceDataManager to retrieve resources // Use datamanager to retrieve the resource keys from the database DbResourceDataManager Data = new DbResourceDataManager(); lock (_SyncLock) { if (Resources == null) { if (_resourceCache.Contains(cultureName)) Resources = _resourceCache[cultureName] as IDictionary; else Resources = Data.GetResourceSet(cultureName as string, _ResourceSetName); _resourceCache[cultureName] = Resources; } } } return Resources; }
/// <summary> /// Deletes a resource entry /// </summary> /// <param name="resourceId">The resource to delete</param> /// <param name="lang">The language Id - if empty or null deletes all languages</param> /// <param name="resourceSet">The resource set to apply</param> /// <returns></returns> public static bool DeleteResource(string resourceId, string resourceSet = null, string lang = null) { var db = new DbResourceDataManager(); return db.DeleteResource(resourceId, lang, resourceSet); }
public Dictionary<string, string> GetResourcesForId(string resourceID, string resourceSet) { DbResourceDataManager manager = new DbResourceDataManager(); var resourceStrings = manager.GetResourceStrings(resourceID, resourceSet); return resourceStrings; }
private void Load() { // RAS Modified: Read the full page path ie. /internationalization/test.aspx string ResourceSet = GetFullPagePath(); // Load IDictionary data using the DataManager (same code as provider) DbResourceDataManager Manager = new DbResourceDataManager(); this._reader = Manager.GetResourceSet("", ResourceSet); }