ASP.NET HttpContext.GetLocalResourceObject() throws InvalidOperationException - asp.net

Let's say we have such site structure:
App_LocalResources
|- A.aspx.resx
|- B.aspx.resx
A.aspx
B.aspx
Now I use HttpContext.GetLocalResourceObject("~/A.aspx", "Key1") in A.aspx.cs, and it works fine.
But if I use HttpContext.GetLocalResourceObject("~/A.aspx", "Key1") in B.aspx.cs, it throws an exception:
The resource class for this page was not found. Please check if the resource file exists and try again.
Exception Details: System.InvalidOperationException: The resource class for this page was not found. Please check if the resource file exists and try again.
How can I resolve this problem? I want to read the local resources from an external page, and I don't want to read the .resx file myself. Thanks :-)
UPDATE: In my case, there're some "data.xml" files(they are in different directories, and have elements like <key name='Key1' value='value1' />), and the contents of them will be rendered as html.
But the key names in the data.xml should be localized before rendering (different data.xml contain different keys).
For example, the data.xml has such an element:
<key name='CategoryId' value='3' />
In the result html page, I want to display "Category Id = 3" for en-US culture, and "类别=3" for zh-CN culture, etc.
So I think I can create some files following the pattern "data.xml.??-??.resx" in the App_LocalResources folder, then use the HttpContext.GetLocalResource() for each data.xml to retrieve the localized key names. That way I don't need to read the xml myself. Is it possible?

That's not the way that local resources are supposed to be used. Local resources are only valid for a page or control. You should use global resources in your case.
From MSDN
Global Resource Files
You create a global resource file by putting it in the reserved folder App_GlobalResources at the root of the application. Any .resx file that is in the App_GlobalResources folder has global scope. Additionally, ASP.NET generates a strongly typed object that gives you a simple way to programmatically access global resources.
Local Resource Files
A local resources file is one that applies to only one ASP.NET page or user control (an ASP.NET file that has a file-name extension of .aspx, .ascx, or .master). You put local resource files in folders that have the reserved name App_LocalResources. Unlike the root App_GlobalResources folder, App_LocalResources folders can be in any folder in the application. You associate a set of resources files with a specific Web page by using the name of the resource file.
And could be also useful for you to check how access resources programatically
Button1.Text =
GetLocalResourceObject("Button1.Text").ToString();
Image1.ImageUrl =
(String)GetGlobalResourceObject(
"WebResourcesGlobal", "LogoUrl");
Image1.Visible = true;

As Claudio Redi recommended, use Global Resource files.
I would create one per xml file in the format of "filename.resx", so in your example, you'd name it Data.resx.
Set the "Name" in the resource to your "name" attribute and the Value equal to the translated "name".
For example, in Data.resx, you'd have Name=CategoryId, Value=Category Id. In Data.zh-CN.resx, you'd have Name=CategoryId, Value=类别.
One you have the data in the resource files, you'd probably want to create a class wraps the functionality of the XML lookup and localization for your in your application. Something like this should work:
public class Data
{
private const string fileLocation = "TODO";
public string Name{ get; set; }
public string Value{ get; set; }
private Data()
{
}
public Data( string Name )
{
// TODO: Look up the single key from XML
}
public string GetLocalizedName( CultureInfo cultureInfo )
{
return Resources.Data.ResourceManager.GetString(Name, cultureInfo);
}
public static List<Data> LoadData()
{
List<Data> dataList = new List<Data>();
// TODO: Load XML and create a list of Data objects.
return dataList;
}
}

Try the following steps:
Step 1 - Delete the temp files of your web site from
C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files
Step 2 - Clean and Rebuild your Solution.
Step 3 - Make sure that your Resource file in the App_LocalResources folder has the same name as the page that has this issue (and both App_LocalResources and the page are in the same folder).
Your App should be OK then.
http://iymbas.blogspot.com

Related

How to read ".resources" file generated by "resgen.exe"?

By using resgen.exe, I can generate the "resources" file from a txt file. I can use the "resources" file in WPF, however I am not sure how can I populate the value in "cshtml" file. Any help would be appreciated.
Design-time .resx files are compiled into binary .resources blobs within .NET assemblies that are then read with the ResourceManager class. These blobs are essentially just key/value dictionaries.
Like so:
ResourceManager res = new ResourceManager("NameOfEmbedded.resources", GetType().GetExecutingAssembly());
String localizedString = res.GetString("resourceKey");
In Visual Studio will create a strongly-typed wrapper around each (non-localized) .resx file so you don't need to remember each resource's string key and also makes it available from a static context, so all you need to do is:
String localizedString = Resources.ResourceKey;
(Assuming Resources is the name of your .resx-wrapper class)
In your .cshtml files, to render localized text, use the # syntax to render accordingly:
<p>Hello this next text is localized: #Resources.ResourceKey</p>
This is different to WPF where you would do it like this:
xmlns:r="MyNamespace.Properties"
<TextBlock Content="{x:Static r:Resources.ResourceKey}" />

