MS Visual Studio, C#.
I need to locate all localized resource files into the .\resource subdirectory. I can't to use the probing XML element of config-file, i.e. my really project is dll (it will loaded in the external application and located not in the hosted application directory). I try to use the AppDomain.ResourceResolve event but I get a problem...
Now I wrote "Hello World" for showing it:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Threading;
namespace HelloWorld {
class Program {
static void Main(string[] args) {
AppDomain domain = AppDomain.CurrentDomain;
Thread thread = Thread.CurrentThread;
thread.CurrentUICulture = new CultureInfo("en");
domain.ResourceResolve += domain_ResourceResolve;
ResourceManager res = new ResourceManager(typeof(Program));
Console.WriteLine(res.GetString("Message"));
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
res.ReleaseAllResources();
}
static System.Reflection.Assembly domain_ResourceResolve(object sender,
ResolveEventArgs args) {
Assembly assembly = typeof(Program).Assembly;
String name = Path.Combine(Path.GetDirectoryName(assembly.Location),
String.Format("resources\\en\\{0}.resources.dll", Path.GetFileNameWithoutExtension(
assembly.Location)));
if (!File.Exists(name)) {
Console.WriteLine("'{0}' file not found.", name);
return null;
}
else {
Assembly result = Assembly.LoadFrom(name);
if (result != null)
Console.WriteLine("'{0}' loaded.", name);
return result;
}
}
}
}
The Program.resx is not exists i.e. if it exists the ResourceResolve event is not occur. Exist the Program.en.resx and Program.ru.resx files also. In the properties of my project I set the post-build event:
rmdir .\resources /S /Q
mkdir .\resources
move .\en .\resources\en
move .\ru .\resources\ru
My localized resource was found and loaded successfully, but I get an exception (look the screen)...
My "Hello World" project attached also: sources.
If I register my event handler on the AppDomain.AssemblyResolve instead of the AppDomain.ResourceResolve it works successful, but the AppDomain.AssemblyResolve generate twice in this case (I don't know why). This decision was found by #Josser - thank you. So problem is solved. If anybody knows why the AppDomain.ResourceResolve don't working in my case, and why the AppDomain.AssemblyResolve generate twice - I will be grateful for the explanation.
Try to use a different constructor:
ResourceManager res = new ResourceManager("Program", typeof(Program).Assembly);
Related
I am trying to determine whether a C# assembly is a GUI or a Console application in order to build a tool which will automatically recreate lost short cuts.
Currently, I have a routine which recursively steps all directories in Program Files (and the x86 directory).
For each EXE it finds, the tool calls IsGuiApplication, passing the name of the EXE.
From there, I create an Assembly object using LoadFrom.
I want to check whether this assembly is has a GUI output, but I'm unsure how to test this in C#.
My current idea is to use GetStdHandle, but I'm not sure how to apply this to an assembly outside of the running application.
My experience with reflection in C# is limited, so any help would be appreciated.
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace BatchShortcutBuild
{
class Program
{
//I'm uncertain that I need to use this method
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetStdHandle(int nStdHandle);
static void Main(string[] args) {
BuildShortcuts();
Console.ReadLine();
}
public static void BuildShortcuts() {
String dirRoot = "C:\\Program Files\\";
processRoot(dirRoot);
dirRoot = "C:\\Program Files (x86)\\";
processRoot(dirRoot);
Console.WriteLine("Finished enumerating files");
Console.ReadLine();
}
public static void processRoot(String path) {
try {
foreach (String theDir in Directory.EnumerateDirectories(path)) {
processRoot(theDir);
}
foreach (String theFile in Directory.EnumerateFiles(path, "*.exe")) {
if (IsGuiApplication(theFile)) {
//I would generate a shortcut here
}
}
} catch { }
}
public static bool IsGuiApplication(String filePath) {
Console.WriteLine(filePath);
Assembly a = Assembly.LoadFrom(filePath);
//How to get the program type from the assembly?
return false;
}
}
}
Just to be safe here, the method suggested by #Killany and #Nissim suggest is not 100% accurate, as console applications can reference the System.Windows.* dlls (either by mistake or by a need of other functionality given by the 'System.Windows' assembly).
I'm not sure a 100% method exist, as some applications can be given a parameter to run with/without ui (i.e. silently)
As several times mentioned before, you can read the Subsystem Field.
private PEFileKinds GetFileType(string inFilename)
{
using (var fs = new FileStream(inFilename, FileMode.Open, FileAccess.Read))
{
var buffer = new byte[4];
fs.Seek(0x3C, SeekOrigin.Begin);
fs.Read(buffer, 0, 4);
var peoffset = BitConverter.ToUInt32(buffer, 0);
fs.Seek(peoffset + 0x5C, SeekOrigin.Begin);
fs.Read(buffer, 0, 1);
if (buffer[0] == 3)
{
return PEFileKinds.ConsoleApplication;
}
else if (buffer[0] == 2)
{
return PEFileKinds.WindowApplication;
}
else
{
return PEFileKinds.Dll;
}
}
}
Use GetReferencedAssemblies() to get all referenced assemblies and look for the system.windows.forms assembly
AssemblyName[] referencedAssemblies = assm.GetReferencedAssemblies();
foreach (var assmName in referencedAssemblies)
{
if (assmName.Name.StartsWith("System.Windows"))
//bingo
}
A basic idea to detect GUI apps is that GUI apps always use assembly System.Windows.*.
bool isGui(Assembly exeAsm) {
foreach (var asm in exeAsm.GetReferencedAssemblies()) {
if (asm.FullName.Contains("System.Windows"))
return true;
}
return false;
}
This will detect all .NET applications that are windows forms, or even WPF
One thing you could check is the .subsystem of the file's PE header. If you open up the file in ILDASM and check the manifest, you'll see this if it uses the Windows GUI subsystem:
I don't think there's any method in the Assembly class to check this, so you'll probably need to check the file itself.
Another way to check would be to go through the types in the assembly and see if any of them derive from System.Windows.Forms.Form (Windows Forms) or System.Windows.Window (WPF):
private static bool HasGui(Assembly a)
{
return a.DefinedTypes
.Any(t => typeof(System.Windows.Forms.Form).IsAssignableFrom(t) ||
typeof(System.Windows.Window).IsAssignableFrom(t));
}
Note that you'll need to add references to System.Windows.Forms.dll and PresentationFramework.dll to gain access to these types.
You can use Assembly.LoadFrom(string) to load the assembly. I tested this method myself and it seemed a bit slow so perhaps you can make it faster by involving Parallel.ForEach.
I'm trying to load dll libraries during runtime using the following code so that I don't have to provide the user with lot of dll files along with the main executable file. I have inlude all the dll files as an embedded resource and also in the reference part I have include them and have set the CopyLocal property to false. But the problems here are:1. All the dll are getting copied to Bin\Debug folder2. I'm getting FileNotFoundException.I did lot of searches to get these things resolved and finally I'm here. I got a similar code here but still couldn't do anything. What should I do to prevent this exception...??
Is there a better way to do the same thing for a Windows Form Application(Not WPF)...??
using System;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using System.Reflection;
using System.Collections.Generic;
using System.IO;
namespace MyNameSpace
{
static class Program
{
static int cnt;
static IDictionary<string, Assembly> assemblyDictionary;
[STAThread]
static void Main()
{
AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;
if (cnt != 1)
{
cnt = 1;
Assembly executingAssembly = Assembly.GetExecutingAssembly();
string[] resources = executingAssembly.GetManifestResourceNames();
foreach (string resource in resources)
{
if (resource.EndsWith(".dll"))
{
using (Stream stream = executingAssembly.GetManifestResourceStream(resource))
{
if (stream == null)
continue;
byte[] assemblyRawBytes = new byte[stream.Length];
stream.Read(assemblyRawBytes, 0, assemblyRawBytes.Length);
try
{
assemblyDictionary.Add(resource, Assembly.Load(assemblyRawBytes));
}
catch (Exception ex)
{
MessageBox.Show("Failed to load: " + resource + " Exception: " + ex.Message);
}
}
}
}
Program.Main();
}
if (cnt == 1)
{
cnt = 2;
System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest;
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args)
{
AssemblyName assemblyName = new AssemblyName(args.Name);
string path = assemblyName.Name + ".dll";
if (assemblyDictionary.ContainsKey(path))
{
return assemblyDictionary[path];
}
return null;
}
}
}
If I'm using something unnecessarily in my code then you can show me the right way...
I'm a student working on Windows Form Application v4.0 project for my papers to be submitted.
If it is still the case that you must do this, then use this OnResolveAssembly method. There is no need to preload them into an array if you don't want to. This will load them the first time they are actually needed.
Then just:
add the some.assembly.dll file to the project.
probably not a reference to the project's output
but the file that is the result of the DLL project.
mark it as a Resource in the file properties.
// This function is not called if the Assembly is already previously loaded into memory.
// This function is not called if the Assembly is already in the same folder as the app.
//
private static Assembly OnResolveAssembly(object sender, ResolveEventArgs e)
{
var thisAssembly = Assembly.GetExecutingAssembly();
// Get the Name of the AssemblyFile
var assemblyName = new AssemblyName(e.Name);
var dllName = assemblyName.Name + ".dll";
// Load from Embedded Resources
var resources = thisAssembly.GetManifestResourceNames().Where(s => s.EndsWith(dllName));
if (resources.Any())
{
// 99% of cases will only have one matching item, but if you don't,
// you will have to change the logic to handle those cases.
var resourceName = resources.First();
using (var stream = thisAssembly.GetManifestResourceStream(resourceName))
{
if (stream == null) return null;
var block = new byte[stream.Length];
// Safely try to load the assembly.
try
{
stream.Read(block, 0, block.Length);
return Assembly.Load(block);
}
catch (IOException)
{
return null;
}
catch (BadImageFormatException)
{
return null;
}
}
}
// in the case the resource doesn't exist, return null.
return null;
}
-Jesse
PS: This comes from http://www.paulrohde.com/merging-a-wpf-application-into-a-single-exe/
Try the following:
For each .dll resource:
If the file allready exists on the AppDomain.Current.BaseDirectory then continue to the next resource
Else save the resource to the AppDomain.Current.BaseDirectory. Do this in a try-catch and if it fails, notify the user. For this step to complete successfully you will need write access on the installation folder (usually a subfolder of "Program Files"). This will be solved by running the program as an administrator the first time only ao that the files are written on the file system.
Ιf the assemblies are referenced by your VS project then you do not have to load them yourself. To understand why this work's you will need to understand how assemblies are located by the CLR.
Else you will need to load each assembly yourself using one of the Assembly.Load that take either a string or and AssemblyName as a parameter.
I have this console type thing that accepts a line of C# code, wraps it up in some surrounding code and compiles it into an assembly. Then, I invoke the method from that assembly, output the result and that's it.
The problem is, the assembly needs to have a name so I can set it as a friend assembly so it could access the non-public classes. I named it "console".
Everything worked as expected but the problem is that I can't run a second script after one has finished because the file named "console" already exists in the directory and can't be overwritten.
I've tried Disposing of everything that has a Dispose method. I've tried manually deleting the file with File.Delete. Nothing helped.
So here's the code I'm using. I hope someone can help me.
CSharpCodeProvider provider = new CSharpCodeProvider();
var param = new CompilerParameters();
param.GenerateInMemory = false;
param.GenerateExecutable = false;
param.OutputAssembly = "console";
param.ReferencedAssemblies.Add("System.dll");
param.ReferencedAssemblies.Add("System.Core.dll");
param.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
var results = provider.CompileAssemblyFromSource(param,
#"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FireflyGL
{
class DebugConsole
{
static void Run(StringWriter writer)
{
var stdOut = Console.Out;
Console.SetOut(writer);
" + input.Text + #"
Console.SetOut(stdOut);
}
}
}");
if (results.Errors.HasErrors)
{
for (int i = 0; i < results.Errors.Count; ++i)
{
PushText(results.Errors[i].ErrorText);
}
}
else
{
try
{
var writter = new StringWriter();
results.CompiledAssembly.GetType("FireflyGL.DebugConsole").GetMethod("Run", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, new object[] { writter });
PushText(writter.ToString());
history.Add(input.Text);
currentHistory = history.Count;
input.Text = "";
writter.Dispose();
}
catch (Exception)
{
}
}
provider.Dispose();
File.Delete(results.CompiledAssembly.Location);
You have to unload the assembly to get rid of all the references. Unfortunately, you can't do that. You can however unload an AppDomain and provided you reference your assembly in that AppDomain, it will be unloaded as well.
If you don't care about creating a memory leak, you could also just create unique names for your assembly (console1, console2 etc.)...
I think I found a bug. In my opinion Process.Start runs wrong directory.
To test, create default console application template and paste following:
using System;
using System.Diagnostics;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
bool test = false;
DirectoryInfo root = Directory.CreateDirectory(
System.IO.Path.Combine(Directory.GetCurrentDirectory(), "folder"));
DirectoryInfo bug = Directory.CreateDirectory(
System.IO.Path.Combine(root.FullName, "bug"));
DirectoryInfo bugDotCom = Directory.CreateDirectory(
System.IO.Path.Combine(root.FullName, "bug.com"));
ProcessStartInfo bugPSI = new ProcessStartInfo(bug.FullName);
ProcessStartInfo bugDotComPSI = new ProcessStartInfo(bugDotCom.FullName);
if (test)
{
Console.WriteLine(bug.FullName);
Process.Start(bugPSI);
}
else
{
Console.WriteLine(bugDotCom.FullName);
Process.Start(bugDotComPSI);
}
Console.ReadKey();
}
}
}
when variable test is set to false, bug.com directory should be opened, otherwise bug directory. However, this example shows that always bug.com is opened (no matter to test variable) - at least for me.
What's wrong? I'm missing something or that's just a bug?
.com is part of %PATHEXT%, so Windows will use it if it exists.
Changing the extension so that there is no bug.com folder avoids the problem.
To fix the problem, add a \ to the end of the path.
Moving files to the recycle bin and emptying the recycle bin are well documented, but how can a file be programmatically restored from the recycle bin?
There seems not to be a solution in pure C#. You most likely have to resort to P/Invoke.
This article presents a solution in C++ using the SHFileOperation API.
The only other reference to this beyond the previously mentioned link to codeproject that I can see mentions this:
Call SHGetFolderLocation passing CSIDL_BITBUCKET.
Then you can manipulate that folder as usual.
You'll have to create an interop for the SHGetFolderLocation function.
CSIDL_BITBUCKET being the CSIDL ("constant special item ID list") value for the virtual Recycle Bin folder. The quote is taken from here, and will involve interop with the Windows shell. MSDN also mentions that this function has been deprecated in favour of another in Vista.
Hope below code will work to restore the files. Please make sure, STA Calls only supported for shell calls
using System;
using System.Collections;
using System.Windows.Forms;
using System.IO;
using Shell32; //Reference Microsoft Shell Controls And Automation on the COM tab.
using System.Runtime.InteropServices;
using Microsoft.VisualBasic.FileIO;
using System.Threading;
private static void Restore(object param)
{
object[] args = (object[])param;
string filename = (string)args[0];
string filepath = (string)args[1];
Shl = new Shell();
Folder Recycler = Shl.NameSpace(10);
var c = Recycler.Items().Count;
var _recycler = Recycler.Items();
for (int i = 0; i < _recycler.Count; i++)
{
FolderItem FI = _recycler.Item(i);
string FileName = Recycler.GetDetailsOf(FI, 0);
if (Path.GetExtension(FileName) == "") FileName += Path.GetExtension(FI.Path);
//Necessary for systems with hidden file extensions.
string FilePath = Recycler.GetDetailsOf(FI, 1);
if (filepath == Path.Combine(FilePath, FileName))
{
DoVerb(FI, "ESTORE");
break;
}
}
}
private static bool DoVerb(FolderItem Item, string Verb)
{
foreach (FolderItemVerb FIVerb in Item.Verbs())
{
if (FIVerb.Name.ToUpper().Contains(Verb.ToUpper()))
{
FIVerb.DoIt();
return true;
}
}
return false;
}