Embed MS Access Database in C# WinForm app - c#

I have a C# winform application that accesses data from an MS Access database. This means my applications requires at least 2 files, the .exe file and the .accdb file. Is it possible to include the database in the .exe file, so my solution consists of a single file (the same way you would include an image in the project resources)? If it is possible, are they any major reasons why it shouldn't be done and how would you access the data from code? The project is a only a little one for personal use so if performance is hit it doesn't matter too much.
thanks in advance

It can be done. Simply add it to your project as you would add any other file (right click project -> Add -> Existing Item), then cancel all the dialogs that will popup offering you to handle it for you, then right click your database from your project explorer, go to properties and select Build Action: Embedded Resource.
Then use the method below to dump your database into a temporary file, which you can create by calling Path.GetTempFileName.
internal void CreateBlankDatabase(string destFile)
{
using (Stream source = new MemoryStream(Properties.Resources.MyEmbeddedDatabase))
using (Stream target = File.Open(destFile, FileMode.Truncate))
{
source.CopyTo(target);
}
}
(Note that MyEmbeddedDatabase would be your embedded database name). Then use your temporary file name in your connection string. Make sure you delete your temporary file after you're done. Also, as other said, you won't be able to modify and save any data.

No it shouldn't be done. How would you send someone and update to the .exe file without them losing their data? Keep it separate.
You need to have a way to manage how your applications installs and the file location in your connection string(s). There could be a \Data subfolder in your app folder with the .accdb file(s) in it.

You probably can't achieve what you want with an access database as an embedded resource, but you effectively get the same result by wrapping all your files in another executable app.
When you run the wrapper application, it extracts the "main" C# app, database file, and an updater app (more on this below) to the temporary files folder and runs the main app.
When the main app is closed, it runs the updater app, passing in the paths to the database file and original wrapper application. The updater app updates the wrapper application file with the changed database file. It then finally deletes the database main app and database file from the temp folder. Unfortunately, the updater app can't delete itself, but you could work around that by adding a command to the runonce section of the registry to delete the updater app on the next reboot.
Instead of figuring out how to extract and insert embedded resources, consider having the wrapper application as a compressed, self-extracting executable (like a self-extracting zip or rar file). Here's a codeproject article that describes how to turn a .Net app into a compressed, self extracting exe.

Access requires to be able to read and write to the file. The OS will lock the exe when it is run so that it can't be changed while in use. This along will cause it to not work, not to mention that Access simple wouldn't be able to read the exe as it is expecting a different file format.

Related

How to read a file that is part of the solution on program load?

