File Permissions Issue with Silverlight - c#

I have a Silverlight 4 / C# project I'm working on in Visual Studio. I made an XML data file by right clicking on the project >> Add New Item >> Xml File. I then try to open the file:
StreamReader streamReader = new StreamReader("data.xml");
However, this gives a security exception. How can I get around this, or grant the necessary permissions?

Silverlight doesn't allow local file system access by default. Your options are:
Using IsolatedStorage.
Run with elevated permissions.
Embedding the file in the assembly, if you only need to read it, as suggested by Jon Skeet.
If you need to store data in general, use IsolatedStorage if you can.

You would need to mark the item as a resource, NOT an embedded resource.
From MSDN...
The Properties window in Visual Studio
provides several other values in the
Build Action drop-down list. However,
you can use only the previous three
values with Silverlight projects. In
particular, Silverlight embedded
resources must always use the Resource
build action, and not the Embedded
Resource build action, which uses a
format that Silverlight cannot
recognize.
A great walk through can be seen here entailing what you are trying to accomplish. Since you are not trying to access files on disk but as resources this is not a problem. IsolatedStorage nor elevated permissions are pertinent here.

Do you just need to be able to read the file at execution time? If so, I would suggest you set it to have a Resource build action in Visual Studio, and then use Assembly.GetManifestResourceStream to open it. That's the simplest way of bundling read-only data with an application, IMO.

That constructor of StreamReader is expecting a file path into the local file system, which is only available out of browser with elevated trust.
Instead you should be using Application.GetResourceStream:-
Stream stream = Application.GetResourceStream(new Uri("data.xml", UriKind.Relative));
StreamReader reader = new StreamReader(stream);
However I expect you really just want this in an XDocument, you bypass this StreamReader stage:-
XDocument doc = XDocument.Load(stream);
BTW, I personally would leave the XML as Content in the Xap rather than embedding it in the assembly.

Related

How to save and read a xml file from another website?

I have this link: http://www.bnro.ro/nbrfxrates.xml to an xml file with daily Currency.
I want to save this xml in folder of my website ex. (~/Content/CurrencyXml).
I want to save it every day, first time when a user is accessing my website (must replace the old file).
I want also to read it in a static method which return an object with each currency type like property, in order to access it something like this:
price=model.Eur * 100;
Can you help me with an example of how to save a copy of this xml and how to read it?
You can try something like this to read the file and save it
public void readFile()
{
XmlDocument document = new XmlDocument();
document.Load("http://www.bnro.ro/nbrfxrates.xml");
document.Save(Path.Combine(
Server.MapPath("~/Content/CurrencyXml"),"myFile.xml"));
}
and in here you can find very usefull information:
XmlDocument Microsoft
Here's an example for the windows service:
Walkthrough: Creating a Windows Service Application in the Component Designer
Here's an example on how to download xml using WebClient:
How can I download an XML file using C#?
Here's an example on how to save a file to your server:
C# save files to folder on server instead of local
Then use what #Augustin suggested.
If you do use the flag file scenario, I would advice to save the xml file to a temporary file and only when fully downloaded, overwrite your original one and make sure to handle locking, overwriting time, etc... One other solution would be to use a temp variable that holds the current filename and when you download a new file, just give it a new name and when downloaded, set that variable name to the new filename and make sure that your load function uses that variable and loads the data from the new filename. Don't forget to delete your old file(s), but at least it will avoid locking issues if any and you can always try to delete the file later again.
If will very much depend if your website if being access 24/7 or not. If it isn't it is less of an issue as you could use the windows service to download this file when you know it's not being used. If you use the windows service, while being used, same as above would apply. If you're using Azure, you could use a WebJob. I'm sure there are many different solutions to handle this and you just have to find the one that will meet your needs.

How to publish config files along with application in windows forms application

I have a very simple use case.
1) I have 4 config files which are needed for the application to start.
When I publish my application these files should be exported by default along with it. How can I do this ? Where should the files be stored so that they are available when the pplication is installed?
The users of this application should be able to edit and access these files.
I have seen the option of saving it using string source = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
I have tried adding these as resources, but these files need to be editable, hence cannot be in exe.(Reference is this question)
Please comment if you need additional information.
If you're building the installer in Visual Studio, you can add those files as Content and it should be automatically included in the installer when it's built.
You create installers in Visual Studio by adding a Setup Project to the solution.
Link to tutorial on MSDN: http://msdn.microsoft.com/en-us/library/vstudio/19x10e5c(v=vs.100).aspx
I recall it should automatically add all Content items automatically, but I'm a bit rusty. Here's more detail on how to add items to your installer, including desktop shortcuts and such:
http://msdn.microsoft.com/en-us/library/vstudio/z11b431t(v=vs.100).aspx
Good luck!
There are meny ways to do whay you want to do. the main question is why do you want to do it?
if you have a normal program for personal use you can simply link it to the needed file, meaning using the file without actual knowledge that it's there.
if it's for a task then you can zip them together, that way you'll know they are together, without adding them as resource.
for other kind of use, or if you have to add them as resources, just add them like shown here
for more reading on what do you need and how to do it i have here linked vs. Embeded resources
good luck

