I'm developing a WinForms application for 2 clients. The difference between the clients are only in branding: ClientA gets LogoA.png. ClientB gets LogoB.png. I need to ship the application to them as in installer and as zip file with all executables.
I'm thinking putting the images in different resource files and compile them as satellite assemblies and on the build server, when I produce zip-file and installer, I include only ResourceA for ClientA and ResourceB for ClientB. That is the plan, but I've never done this before.
The documentation says that resource files should be identified by language and culture codes. Both of my clients will run their machines in English (en-GB or en-US). I can ignore the recommendation and call the resources by the name of clients. But would they be picked up by the application? (taking there is only one resource file and machine culture does not match the resource culture code).
Is there a better solution for that?
p.s. I know about compiler directives, but it is making code hacky and dirty. Possibly, in the future, clients will have different text on the screens and that is the perfect case for the resources.
You can create a separate build configuration for each company. Then you can change the .csproj file to have msbuild tasks which will replace default resource file with chosen company resources, here is example how to check current configuration in msbuild.
<PropertyGroup Condition="'$(Configuration)' == 'CompanyABuild'">
//set resource to point to company A
</PropertGroup>
<PropertyGroup Condition="'$(Configuration)' == 'CompanyBBuild'">
//set resource to point to company B
</PropertGroup>
You can add to separate resource file one for clientA another one for clientB (ClientA.resx, Clinetb.resx). Then add a config entry in your app.config file with the name of the resource to use.
Then you need to create a wrapper class which will provide you resources depending on the config value, you need to use dynamic objects and resource managers here is a sample code:
class Program
{
static void Main(string[] args)
{
var res = new CompanyAResource();
var companyResources = new global::System.Resources.ResourceManager("ConsoleApplication1.CompanyAResource", typeof(CompanyAResource).Assembly);
dynamic resources = new DynamicResources(companyResources);
string name = resources.CompanyName;
Console.WriteLine(name);
}
}
public class DynamicResources : System.Dynamic.DynamicObject
{
private ResourceManager resources;
public DynamicResources(ResourceManager resources)
{
this.resources = resources;
}
public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result)
{
result = this.resources.GetString(binder.Name);
return true;
}
}
Related
this question follows my previous question.
I have a c# ASP.NET application and i want to provide support for plugins. Plugins can be custom c# classes, javascript, html, css, images, etc.
I see no problem as long as my application is extended with c# classes because all the user has to do is create a new "class library" project in visual studio and implement the interfaces, i provide. Then build a dll out of it and upload it to my server. The plugin-developer can add static files (html, js, css, etc.) into this project as well but i found some problems with that:
Every static file i add to the plugin project gets the build action "content" and it seems i cannot read those files from my server. (see my previously answered question). I have to manually select "Embedded Resource" on each file, so it is packed with the plugin dll.
I want to support Typescript for the plugins. The Typescript compiler generates javascript files in the same directory as the typescript-files. But the javascript files are not included in the project and therefore i have to include these in the plugin project and then set the correct build action. I don't want the plugin developers to do that all the time.
If the static files have the build action "enbedded resources", then the server can pickup these files by using the assembly.GetManifestResourceNames() method. This method returns the resources as a string. The path is not separated by \ or / but with a dot instead. So i am not able to distinguish between file path (this is relevant) or filename (also relevant to pickup the correct files), because the original filename can also have dots.
So i am starting to question the "class library" project type is right for my needs. Is there a way to get around of my issues or do i have to use another project type?
Thank you for any help!
Edit: Changed the question a little bit so it is better to understand.
You could make a zip package with the plugin dll and files. NuGet also uses this mechanism. A .nupkg is also just a zip file.
I would start by looking at MEF (Managed Extensibility Framework).
MSDN information can be found here: https://msdn.microsoft.com/en-us/library/dd460648(v=vs.110).aspx
From that link you can get more information and I believe there is a tutorial as well.
Oh, for me it seems very simple.
Let the developer create the plugin freestyle and put all the additional files in a directory, let's call it extras
To implement the your interface they will need your assembly so I guess you will ship it via nuget, or just some link. No matter what the case, provide them with some powershell script what will be required to run before the final build
The script would create zip archive from the extras directory and add it to the ClassLibrary project as EmbeddedResource.
As you mentioned earlier, you can access EmbeddedResource. So all you would do is to unpack it and you would have the exact directory tree.
The best idea would be to provide project template with script included, and also the empty zip archive added as embedded resource (it will be easier to just pack the files in the script and replace the file), and pre-build action set to run the script.
Am I missing something?
What about this.
In your web application, you could add a function that loop into your plugin directory and find DLL implementing an Iplugin (name is up to you) interface.
The interface is defined in a class library that both your web application and plugins have to implement.
You can use the Httpcontext Server mappath to read javascript and other files.
Here is a very basic implementation
First, you have the plugin interface (a class library implemented both by the web application and the individual plugins) I implemented sample properties and methods...
using System.Web;
public interface IPlugin
{
string Name { get; set; }
string Output { get; set; }
void Load(ref httpcontext Context);
void Dispose();
void Display();
}
Next, you have the Actual plugin class library we want to implement.
using System.Web;
using IPlugins;
public class AwesomePlugin : IPlugins.IPlugin
{
private string _Name = "AwesomePlugin";
private HttpContext _Context;
public string Name {
get { return _Name; }
set { _Name = value; }
}
public string Output {
get { return "Yay !!!"; }
set {
throw new NotImplementedException();
}
}
public void Display()
{
throw new NotImplementedException();
}
public void Dispose()
{
throw new NotImplementedException();
}
public void Load(ref Web.HttpContext Context)
{
}
}
Finally, you dynamically load your plugins so you can use them in your application.
private Dictionary<string, IPlugins.IPlugin> _Plugins = new Dictionary<string, IPlugins.IPlugin>();
public void LoadPlugins()
{
lock (static_LoadPlugins_IpluginType_Init) {
try {
if (InitStaticVariableHelper(static_LoadPlugins_IpluginType_Init)) {
static_LoadPlugins_IpluginType = typeof(IPlugins.IPlugin);
}
} finally {
static_LoadPlugins_IpluginType_Init.State = 1;
}
}
string ServerPath = HttpContext.Current.Server.MapPath("~") + "Plugins";
dynamic Plugins = io.Directory.GetFiles(ServerPath);
foreach (string PluginPath in Plugins) {
dynamic Assembly = system.Reflection.Assembly.LoadFile(PluginPath);
Type PluginClass = Assembly.GetTypes.Where(T => T.GetInterface("IPlugin") != null).First;
IPlugins.IPlugin MyPlugin = Activator.CreateInstance(PluginClass);
MyPlugin.Load(httpcontext.Current);
_Plugins.#add(PluginClass.ToString, MyPlugin);
}
}
static bool InitStaticVariableHelper(Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag flag)
{
if (flag.State == 0) {
flag.State = 2;
return true;
} else if (flag.State == 2) {
throw new Microsoft.VisualBasic.CompilerServices.IncompleteInitialization();
} else {
return false;
}
}
That way, you can implement whatever you want in your plugin.
I believe you could load your plugins in a separate appdomain with restricted permissions to everything.
The files (Javascript / CSS / Html) should be available by accessing the full path of the file.
string ServerPath = HttpContext.Current.Server.MapPath("~") + "Plugins";
If the resources is embedded into the plugin DLL, you could read the stream from the loaded assembly or let the plugin manage its own embedded files.
For question Number 2, you can use
MS Build
to change the contenttype during build process.
You have to make yourself confident with MS Build
I have a solution with a Windows Store app project and a Class Library project and I want to add Localization support.
How can I add the all the Resource files to my Class Library and use them in both my App and Class Library?
In order to avoid writing a lot of boilerplate and error prone code when you add a new resource string like:
Add it to .resw file
Add it to your Static class that provides access to the resource
Add it to each language specific .resw file (ex: en, fr, pt, etc)
You can use the following approach:
Create "Strings" folder and add there just one folder for default language (for example "en-US") in your Class Library
Add Resources.resw file to "en-US" folder with required keys/values
Install Multilingual App Toolkit
Enable MAT in VS for your Class Library (VS->Tools->Enable Multilingual App Toolkit)
Add required languages to your Class Library (VS->Project->Add Translation languages...)
Install ResW File Code Generator VS extension
Go to Resources.resw file properties and set Custom Tool to "ReswFileCodeGenerator" (you can also specify namespace in Custom Tool Namespace)
To solve issue with supported languages detection(currently generated manifest contains supported languages according to folder structure "Strings/en-US") you need to add folders for all required languages in your App library ("fr-FR", "bg-BG", etc) and put Resources.resw file with only one fake key.
Build your solution and enjoy!
With this approach all your resources are available via static class generated by ReswFileCodeGenerator and all of them work with x:uid in XAML. You don't need to care about keys synchronization between different languages. Also MAT can translate your resources for you.
Ok, I found how to do this and with a sample project found here
Basically the implementation is the following:
In the ClassLibrary create a folder named "Strings"
Inside the Strings folder create one for each language (ex: en, fr, pt, etc)
And add a Resources.resw in each of those folders with your keys/values
Now add a new Class in your ClassLibrary that has the following code(adapted to your project):
using System;
using Windows.ApplicationModel.Resources;
namespace MyClassLibraryName.Tools {
public static class LocalizationTool {
static ResourceLoader resourceLoader = null;
public static string MyStringOne {
get {
String name;
GetLibraryName("MyStringOne", out name);
return name;
}
}
private static void GetLibraryName(string resourceName, out string resourceValue) {
if(resourceLoader == null) {
resourceLoader = ResourceLoader.GetForCurrentView("MyClassLibraryName/Resources");
}
resourceValue = resourceLoader.GetString(resourceName);
}
}
}
And in your ClassLibrary or MainApp just call the following:
string text = LocalizationTool.MyStringOne;
I would like two how to do to share Resources files between 2 (or more) projects?
So, to resume, I've three project :
the development project (CF.NET) that include the resource file (with all definition).
I've two other projects that are empty BUT linking to the development projects, it's just a different build each time, so when I modify the development project, all three projects are updated too. (Modification of the csproj file.)
Question is, what about Resources files? When I try to access from the development project I get all resources but when I try from the 2 others, it throws an "MissingManifestResourceException".
Any idea how to solve this issue?
Thanks.
[EDIT]
Here is what I've done :
Create a project named "RealProject" which contains all code (including resources files)
Create a project named "LinkedProject" which contains nothing (I deleted all files into it and modify the csproj file as the following :
<ItemGroup>
<Compile Include="..\RealProject\**\*.cs" />
</ItemGroup>
So in LinkedProject directory I've only :
[Directory] bin
[Directory] obj
[File ] LinkedProject.csproj
The whole LinkedProject uses the RealProject files, it's just a different configuration build (see here to know why : C# - Code compiler for .NET & CF.NET )
Once in that configuration, I've no access to the resources files from the RealProject ...
If you need screens or more detailed explanation, just ask.
[EDIT]
With this code, it works, Resource manager isn't loaded on the good Assembly name, but it should exists a better solution !!!
Assembly ass = Assembly.ReflectionOnlyLoadFrom(#"..\..\..\RealProject\bin\Debug\RealProject.dll");
ResourceManager manager = new ResourceManager("RealProject.Properties.Resources", ass);
[Solution]
Things to check :
The LinkedProject as the same
namespace as the RealProject
Add Resources as links
Clean up all your solution
Rebuild it
Test !
Try to add the resource file as a link to the other two projects and make sure the namespaces as defined in the project file is the same.
Try adding existing file in other projects as a link.
The problem with sharing resources files between different projects is that the root namespace has to be the same in all the projects you use the same file in.
Or not.
You can get the root namespace at runtime in the *Resources.designer.cs file. Note the links in the comments to related answers. Make sure you commit this and keep an eye on it, the code-generator has a habit of overwriting it which would break its universality. I used the xml doc comments to remind me what's going on, if the code-gen obliterates it I'll see it in the commit diff.
/// <summary> Returns the cached ResourceManager instance used by this class. </summary>
/// <remarks> DO NOT commit any version of this file the tool overwrites, it will break it for other projects</remarks>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null))
{
// https://stackoverflow.com/a/1329631/492 https://stackoverflow.com/a/51978052/492
Assembly thisAssembly = typeof(/*thisClassName*/).Assembly;
// you need a class called "App", or just change the name on the next line to one you have in the root namespace
var apps = thisAssembly?.GetTypes().Where(t => t.Name == "App");
if (apps.Count() != 1)
throw new InvalidOperationException($"Too Many App classes. Count: {apps.Count()}, Apps: {apps}");
Type appType = apps.FirstOrDefault();
string ns = appType.Namespace;
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager($"{ns}.OtherNames.Spaces.thisClassName", typeof(thisClassName).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
Ive decompiled a library but when i try to run it, anything that requests something from the resource manager doesnt work properly leaving me with "{"Could not find any resources appropriate for the specified culture or the neutral culture. Make sure \"Logistics.Products.LayerPicking.Properties.Resources.resources\" was correctly embedded or linked into assembly \"LayerPicking.PBG\" at compile time, or that all the satellite assemblies required are loadable and fully signed."}"
[EditorBrowsable(EditorBrowsableState.Advanced)]
internal static System.Resources.ResourceManager ResourceManager
{
get
{
if (resourceMan== null)
{
System.Resources.ResourceManager manager = new System.Resources.ResourceManager("Logistics.Products.LayerPicking.Properties.Resources", typeof(Resources).Assembly);
resourceMan = manager;
}
return resourceMan;
}
}
It looks like the decompiling changed the name. The Resource looks like it is LayerPicking.PBG.KUKARoboter.Logistics.Products.LayerPicking.Properties.Resources - notice the "LayerPicking.PBG." - which is the name of your project.
VS.Net likes to add the default namespace of the project to the beginning of the resources when it embeds them.
So here are 2 options (you can do either one - I would recommend #1):
Change your default namespace to KUKARoboter and rename your resx files to start with Logistics (not KUKARoboter).
Search for the "KUKARoboter.Logistics string and add in your default namespace to the string so it reads like the string it is looking for "LayerPicking.PBG.KUKARoboter.Logistics"
In a .NET Win console application, I would like to access an App.config file in a location different from the console application binary. For example, how can C:\bin\Text.exe get its settings from C:\Test.exe.config?
using System.Configuration;
Configuration config =
ConfigurationManager.OpenExeConfiguration("C:\Test.exe");
You can then access the app settings, connection strings, etc from the config instance. This assumes of course that the config file is properly formatted and your app has read access to the directory. Notice the path is not "C:\Test.exe.config" The method looks for a config file associated with the file you specify. If you specify "C:\Test.exe.config" it will look for "C:\Test.exe.config.config" Kinda lame, but understandable, I guess.
Reference here: http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openexeconfiguration.aspx
It appears that you can use the AppDomain.SetData method to achieve this. The documentation states:
You cannot insert or modify system entries with this method.
Regardless, doing so does appear to work. The documentation for the AppDomain.GetData method lists the system entries available, of interest is the "APP_CONFIG_FILE" entry.
If we set the "APP_CONFIG_FILE" before any application settings are used, we can modify where the app.config is loaded from. For example:
public class Program
{
public static void Main()
{
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", #"C:\Temp\test.config");
//...
}
}
I found this solution documented in this blog and a more complete answer (to a related question) can be found here.
Use the following (remember to include System.Configuration assembly)
ConfigurationManager.OpenExeConfiguration(exePath)
You can set it by creating a new app domain:
AppDomainSetup domainSetup = new AppDomainSetup();
domainSetup.ConfigurationFile = fileLocation;
AppDomain add = AppDomain.CreateDomain("myNewAppDomain", securityInfo, domainSetup);
AppDomainSetup domainSetup = new AppDomainSetup();
domainSetup.ConfigurationFile = #"D:\Mine\Company\";
string browserName = ConfigurationManager.AppSettings["browser"];