How to create resx files - c#

I am trying to use Icons in a windows form application. I read that you can use resx files to do this. (I also read that resx files can be used for localization but this is not the point of this question)
I know more or less how to use a resx file if I have one(see below). What I don't know and I can't find anywhere is how to create these resx files (I know what these files are already)
Can someone teach me how to create a resx file that holds information on icons non-programmatically (the few responses about this in SO are programmatical ones)
The objective is to have a "resource.resx" file in my project that holds data about a "myicon.ico" file.
I am planning to use this as in
ResourceManager rm = new ResourceManager("resource",
typeof(Resource).Assembly);
Object ret= rm.GetObject("something");
if(ret!=null && ret is Icon)
return (Icon)ret;
else
return null;
Please don't point me to this link since I have already read it and could not find a practical way to do what I asked.

Assuming you're using Visual Studio:
Right-click your project
Select Add | New Item
Select Resources File
Give it a name (e.g. Resources)
Click Add
You will now have a Resources file in your project with the name you provided, and it should auto-open the resources editor. If it doesn't, double-click it in the project.
In the top-left of the editor, click the "Strings v" drop down and select "Icons".
Drag your icon into this screen.
Rename it to whatever you want (e.g. something).
If you named your resources file "Resources", you should be able to access the icon like so:
Object ret = Resources.ResourceManager.GetObject("something");
if (ret != null && ret is Icon)
return (Icon)ret;
else
return null;

Related

Making GTK# File Chooser to Select File Only

Im using GTK# FileChooserDialog widget.The problem is that even though the widget is named file chooser you can select folders with it and it returns folder names also.
Is there any way by which i can restrict it to choosing only files? I have checked almost class all properties i could not find any.
you can restrict the action by defining its Action-Property in the constructor
private void OpenOFD()
{
Gtk.FileChooserDialog filechooser =
new Gtk.FileChooserDialog("Choose the file to open",
this,
FileChooserAction.Open,
"Cancel",ResponseType.Cancel,
"Open",ResponseType.Accept);
if (filechooser.Run() == (int)ResponseType.Accept)
{
System.IO.FileStream file = System.IO.File.OpenRead(filechooser.Filename);
file.Close();
}
filechooser.Destroy();
}
There are 4 FolderChooserActions:
CreateFolder: Indicates a mode for creating a new folder. The chooser will let the user name an existing or new folder
Open: Will only pick an existing file
Save: Will pick an existing file or type in a new filename
SelectFolder: Pick an existring folder
According to the documentation, that behavior depends on the Action property:
If it is set to FileChooserAction.Open or FileChooserAction.Save, only files can selected.
If it is set to FileChooserAction.SelectFolder or FileChooserAction.CreateFolder, only folders can be selected.

StreamReader Null Reference Exception

Im trying to read SQL statement from .SQL files in a resource folder,
I have 2 .SQL files right now and it reads one correctly and the other returns a NullRefrenceException
Here is my calling of the sql files:
string sqlFailRecordNoMatch = EmbeddedResource.GetString("Resources.SQLScripts.RecordNumberFailQuery.sql");
Here is the GetString method:
public static string GetString(System.Reflection.Assembly assembly, string name)
{
System.IO.StreamReader sr = EmbeddedResource.GetStream(assembly, name);
string data = sr.ReadToEnd();
sr.Close();
return data;
}
The only reason you would get a NullReferenceException on one vs. the other is:
The one that's failing isn't set as an Embedded Resource. You can check that by clicking on the file in the Solution Explorer and hitting F4.
You're using the wrong fully qualified path.
I suspect it's #1.
It would be much easier if you simply use the resource editor from Visual Studio:
Within your project create a new folder (maybe called Queries)
Right click this folder and select Add - New Item
In the dialog just select Textfile and give it the name about what this query will do
Make sure you replace the file extension from .txt to .sql
Just put your statement right into this file
In the Resource Editor add this file as a resource (normally located in your project under the properties folder or simply also create it by Add - New Item - Resources File)
Now you can access this sql statement within your code just by using Properties.Resources.MySqlStatement

.resx form icon cascade updates

Suppose that we have a Windows Form, Form1, for which we have set an icon. Visual Studio will store the icon in Form1.resx ($this.Icon).
Now we decide to localize the application into N languages, so we set Localizable to True, we pick the first language from the Language option, we translate the texts and we continue with the next language repeating the procedure (pick another and translate) up to N. The result will be N .resx files containing the $this.Icon entry with the original icon.
Then we realize we want to update the form icon, so we set Language to "(Default)" and we set the new icon. To our surprise, we discover that the N .resx files were not updated.
Do we have to update the N .resx files manually? Is there something like cascade updates? What would you do in this case to avoid updating N icons?
I just added code to my Program.Main to modify all solution .resx files to remove Form.Icon.
try
{
string solutionDirPath = #"path\to\solution";
string[] resxFilePaths = Directory.GetFiles(solutionDirPath, "*.resx", SearchOption.AllDirectories);
foreach (string resxFilePath in resxFilePaths)
{
XDocument xdoc = XDocument.Load(resxFilePath);
var iconElement = xdoc.Root.Elements("data").SingleOrDefault(el => (string)el.Attribute("name") == "$this.Icon");
if (iconElement != null)
{
iconElement.Remove();
xdoc.Save(resxFilePath);
}
}
}
catch (Exception ex)
{
}
finally
{
}
And my bin size reduced almost twice!
Also for all forms I just will use icon from my app executable
Icon.ExtractAssociatedIcon(Application.ExecutablePath)
Honestly there is no reason to have the same icon in every resx.
ResX files cascade based on language, from the most specific language resource to the least.
If you remove the icon from all your resx files excepting your default, that icon will always be used.
If you wanted a different icon for a particular language, you would simply add the different icon to that resx file.
You can see this easily yourself. Add a label to your form, and populate it based on the value of a key called 'test' (You can do this with a call to 'GetLocalResourceObject("test")' in your code).
Add the key-value pair 'test'-'Hello' to your resx file. Let's say your resx is called 'foo.resx'. In a language-specific file (such as 'foo.fr.resx') add 'test'-'Bonjour'. If you run your program in any non-French language, you will see 'Hello', but if you switch to French you will see 'Bonjour'.
It will work the same way with your icon - you can set it in the base resx, and it will show up for every language. You can then override it in a different resource file.