Embed MS Access Database in C# WinForm app

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.

how to store settings for deployable c# application?

I want to store settings for my C# application, such that default setttings can be easily shipped with my binaries and the end-user can change them using a simple text editor(or in some other simple way).
I seem to face several alternatives : a .config file, .settings file or a .resx file. What are the pros and cons of these?
Edit1: End-users are computer professionals mainly, so editing these files should not be much of a problem.
Edit2: The settings are something like connection strings, and some other parameters (mostly one-time stuff). Building some kind of GUI/API for changing them is not really an option. Also my application will not edit any of these values, so persistence through code is not required.
Yes, Project + Properties, Settings tab was designed to do this. Add your settings here, change the Scope to Application. That generates a app.exe.config file in your build direcctory, deploy it along with your EXE. Use Properties.Settings.Default.SettingName in your code to obtain the setting value. Your user will normally need admin privileges to edit the .exe.config file on the target machine to change the setting value.
The small print: settings do not work well for DLL assemblies, you have to merge the .config files by hand. When using the debugger, settings are retrieved from the app.vshost.exe.config file.
The .settings file is a helper file used by the IDE, ignore it. .Resx files store resources, they get compiled and embedded in a binary form in an assembly. They are not editable by the user.
I think you can have two ways of doing this.
For regular users, you can make a custom GUI that will make it simple for them to use.
For advanced users, they can edit the configurations using a text editor if it's stored in a text file (ini file, config file, etc..) or you can make an API.
The .settings file is typically used for user-specific preferences and configuration information (whereas the .config file is used for global settings for the application or anything that modifies the .Net runtime. Simply putting parameters in a .config file can alter the behavior of your application even without you writing a single line of code for it).
Check out the Settings article on MSDN for more: http://msdn.microsoft.com/en-us/library/aa730869(VS.80).aspx
Since the file will be modified by the users, I think using app.config is not a good idea. What if they break the file structure? Or set an invalid value? Probably your application will crash directly.
One of the solutions would be to use a custom XML file. You will then validate it when your application starts. XSD will probably be the more elegant way to do it, but you can also parse it directly and validate it in code. If the file is invalid, instead of crashing, you will try to solve the problem, and if impossible, display a pretty error to the user, explaining that there is an error in XML at line n, position n, which is [error description here].
If the end user is really going to be editing them, I'm not sure I would want them editing my app.config file.
You have another couple alternatives that you haven't included. You could use an old-school .INI file that is simpler for an end user to understand. You could also use the registry. I would recommend the INI file, unless your users are very savvy, in which case use the .config file.
The answer depends on the deployment method. For instance, if you are using ClickOnce and offer updates, you might encouter problems using Application Settings.
I believe the best way to go is to create a GUI, something that is most certainly suitable for novice users. Given that you already excluded that option, use John's suggestion (ini files).

Advantages and usefulness of adding an XML file to a Visual Studio 2008 project

What is the advantage of adding XML files to a visual studio 2008 project (windows form app project for example).
Once added to the project, how could I refer to this XML to use it in a class in the same project? In this case, I would be sending it as a query to a web service.
If you want to use the XML in some form, you could mark it as a "embedded resource" in the properties window, and then access it from your code like so:
Assembly a = Assembly.GetExecutingAssembly();
if(a != null)
{
Stream s = a.GetManifestResourceStream(typeof(yourType), "YourXmlName.xml");
if (s != null)
{
String xmlContents = new StreamReader(s).ReadToEnd();
}
}
Once you're done, you have the XML file's contents in "xmlContents", if all goes well.
Marc
I guess the advantage of having your XML reside there in your project (or solution even) is that you can maintain it in VS with nice formatting and even intelli-sense, but then using something like XML Spy or whatever can give you that too.
To refer to it in a class you'll need to ensure you have access to it, and that it resides in a reliable place.
In the past I've used post build events to move the latest copy of the file to where I need it. As Arnshea writes here is another answer, "to the output directory". You can use the "Copy to Output directory" property on the XML file itself to achieve this. Then your classes can use the XML file, knowing it will reside in a reliable place.
You'll need to make sure it's accessible though especially if you're writing back to it. Make sure it doesn't end up "Read Only" - as Source Control system could do to you. Storing these files in a folder under Program Files could also be problematic especially on Vista, where user privileges are (should be) restricted.
If your app needs to load the XML it can be copied to the output directory. Also simplifies use of Setup/Deployment projects...
Another major advantage would be (assuming it's in place--and it should be!) is that you can apply revision control to the XML file.
I guess that you won't be sending the same XML file to the WebService over and over again.
You will want to modify its content every time for that you have XML Serialization.
If all of the above apply then you don't need the XML file, you just need the class that generates the file at runtime. The XML is just the transport, today its XML and tomorrow it might be some other format (JSON).

Categories

Resources