I'm writing a C# WinForms application, and one of the components of the application is a SQLite database.
If the user is running the program for the first time, the program is supposed to create the necessary folders and files (namely, the database file) in the user's home directory. That works fine.
However, the database also needs to be set up (i.e., tables need to be added). I have a SQL script that will create the necessary tables; however, it is currently stored in the solution directory and I'm not sure if this is the best practice for when the program actually gets packaged into an .exe file.
The script will be the same every time the database needs to be set up, so I'm thinking there are probably a few options:
Have the program read from the SQL script and apply it to the database (preferred unless there is a better way)
Load the contents of the script file into memory (hard-code it into a string) and have the application run it that way (not preferred because of future versions, there needs to be a way to update the existing structure so as to not obliterate the existing database, so this way could get complicated)
Include the SQL script as part of the program package or a standalone file (very dangerous because users aren't supposed to know about that)
So what is the best way to run SQL statements from a "companion" script file? How does all of this get packaged when the program is ready for production, and how can I ensure that this file will be accessible by the program every time it is needed?
You can set the file to be copied in output directory. Select the file in solution explorer and then in property window, set Copy to Output Directory to Copy Always. This way the file will be copied in output directory and you can load it this way:
var path = System.IO.Path.Combine(Application.StartupPath, #"Script.txt");
var content = System.IO.File.ReadAllText(path);
If the file in root of the solution, use filename as above. If the file is in a folder in your solution, for example for a file in Folder1, use #"Folder1\Script.txt" in above code.
As another option you can add the file to Resources.resx. Then it will be included in resources and you can simply access it this way:
var content = Properties.Resources.Script;
Include an encrypted version of the sql file. Have your program load, decrypt it then execute it. At least that's how I'd do it.

Publishing winform application with .sql files

Maybe someone can help me with the following problem:
I created a winform application in visual studio which i want to publish. The application contains a map Sqlscripts with .sql files in it.
FileInfo file = new FileInfo("../Sqlscript/View.sql");
string SQLscript = file.OpenText().ReadToEnd();
i thought about creating a directory for those files in C:\ when running the application, but ten i realized that it's not safe doing it this way. No one should have acces to sql querys. Can anyone help me for an alternate?
Thanks!
Embed your .sql file as resource (i.e, file content will be embedded in compiled code), and read it at runtime with Properties.Resources.yourresourcename
string sql = Properties.Resources.yourresourcename;
To add a file as resource, open Resources.resx in solution explorer -> Add Resource -> Add existing file (or add new text file)
Obscurity != security. If someone wants to, they can always get the contents of the file. Be it reverse engineering, or simply reading out the memoty of the program. How important is it that thay can't edit / view the SQL? Otherwise I would generate the SQL on a server somewhere. Make sure the server only accepts parameters and generates / runs the SQL there.

Add config directly into C# assembly

I need develop some application, that will be distributed to user as a single executable file. User should click to some button like "Download" and get exe file, then he executed it, and upload results back to my site. App should not contain any installer or something like this, just run once and get result.
My application have a main executable like "myapp.exe" and several data files, that depends on current user. Now i have to generate SFX zip archive, that contains myapp.exe, datafiles and current user config. When user click "download", i'm adding user data to archive and provide it to user.
Problem is that SFX archive is very boring and difficult to maintain thing. I can't change it's interface, i can use only one or two zip libraries, that can create SFX arxhives.
Is there any way to use another container or pack user data into resources of my utility "on the fly"?
I've been doing that for an application where i needed to identify which user it was without asking for any credentials. Basically, some kind of token was bundled within application before download and then sent to the server.
From what i've found, there are 2 methods :
Using WiX: build the XML, call candle + light, send to client
Making a single MSI and editing its database just before sending it to client
We chose MSI database editing for its simplicity of implementation, but i've seen WiX in production recently and the result is pretty neat.
You can use Mono Cecil to programmatically alter assemblies, including their resources. In your case, you could use it to modify your assembly pre-download to add/modify embedded resources that contain the data for the specific user.
byte[] userData = ...;
EmbeddedResource resource = new EmbeddedResource("UserData", ManifestResourceAttributes.Public, userData);
assembly.MainModule.Resources.Add(resource);
You can then read the added/modified resource(s) (at runtime, post-download) using Assembly.GetManifestResourceNames and Assembly.GetManifestResourceStream.

Re-Embedding Sqlite Database file into the same Executable

I'm Creating Win Form application ,I'm adding a Empty Sqlite Database file having Tables in it as embedded data source. on run time i extract Database file into application path and INSERT THE VALUES into the TABLE of that Database file.
On Closing the application again i have to update or replace Database File into Executable.
Is it possible ,if so how to do that.
I'm not sure if I understand the question correctly. If you are trying to re-write to the same exe you are running this is NOT possible. Windows locks code files that are in use so that they can't change. Additionally, it is not advisable either, code and data should be separate.
If you are trying to update another resources executable (that is not currently running), I don't know how to do that programatically (See this thread here for more info How do I replace embedded resources in a .NET assembly programmatically?) but if your program has access to the Visual Studio Compiler tools (which it probably doesn't) you can disassemble and reassemble the executable. See here: http://fortheloveofcode.wordpress.com/2007/09/24/change-resources-inside-assembly/.
Why not just store it in application folder? Or maybe user's AppData if you don't want to show it?

Embedded a *.exe into a dll

does somebody know how can I embedd an exe file into a dll ?
I have a tool which is an exe file that I call from c# code.
The thing is that I want to have 1 dll containing this tool (exe file) and the dll containg my c# code.
Is it possible to embedd this exe file within the resources?
Thx in advance
Sure it is. You can add any file as RC_DATA in application as resource. But I believe you will need to extract it to disk first before calling it!
Which IDE/Language you are using?
[EDIT]
Sorry! you did mention that you are using C#.
Add a resource file to you application (right click application in IDE and select "Add new item".
Use the toolbar in resource editor to add an existing file.
Then extract the exe whenever required by calling code something like:
System.IO.File.WriteAllBytes (#"C:\MyEXE\", Resource1.MyEXE);
It's worth baring in mind that your uses may not be too happy about you doing this. Embedding an executable that they've got no control over into a DLL that you'll extract and run will probably make people worry about the running a Trojan on their machine.
It's better to leave the .EXE in the filesystem and be transparent about what your application is doing.
You can load an Assembly from a byte[]. This can be obtained via the ManifestResourceStream of an embedded resource.
An alternative may be to not embed the .exe itself, but rather include its functionality in the dll, and use rundll32[1] to execute it.
On a side note, remember that when you pull a file from your resources to disk and then execute code on it, you may trigger Windows Data Execution Prevention - basically, Windows tries to automatically detect if something is supposed to be code or data, and if it looks like data (which a resource would), then it will prevent that data from being executed as code.
This becomes a particularly sticky issue if your .NET assembly is going to be used over a network instead of from a local drive - there are all sorts of .NET security configurations that might prevent this from working correctly.
Another option, and not knowing the details of your project, take this with a grain of salt: add a .exe.readme file to your install that describes to any curious users or IT people why there is an executable they weren't expecting in the installation directory :)

Categories

Resources