Use a ShellFile object using Windows API Code Pack for Microsoft

Windows API Code Pack for Microsoft can be downloaded from here. That is a really nice library and it has great examples. For example if I open the solution WindowsAPICodePack10 that comes in the zip from downloading the code pack (it only contains the libraries I added a win forms and wpf application)
then I am able to use the library very easily for example in my wpf application I can drag:
ExplorerBrowser user control (note I have to add references to the libraries that came with the solution)
and then with a button I can populate that control with this lines of code:
// Create a new CommonOpenFileDialog to allow users to select a folder/library
CommonOpenFileDialog cfd = new CommonOpenFileDialog();
// Set options to allow libraries and non filesystem items to be selected
cfd.IsFolderPicker = true;
cfd.AllowNonFileSystemItems = true;
// Show the dialog
CommonFileDialogResult result = cfd.ShowDialog();
// if the user didn't cancel
if (result == CommonFileDialogResult.Ok)
{
// Update the location on the ExplorerBrowser
ShellObject resultItem = cfd.FileAsShellObject;
explorerBrowser1.NavigationTarget = resultItem;
//explorerBrowser1.Navigate(resultItem);
}
and after that I am able to have something like:
That is amazing but I don't understand Microsoft. If they give you those libraries they should make it easy to customize that user control. the reason why I downloaded those libraries is because I need to place files from a specific directory on a stackpanel and be able to have the same functionality that you get with files on explorer (able to drag files, get context menu when right clicking file, dropping files to that container etc)
anyways I don't need all that functionality. from studing the library I think that user control contains a ShellContainer object and it's childern are ShellFiles maybe.
So from this library I will like to create a ShellFile object and place it in a StackPanel. after tedious studing of the library I finally found out how to instantiate an object from shellFile (ShellFile class is abstract) :
string filename = #"C:\Program Files (x86)\FileZilla FTP Client\filezilla.exe"; \\random file
ShellFile shellFile = ShellFile.FromFilePath(filename);
now it will be nice if I could place that file in a container. I am not able to instantiate a ShellConteiner object becaue it is abstract too. so how Will I bee able to place that shell file on a canvas for example?
or maybe I could extract the properties that I need and create a user control that will represent a shellFile. I know how to get the thumbnail I can do something like:
string filename = #"C:\Program Files (x86)\FileZilla FTP Client\filezilla.exe";
ShellFile shellFile = ShellFile.FromFilePath(filename);
System.Drawing.Bitmap btm = shellFile.Thumbnail.ExtraLargeBitmap;

OPEN a Resource.resx file instead of Creating it which overrides the previous Resource.resx file

I start my application from withint Visual Studio 2010.
I add then some files into my application and each file type`s icon like icon from doc,docx,xls,pdf etc are added as String/Bitmap key/value pair to my IconImages.Resx file via
private void DumpTempResourceToRealResourceFile(IDictionary<String, Bitmap> tempResource)
{
using (ResXResourceWriter writer = new ResXResourceWriter("IconImages.Resx"))
{
foreach (KeyValuePair<String,Bitmap> item in tempResource)
{
writer.AddResource(item.Key, item.Value);
}
writer.Generate();
}
}
When the icons are added to the resource I close the application.
Then I start my application again with VS 2010 and add some files within my document application. The file types are written again to my IconImages.Resx.
Then I close my application and check the IconImages.Resx file under the \bin\ folder and the previous saved images are gone and I have new/different ones now.
Why can I not say OPEN a .resx file and append stuff to it? Everytime I create a ResourceWriter object with the same name "IconImages.Resx" I overwrite the previous added stuff and thats stupid.
How can my IconImages.Resx file stay alive over an application session without being overwritten by other stuff I add?
I haven't used ResXResourceWriter, but usually *Writer classes simply write a data file from scratch.
If you want to "append" new data you would typically have to use a *Reader class to deserialise the existing data into memory, then merge/add in any new data you wish to, and use a *Writer object to then write the resulting data back out. Take a look at ResXResourceReader to see if it supports what you need to do this.
I am having now a lookup table "FiletypeImage" with the filetype ".docx" and the raw binary data aka blob. This table gets retrieved in my documentService and cached in a static variable. with a Get and Add method which are called by my DocumentListViewModel. Its very fast thx to sqlite :)

Categories