How can a program change its own resources? - delphi

I would like to store some XML program preferences as a resource in a Delphi application. The resource would be modified based on user changes. I have no problem creating the XML and loading it as a resource, and can modify the xmlDocument that I load it into, but I don't know how to write the document back. Is this even possible? I would prefer not to end up with 2 files in the end (.exe and .xml).

The answer is both yes and no.
Yes, it is possible to update resources in a binary using Windows API routines. This link to BeginUpdateResource() should get you on the right track on that score.
However, you will note the following condition on the use of BeginUpdateResource():
"The binary file in which to update resources. An application must be
able to obtain write-access to this file; the file referenced by
pFileName cannot be currently executing."
In other words, it is not possible for an application to simply update it's own resources while running.
There are a number of strategies you could employ to achieve what you want - or something close enough to it as to be satisfactory. Which is most appropriate will depend on your precise needs.
Of the multitude of solutions, two might be:
1) Maintain all such resources in a DLL (resource only DLL - containing no actual code as such) which you open only when specifically loading resources (or updating them). Thus at the time you wish to write a resource back to the DLL you should be able to get the required write-lock.
or
2) When you need to update a resource rename the current running EXE to something like "myapp.OLD", copy it so that you have a new file with the current name "myapp.exe". You can then update "myapp.exe" because it is actually "myapp.old" that is executing.
This second approach is quite messy and has a "nasty smell" but is a technique that is (or used to be) quite commonly used by auto-updaters, for example. Obviously will involve a restart of your app at some point if the current running code is to make use of the updated resources in the modified EXE, so it may not be appropriate to your needs.

Something else to consider is that anti-virus software may flag the activity as suspicious.
Thinking about Deltics' answer I thought you could also create a console application that writes your resource back to the main exe. So your main exe saves it's changes to a file and also extracts the console app. When the main application terminates it calls the console app. The console app waits for a short period of time and then binds the resource file to the main executable, deletes the resource file and itself. The console app could do a check to make sure that the resource file was written successfully and, if not, leave the resource file open. The main executable could see the resource file upon start up and use it instead of the embedded file - as a safeguard.
All of this assumes a single user application.

Related

How can we integrate resource file with any translation management tool

I am working on multilingual site developed in asp.net MVC. Currently we are managing the translation task using resource (resx) file and everything is working fine.
Now as per client requirement, they want to integrate our resource file to a TMS "phrase" through a webhook. So in future, if they create any new key or modifying the existing resource file. Its automatically reflects in application resx file and it should automatically reflects on dev/test/prod environment.
As I tried to update the resource file on API call, its get modified and changes are reflected on application.
But when we modified the resx file under app_GlobalResources folder then it restarts the whole application. so this is one of drawback to use this approach. Also when we deploy our changes then it makes the dll of app_globalreources. Post deployment, unable to add new or make changes in existing translation.
Can any one suggest a best approach, which we should consider to fulfill above requirement.
Edit:-
Can we use json instead of resx file in existing application.
A common way to do translations is through database instead resource files. You save the same information in your database: language, key (the resource name) and value (the translated text).
With this focus, you must develop a way to do translations (the typical CRUD operations) and some layer to get any key in each language.
Talk with your client and check how important is this feature. I worked in a project like this some time ago and, at the end, we never do translations in this way. We add more functionality, made changes, translations and, when iteration finished, we move to production everything. Maybe not your case but it's a pity work on something that later hasn't use.

How to avoid intermittent Errno::ETXTBSY exceptions?

During part of a request in a Rails application, I copy a directory from one place to another, think of it like a working area. Sometimes this copy operation results in "Errno::ETXTBSY" exceptions being thrown. I can't seem to pin down the case that causes it, any tips to detect the case or avoid it altogether?
I've made sure the destination directory is uniquely named, so it shouldn't be a case of 2 processes attempting to write to the same place. Beyond that I'm out of ideas.
ETXTBSY means that you're trying to open for writing a file which is currently being executed as a program, or that you're trying to execute a file which is currently open for writing. Since you say you're copying files, not executing them it seems likely it's the former, not the later.
You say you're targeting a unique new destination, but my guess is that's not entirely true and you're actually targeting an existing directory and one of the files you're attempting to overwrite is currently open as an executable text segment of a running process.
You haven't posted any code, so it's hard to comment specifically. I suggest you add enough logging so you know exactly what file(s) are being processed and specifically, the source and destination path that throws the exception. Then you could use lsof to see what process may have that file open.
One way to avoid the problem if you are overwriting a currently open executable, is to first unlink the target file. The running process will still have the old inode mapped and proceed merrily using the deleted file, but your open for write will then create a new file which won't conflict.

How to put configuration information inside the executable?