How to read the Resource File using C#?

I have a web application which should be Localized to 3 languages. All the controls are taking the control text from the Resx file of that language. Now I have scenario like suppose if we have a messages,custom error messages to show for that particular culture. So for this I have created a seperate Foldere as "Resources" and created a resx as "DialogMessages.ar-IQ.resx".
How can I read the "DialogMessages.ar-IQ.resx" in C# ?
I have tried to read the file using ResxResourceReader class. Is this a correct process or any flaw exists ?
You can use ResXResourceReader and specifying the resource file location properly .
ResXResourceReader reader = new ResXResourceReader("Map path with resource file");
IDictionaryEnumerator iterator = reader.GetEnumerator();
while (iterator.MoveNext())
{
// process the collection of key value pair.
}

Asp.net mvc - get full file name of uploaded file

Is it possible to get full file name of uploaded file in asp.net mvc?
UPDATE
The data contains only the file name, but doesn't the file path! See the attached image for details.
It depends on the browser.
Most browsers (FF, Chrome, Safari) do not send this information, primarily for security reasons. However, it appears as though some versions of IE do send the full client path.
This value will be stored in the FileName property of the HttpPostedFile.
The documentation for FileName should help. It says:
FileName: The name of the client's file, including the directory path.
In the following code, postedFile.FileName will vary based on the browser. Therefore, it's important to always extract just the filename, and you might also get lucky and get the clientPath too.
public ActionResult UploadFile(HttpPostedFile postedFile) {
var clientPath = IO.Path.GetDirectoryName(postedFile.FileName);
var filename = IO.Path.GetFileName(postedFile.FileName);
... Save the file, etc ...
}

how to get the list of the images from the Application Directory

I am Developing a Web site and i need to read all the images from the images folder in the
application directory and i have to display all the images on the page can any body tell me how to read all the images from the images folder which is in my application directory.
Thanks in Advance.
This could help
https://web.archive.org/web/20210304125318/https://www.4guysfromrolla.com/articles/052803-1.aspx
To add to the answer of Mr. Disappointment, you can get a list of all the files using the command specified,
To get the path of the application using Server.MapPath.
Then getting the list of files, you can simply iterate and filter on the extensions you need.
This will get you an array of the file names in a given path:
string[] fileNames = System.IO.Directory.GetFiles(yourPath);
You can then generate URLs for them and use <img> tags written out to the response, for example something like ought to get the valid URLs:
string relativePath = Request.AppRelativeCurrentExecutionFilePath;
relativePath = relativePath.Substring(0, relativePath.LastIndexOf('/') + 1);
string requestPath = Path.GetDirectoryName(Server.MapPath(relativePath));
string[] fileNames = Directory.GetFiles(requestPath);
List<string> imageUrls = new List<string>(fileNames.Length);
foreach(var fileName in fileNames)
{
imageUrls.Add(Path.Combine(relativePath, Path.GetFileName(fileName)));
}
You could just write out the <img> items in the loop. Also, note that a call to GetFiles supplying only a path will return all available files so you might want to supply a searchPattern argument such as *.jpg.

Resource file for a Custom ASP.net control (.ascx) InvalidOperationException

I have a control containing some text which I want to get from a resx file, I thought I could just create a file called ControlName.ascx.resx but that doesn't seem to be working.
I'm using
label1.InnerText = (string)GetLocalResourceObject("default");
To get the value from the resource file but it keeps throwing up an InvalidOperation Exception.
Am I right about how resx files work or does it only work for Pages?
I have the same code working on an aspx page.
When you call GetLocalResourceObject from within a user control, you are actually calling TemplateControl.GetLocalResourceObject, which will look in the wrong place for the resource file. You need to call HttpContext.GetLocalResourceObject instead.
protected string HttpContextGetLocalResourceObjectAsString(string message)
{
string path = HttpContext.Current.Request.Path;
return (HttpContext.GetLocalResourceObject(path, message) as string);
}
Now you can do
label1.InnerText = HttpContextGetLocalResourceObjectAsString("default");
Per the documentation:
Gets a page-level resource
http://msdn.microsoft.com/en-us/library/system.web.httpcontext.getlocalresourceobject.aspx
Edit- added
It may be less work to just add the string to the web.config and grab it from there.
<configuration>
<appSettings>
<add key="LoggingSystemId" value="B2F085A9-6EC1-4CBF-AF8B-B17BFA75AD81"/>
<appSettings>
...
referenced as follows:
logger.SystemId = System.Configuration.ConfigurationManager.AppSettings["LoggingSystemId"];
Of course, you'll need a reference to the System.Configuration dll.
A year or so later, but i think this is what you're after?
var resource = HttpContext.GetLocalResourceObject(TemplateControl.AppRelativeVirtualPath, termType.ToString());
Mark answer if that's the one!

Resources