C# - Windows CE: form translation independent of OS culture settings - c#

I am writing a program in C# for a Windows CE device and would like the application to be translated according to a language setting in the application itself.
I have already read some articles about localisation using resource files and translating forms using the 'Localizable' and 'Language' properties. From what I have read I understand that this type of form translation works with the OS language setting (correct me if I am wrong).
Now I am looking for a way to do the form translation dependent on my own in-program language setting, preferably using resource files.
I have already thought of doing this translation in the Load event of each form but maybe there are other solutions or best-practice for this. Any help is appreciated.

If you use the Language.resx, Language.[language]-[country].resx way of localizing, the generated class Language will have a property named Culture that can be set to override the current system culture.
Language.Culture = new CultureInfo("sv-SE");
label1.Text = Language.my_language_string;
If you want to use the ResourceManager-class it has a member GetResourceSet() that takes a parameter CultureInfo. I haven't tried to use GetResourceSet myself but it sounds like something you could use.
ResourceManager CultureResourceManager = new ResourceManager("My.Language.Assembly", System.Reflection.Assembly.GetExecutingAssembly());
ResourceSet resourceSet = CultureResourceManager.GetResourceSet("sv-SE", true, true);
resourceSet.GetString("my_language_resource");
MSDN-link:
http://msdn.microsoft.com/en-us/library/system.resources.resourcemanager.getresourceset(v=vs.80).aspxo

If you are going to put it in the Load event, consider making a template form. Somewhere in the template form, add your localisation checks. Then, have your other forms inherit the template, and they will get the Load event by default.

Related

What's the easiest way to create a managed visualiser in C#?

