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.
}
Related
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}" />
I have created a iTextSharp PDF file that is created to a MemoryStream. But I now need to pass this file to the Kentico media library.
I would be grateful if anyone could show my how to do this. The code I have currently is:
//Media Library Info - takes Media Library Name and Website Name
MediaLibraryInfo libraryInfo = MediaLibraryInfoProvider.GetMediaLibraryInfo("MyLibrary", CMSContext.CurrentSiteName);
//Folder in Media Library where Item will be Inserted
string mediaLibraryFolder = folder;
//create media file info item - takes the relative path to the document, the library ID, and the folder name where the document will be located within the media library
MediaFileInfo fileInfo = new MediaFileInfo();
fileInfo.FileLibraryID = libraryInfo.LibraryID;
fileInfo.FileBinaryStream = file;
fileInfo.FileName = title.Replace(" ", "").Trim();
fileInfo.FileTitle = title;
fileInfo.FileDescription = description;
fileInfo.FileExtension = ".pdf";
fileInfo.FileMimeType = "application/pdf";
fileInfo.FilePath = String.Concat("/", folder, "/", title.Replace(" ", "").Trim(), ".pdf");
// Save media file info
MediaFileInfoProvider.ImportMediaFileInfo(fileInfo);
I keep getting database errors due to nullable columns e.g. FileSize, FileExtension, etc. Since I am using a MemoryStream I can't find a way to supply all that information.
Am I using the MediaFileInfo API incorrectly in conjunction with a MemoryStream file?
Actually, I don't think that you need to do anything that RadekM said. You can simply stream the file to disk to save it, and then call the import method you're using to import it into the media library.
For example, a Media Library called "Site Images" for the site "MySite" will have a folder on disk at /MySite/media/Site Images/. Drop your file into there (you can use sub folders if you want). At this point the file is "in" the media library, but it hasn't been imported yet, so you wont be able to use it. You can see this is true by viewing the Media Library in the CMS Desk interface. However, this file has not yet been imported into the Media Library and you should see an exclamation point inside a yellow triangle next to your new file.
So after you get the file in the right location, you can use that file information to populate the MediaFileInfo object and Import the file.
Could you adapt this code and pass the bytes of the PDF from here?
programmatically adding files to the Kentico Media Library
Regrettably, MemoryStream class does not contain these informations, so you can’t gain them from this object directly. Anyway, if you want to supply FileSize property, you can use ms.Length property as a workaround. Basically, this particular property is not important, so it can be even some dummy number.
As for extension – are you saying that you are receiving error saying this property is null, although you set it like „fileInfo.FileExtension = ".pdf";“? Can you clarify?
Also please note that you need to set some other properties, FileSiteID, FileCreatedWhen, FileGUID and FilePath (path inside given media library). If you have full source code of Kentico API, you can get an inspiration from constructor of MediaFileInfo object in \MediaLibrary\MediaFileInfo.cs class.
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
In my project I want to rename the file before it is updating. For example a file in my system like Mycontact.xls. I want to rename it as sasi.xls (it is an excel file). How can I write the code in ASP.NET?
Actually I am using a fileupload control to get the file in and rename the file and upload the renamed file in a folder which is in Solution Explorer.
You can do it with the File.Move method eg:
string oldFileName = "MyOldFile.txt";
string newFileName = "MyNewFile.txt";
File.Move(oldFileName, newFileName);
C# does not provide a file rename function, unfortunately. Anyhow, the idea is to do this:
File.Copy(oldFileName, NewFileName);
File.Delete(oldFileName);
You can also use - File.Move.
Be aware that when that code executes, the owner of the file will turn into the identity you have set on your Application Pool on which the website is running.
That account might not have enough permissions to 'create new' or 'delete' files.
I would advise you to place all read/writable files in a seperate location so you can control the security settings seperately on that part. This will also split off the 'only readable files/executables' (like the aspx and such) from the 'read/writable' files.
I am creating an xml file. I need to check first if the file exists or not. If the file does not exist, create it and add the data cmg from a .cs file.
If the file exists, don't create the file just add the data cmg from a .cs file.
My code looks like this:
string filename="c:\\employee.xml";
XmlTextWriter tw=new XmlTextWriter(filename,null);//null represents
the Encoding Type//
tw.Formatting=Formatting.Indented; //for xml tags to be indented//
tw.WriteStartDocument(); //Indicates the starting of document (Required)//
tw.WriteStartElement("Employees");
tw.WriteStartElement("Employee","Genius");
tw.WriteStartElement("EmpID","1");
tw.WriteAttributeString("Name","krishnan");
tw.WriteElementString("Designation","Software Developer");
tw.WriteElementString("FullName","krishnan Lakshmipuram Narayanan");
tw.WriteEndElement();
tw.WriteEndElement();
tw.WriteEndDocument();
tw.Flush();
tw.Close();
so next time we add data to file we need to check if the file exits and add data to xml file
and as we have made empID as a primary key, if user tries to make duplicate entry we need to avoid
Is this possible to do?
if (!File.Exists(filename))
{
// create your file
}
or
if (File.Exists(filename))
{
File.Delete(filename);
}
// then create your file
File class is in System.IO namespace (add using System.IO; to your file)
You can't append records to an XML file, you have to read the file and then rewrite it.
So, just check if the file exists, and read the records from it. Then write the file including all previous records and the new record.
Have a look at the File.Exists method here
Testing for existance of a file before attempting to create it inherently is subject to a "things change after check" race condition. Who can guarantee you that your application isn't preempted and put to sleep for a moment after you checked, someone else creates/deletes that file, your app gets to run again and does exactly the opposite of what you intended ?
Windows (as well as all UN*X variants) supports file open/create modes that allow to perform that create-if-nonexistant/open-if-existant operation as a single call.
As far as .NET goes, this means for your task (create an XML file) you'd first create a System.IO.FileStream with the appropriate modes, see http://msdn.microsoft.com/en-us/library/system.io.filemode.aspx and then pass that stream to the XmlWriter constructor. That's safer than simply performing an "exists" check and hoping for the best.