If we want to store critical information, like passwords and server addresses, inside the executable file generated by the Delphi compiler, how can we do that, without knowing the final executable size and binary structure, like at the end of the file for example?
Side note:
The text to be stored is already encrypted; and in some computers the windows don't give access to write in the registry, specially when the user is not administrator, and there are hacks to monitor registry changes and the smart user can find the new windows registry entry.
Comment
Why this question was down voted? This is achievable! Doesn't meter if not interesting for most people.
I think about the bios and other firmware upgradeable, like satelite tv signal decoders that update themselves. How is that possible?
You can use an .rc file to put your data into a custom resource inside the final .exe file. You can then access that resource at run-time, such as with a TResourceStream, and decrypt and use its content as needed. However, you cannot write new data into the resource while the .exe is running, as the file is locked by the OS. If you need to write new settings, and do not have write access to the Registry, you will have to use a separate file instead. Windows has special folders set aside that users have write access to within their user profiles.
Create a string table resource is one way.
Create a text file. say secretstuff.rc (has to have .rc extension)
with something like this in it.
STRINGTABLE
{
1,"This is my encrypted password in say Base64"
}
Compile it to a .res file with BRCC32.
Include it in the relevant code with a compiler directive
{$R secretstuff.res}
After that you access with TResourceStream.
If you want to manage it a bit better might be wise to stuff them in a dll instead of an exe, then you can update things by delivering a new version of the dll.
There's an example with a it more detail, another purpose but same principle here

How to migrate my files from one folder location to another with full user visibility

For years I've put my application data files in c:\MyCompany\MyDataFileFolder\App where 'App' is my application name. I made this choice in the early days of Wild-West-Windows when Microsoft seemed to keep changing its own mind (My Documents, Documents, Program Data etc). As I've learnt more about how to do things correctly, and as Windows has now 'settled down' and is more picky about permissions I'd like to move my files. Users have got used to where they are though, and what I'd really like to do is to implement something like Windows does with 'special folders' where there are several synonymous names, thus in my legacy folder I'd like to put something in (or change a folder to) an alias for the real location which will now be something descended from Program Data. This way, the files are in a good place with the correct permissions and if we run a utility expecting or modifying files in the 'old' place this gets changed transparently to the 'new' place (thus a simple shortcut wont work).
Is this possible? Is there are recognised technique for this? I'm using Delphi XE2.
What you are looking for is either a Symbolic Link or a Reparse Point.

How to pass parameter to exe downloaded from web?

I have .Net desktop app which users can download from my website. I want to customize this app to per user basis.
Is there way to modify exe before downloading, just to change few strings with appropriate for the users downloading ?
Or it is possible to pass command line parameters to this exe via URL ?
The .exe file needs to be customized for it to behave differently for certain downloads.
Skip below to find the solution I found tolerable.
Add section to the .EXE file – Not ideal.
The .exe file has sections one after the other. You could add a section with your data in it, which the executable would then read. This requires you to modify (have access to) the source code of the executable for it to do anything meaningful with the data. Also getting familiar with the .exe file format and modifying it on the web server side as well al playing with it in the program's source code is somewhat tedious.
Change resources section of the .EXE file – Not ideal.
A dedicated "resources" section exists in the executable. You could add custom strings or blob of data to it. Same cons as the first one.
Overwrite data in the .EXE at a fixed position – Passable.
Have the executable read data from itself from a fixed position in the file, which is overwritten with the customization data when serving the .exe file. Requires modifying the executable's source code.
Append data to the .EXE – Passable.
Append data to the executable. Again, reading it and doing anything special with it requires the executable itself doing so.
☑ Wrap the .EXE in another .EXE and append your data to it – Tolerable.
Create a program to which the original executable and the custom data will be appended to. When this custom program is then executed, it will extract the embedded executable and launch it with the custom data as it arguments.
This kind of a bundle-executable is also easy to produce on most server-side (scripting) languages. When the download is requested, the server sends the wrapper-exe, the original exe, the customized data and of course some statically-sized data fields denoting the sizes of both of those data blocks so it can extract them.
Cons: Requires such a wrapper program to be created, unless someone already has.
Related links:
1. Best practices to let my web users download custom .exe from my site using PHP
2. Modifying executable upon download (Like Ninite)
If the application is ClickOnce deployed, passing URL parameters is an option in the ClickOnce options dialog. However, I have not yet used this feature.
EDIT
You might want to change some user settings in your configuration depending on the user that actually runs the application. You could also make sure this is done only once per user by adding an appropriate SettingsNeedUpdate setting you set to true after the initial initialization.
Example:
Add new setting "Option1", "Option2" and "SettingsNeedUpdate" which are user settings. In Main you could add something like:
...
try
{
if (Properties.Settings.Default.SettingsNeedUpdate)
{
Properties.Settings.Default.Option1 = ...;
Properties.Settings.Default.Option2 = ...;
Properties.Settings.Default.SettingsNeedUpdate = false;
Properties.Settings.Default.Save();
}
}
catch (Exception exp)
{
...
}
...
You could write a library which can modify an assembly resources (here string table).
This library could benefit from reflection.
When a user asks for your file, asp.net page could customize the exe (using your library) and send it to client.
Not like that, No.
You could however automatically zip (on your server) your exe with a custom app.config file for each user.
Update
Point your download location to a custom HttpHandler that zips together your exe (using http://www.sharpdevelop.net/OpenSource/SharpZipLib/) with a generated (for the current user) application configuration file ( http://generally.wordpress.com/2007/09/27/using-appconfig-for-user-defined-runtime-parameters/).
The user then unzips the two files (MyApp.exe & MyApp.exe.config) to any location and run MyApp.exe.
This method does not work if you have an installer.

Resources