I have a background in C++ and recently I started working in C#.
I have written following pieces of code (in Visual Studio):
var list_Loads = database.GetData<Load>().ToList();
var test_list = list_Loads.Where(o => (o.Name.Substring(0, 3) == "123")).ToList();
When I run the program and I move my mouse over both lists, first I get the count, which is very useful, but when I ask for the entries, this is what I get:
0 : namespace.Load
1 : namespace.Load
2 : namespace.Load
...
Not very useful, as you can imagine :-)
So my question: how can I show the Name attributes of those objects?
I thought: no problem. I have a background in native visualisers, so it should be rather easy to turn this into useful information, but then it comes:
In order to alter the way that those objects are represented, there is the first proposal to add a [DebuggerDisplay] "tag" to the definition of that class in source code.
However, as those classes are part of a framework I'm just referring to, I don't have access to the source code and hence I can't modify this.
Then I found another solution, which comes down to: "Write an entire C# project, debug, test and install it and it might work" (see documentation on "Custom visualisers of data" on the Microsoft website).
I almost choked in my coffee: writing an entire project, just for altering the view of an object??? (While, in C++, you just create a simple .natvis file, mention the classname and some configuration, launch .nvload and that's it.
Does anybody know a simple way to alter the appearance of C# object, without needing to pass through the whole burden of creating an entire C# project?
By the way, when I try to load a natvis file in Visual Studio immediate window, this is what I get:
.nvload "C:\Temp_Folder\test.natvis"
error CS1525: Invalid expression term '.'
What am I doing wrong?
Thanks in advance
OP (my emphasis):
In order to alter the way that those objects are represented, there is the first proposal to add a [DebuggerDisplay] "tag" to the definition of that class in source code.
However, as those classes are part of a framework I'm just referring to, I don't have access to the source code and hence I can't modify this.
Does anybody know a simple way to alter the appearance of C# object, without needing to pass through the whole burden of creating an entire C# project?
If you just want to specify [DebuggerDisplay] on a type, you don't have to have access to the source code. You can make use of [assembly:DebuggerDisplay()] and control how a type appears in the debugger. The only downside is that [assembly:DebuggerDisplay()] naturally only affects the current assembly whose code your mouse is hovering over. If you wish to use the customised display in other assemblies that you own, then you must repeat the [assembly:DebuggerDisplay()] definition.
Here's an easy before-and-after example with DateTime. I picked DateTime because we generally don't have access to the source code and it has some interesting properties:
var items = new List<DateTime>
{
DateTime.Now.AddDays(-2),
DateTime.Now.AddDays(-1),
DateTime.Now
};
...which on my machine defaults to:
Maybe I'm fussy and I just want to see:
Day of the week and
Day of the year
...I can do that via:
using System.Diagnostics;
[assembly: DebuggerDisplay("{DayOfWeek} {DayOfYear}", Target = typeof(DateTime))]
...which results in:
Example:
namespace DebuggerDisplayTests
{
public class DebuggerDisplayTests
{
public DebuggerDisplayTests()
{
var items = new List<DateTime>
{
DateTime.Now.AddDays(-2),
DateTime.Now.AddDays(-1),
DateTime.Now
};
}
}
.
.
.
}
Overrides
[assembly:DebuggerDisplay()] can also be used as a means to override pre-existing [DebuggerDisplay] on a 3-rd party type. Don't like what style they have chosen? Is the type showing far too much information? Change it with [assembly:DebuggerDisplay()].

Casting as a form from a window handle

My C#.NET Windows application dynamically creates a bunch of forms with no name and no borders, this works fine, however I later need to find these forms and set them to be the top most forms. My current logic is to write the myForm.Handle to a string at the time of creation so I can refer to that handle later.
And this is where it fails, when I'm ready to set it to be the top most windows, I do this:
Form myForm = Form.FromHandle(sFormHandle);
if (myForm != null) { myForm.TopMost = true; }
The sFormHandle is a string and it expects a IntPtr, how can I convert it, or do this in some other way?
Many thanks.
The Handle property on a form is an IntPtr.
Why have you stored it as a string?
The solution here is to store the handle as an IntPtr, not a string.
Better than that, if this is all .net windows forms code, why not keep a reference to the form rather than the handle?
Edit: added emphasis. Consensus from community seems to be that references to the forms should be retained and the handles should not be relied upon.
Form fr = (Form)Form.FromHandle(new IntPtr(int.Parse("0")));
and beware of direct refrence to a class...
you better try WeakRefrence because of COM class models
if you use a direct refrence to a class,
the class will not unload till all the refrences are removed!

MVVM conform localization in WPF Applications

How can I localize an WPF Application using the MVVM Pattern? I really want to do it the "right" way.
My current approach is that I use .resx Resource files to localize my application.
I included them in my xaml code
xmlns:localization="clr-namespace:ClientLibTestTool.ViewLanguages"
and access them like this:
<Button x:Name="BtnGenerate"
Content="{x:Static localization:localization.ButtonGenerate}"/>
My Questions:
Is there a better way to do it?
How can i test the different languages (load application with different language settings)?
Is it possible to change the language at runtime?
Answers:
Question 1:
Question 2: (Thank you, stijn)
public MainWindow()
{
// Debug Settings
localization.Culture = CultureInfo.GetCultureInfo("en-US");
// localization.Culture = CultureInfo.GetCultureInfo("de-DE");
this.InitializeComponent();
}
Question 3: (Thank you, stijn)
Not really, it is necessary to redraw the complete window.
This is the appropriate way to do it, as far as I'm concerned.
To switch languages, change the culture used by the localization class:
localization.Culture = CultureInfo.GetCultureInfo( "de-DE" );
Since all strings are fetched at runtime (all calls in the generated Designer.cs files look like ResourceManager.GetString( "SomeString", resourceCulture ); and resourceCulture is what gets set by the call above, this affects what you get at runtime. However supose you use the values in menu items etc from within xaml, you have to rebuild the entire menu before this takes effect.

Editing app.config in execution time using the same App

I have an Windows Forms application VS 2008 - C#, that uses app.config.
In execution time, in Menu option of my application, I want editing values of app.config, save it and restart application.
any sample source code, any good patterns and practices ??
edit:
in MSDN Forums, Jean Paul VA:
Create an test windows forms application and add an app.config into it.
Add reference to System.confguration
Add a key named "font" in appSettings with value "Verdana"
Place a button on form and on click of it add the modification code.
System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
configuration.AppSettings.Settings.Remove("font");
configuration.AppSettings.Settings.Add("font", "Calibri");
configuration.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
what you think about it ?
I don't think you can actually write to the configuration file at runtime - it may well be read-only, however, there may be a way around this by re-writing the file (with proper alterations as required) and essentially replacing the existing one, then, further, restarting the application to load the new values (I highly doubt this is desirable and personally would not try to instrument this malarkey).
You may also just consider storing application settings in the settings file which are easily manipulated in this way.
To use settings, first let's assume you have a Settings.settings file (if not then create one: Add Item->Settings File), then we have a setting configured named MyUnicornsName; In order to make a change and persist it you can simply do as follows:
Settings.Default.MyUnicornsName = "Lucifers Spawn";
Settings.Default.Save();
Similarly, to read a setting:
ATextDisplayControl.Text = Settings.Default.MyUnicornsName
In case you don't know, Visual Studio will open the settings editor when you open/double click the settings file in the IDE; using this interface you can add and edit your initial settings and their values, and string is not the only supported value, all primitives can be used, and, as far as I know, any serializable value too.
Is there any reason you can't use the usual auto-gen'd Properties.Settings to store the changing data in a settings file instead? One great thing is that you know what you're changing so you don't even have to restart the application!
Using Settings in C#
Runtime access of settings is as easy as:
this.BackColor = Properties.Settings.Default.myColor;
(There is no good pattern for modifing app.config itself simply b/c it's designed to be readonly in that context, with expert-user settings.)
Use the Project->Properties->Settings for these kinds of things.
well actually the Properties in the App.config are ReadOnly so u cant do it.
But there's a trick............................
In the Settings.cs file create a Function or method that is public so that it can be available with Properties.settings
and write the following code..
public void ChangeProperty(string propertyname, string value)
{
this[propertyname] = value;
}
remember to pass the exact string of the property name to the method. or better create a Writeonly Property for the setting.
update
here is a code for setting as a property, i am taking a connection string as an example, bet it can be anything. remember the property stored is of Object type so you can create property specific to that..
public string MyCustomConnectionstring
{
set
{
//replace the string with your connection string otr what ever setting you want to change
this["myConnectionString"] = value;
}
}
Now you can easily use this Property to change the ConnectionString at run time...

C# property attributes

I have seen the following code:
[DefaultValue(100)]
[Description("Some descriptive field here")]
public int MyProperty{...}
The functionality from the above snippit seems clear enough, I have no idea as to how I can use it to do useful things. Im not even sure as to what name to give it!
Does anyone know where I can find more information/a tutorial on these property attributes?
I would be also interested in any novel / useful tasks this feature can do.
The functionality from the above
snippit seems clear enough,
Maybe not, as many people think that [DefaultValue()] sets the value of the property. Actually, all it does to tell some visual designer (e.g. Visual Studio), what the code is going to set the default value to. That way it knows to bold the value in the Property Window if it's set to something else.
People have already covered the UI aspect - attributes have other uses, though... for example, they are used extensively in most serialization frameworks.
Some attributes are given special treatment by the compiler - for example, [PrincipalPermission(...)] adds declarative security to a method, allowing you to (automatically) check that the user has suitable access.
To add your own special handling, you can use PostSharp; there are many great examples of using PostSharp to do AOP things, like logging - or just code simplification, such as with automatic INotifyPropertyChanged implementation.
They are called Attributes, there is a lot of information in msdn, e.g. http://msdn.microsoft.com/en-us/library/z0w1kczw.aspx
In general they don't "do" anything on their own, they are used by some other code that will use your class. XmlSerialization is a good example: XmlSerializer (provided by Microsoft as part of the framework) can almost any class (there are a number of requirements on the class though) - it uses reflection to see what data is contained in the class. You can use attributes (defined together with XmlSerializer) to change the way XmlSerializer will serialize your class (e.g. tell it to save the data as attribute instead of an element).
The ones in your example is used by the visual designer (i.e. MS Expression Blend and Visual Studio designer) to give hints in the designer UI.
Note that they are metadata and will not affect the property logic. Setting DefaultValue for instance will not set the property to that value by default, you have to do that manually.
If you for some reason want to access these attributes, you would have to use reflection.
See MSDN for more information about designer attributes.
We use it to define which graphical designer should be loaded to configure
an instance of a specific type.
That is to say, we have a kind of workflow designer which loads all possible command
types from an assembly. These command types have properties that need to be configured,
so every command type has the need for a different designer (usercontrol).
For example, consider the following command type (called a composite in our solution)
[CompositeMetaData("Delay","Sets the delay between commands",1)]
[CompositeDesigner(typeof(DelayCompositeDesigner))]
public class DelayComposite : CompositeBase
{
// code here
}
This is information is used in two places
1) When the designer creates a list of commands, it uses the CompositeMetaData
to display more information about the command.
2) When the user adds a command to the designer and the designer creates
an instance of that class, it looks at the CompositeDesigner property,
creates a new instance of the specified type (usercontrol) and adds it
to the visual designer.
Consider the following code, we use to load the commands into our "toolbar":
foreach (Type t in assembly.GetExportedTypes())
{
Console.WriteLine(t.Name);
if (t.Name.EndsWith("Composite"))
{
var attributes = t.GetCustomAttributes(false);
ToolboxListItem item = new ToolboxListItem();
CompositeMetaDataAttribute meta = (CompositeMetaDataAttribute)attributes
.Where(a => a.GetType() == typeof(Vialis.LightLink.Attributes.CompositeMetaDataAttribute)).First();
item.Name = meta.DisplayName;
item.Description = meta.Description;
item.Length = meta.Length;
item.CompositType = t;
this.lstCommands.Items.Add(item);
}
}
As you can see, for every type in the assembly of which the name ends with "Composite",
we get the custom attributes and use that information to populate our ToolboxListItem instance.
As for loading the designer, the attribute is retreived like this:
var designerAttribute = (CompositeDesignerAttribute)item.CompositType.GetCustomAttributes(false)
.Where(a => a.GetType() == typeof(CompositeDesignerAttribute)).FirstOrDefault();
This is just one example of how you might be able to use custom attributes,
I hope this gives you a place to start.
These attributes customize the design time experience.
http://msdn.microsoft.com/en-us/library/a19191fh.aspx

Categories