I'm trying to write a C# program, where when a user enters some data into a text box and clicks on a "save" button, the information is stored in some sort of file that when the program is opened the next time around, the information is automatically loaded in.
I'm using Visual C# express. What's the best way to do this without requiring some sort of database like MySQL or MSSQL or Access?
If the only way or easiest way is a database, I'd rather use Access. If so, does the user of the program need Access installed for my program to run on their computer? What if I go with another database?
p.s.
I forgot to mention, I'd rather the user not be able to access this file and read the contents easily. Text file without encryption would be easy to open. Any way to encrypt this? Also, if I use a delimiter like ':', then that means the user cannot use that character. So any other way?
Thanks!
Make your user data serializable by adding the keyword:
[Serializable]
above your data structure. When you load the dialog box, load your serialized structure from disk, and when you leave the dialog, save the data structure.
From a style standpoint, you should probably not have the dialog box change data until the dialog box is closed (if it's modal).
To save:
private bool Save(String inFileName, MyObject inObject){
try {
FileStream theStream = File.Open(inFileName, FileMode.Create);
BinaryFormatter theFormatter = new BinaryFormatter();
theFormatter.Serialize(theStream, inObject);//add it to the end there
theStream.Dispose();
theStream.Close();
} catch{
return false;
}
return true;
}
To Load:
private MyObject Read(String inFileName){
MyObject theReturn = null;
try {
FileStream theStream = File.Open(inFileName, FileMode.Open, FileAccess.Read);
BinaryFormatter theFormatter = new BinaryFormatter();
theReturn = (CImageData)theFormatter.Deserialize(theStream);//add it to the end there
theStream.Dispose();
theStream.Close();
}
catch {
return null;
}
return theReturn;
}
You can also use 'using' on a stream, but this code is pretty straightforward, I think. It also means that you can add more items into MyObject.
Edit: For encryption, you can add in AES or something similar. That might be overkill for you, and saving the file as binary may make it readable by something like notepad, but not easily editable. Here's a lengthy explanation on real encryption:
http://msdn.microsoft.com/en-us/magazine/cc164055.aspx
Sql Compact Edition would hide the data from being easily accessible (and its free). You can also password protect a CE database. A SQL CE database is contained completely in an .SDF file, like Access, so you can copy the .sdf file around and not have to worry about network connectivity, etc.
If your application is only to be used by a single person then simply store your data in a file (XML would give you some structure)
If your application will be used by multiple people and the data shared among them, then a database is your best option. If you use a database then yes you will need to have a database installed on your users computer, though it is possible to do that transparantly to your user, for that you are best off with an embeddable database, something like MySQL would be your best bet.
(EDIT: the database actually does not have to be on the users computer, but he would need to be able to see it from his coputer)
If it's very simple then you could place it in a plain text file. For more structured data you could consider storing it as a CSV and parsing it or creating an XmlDocument and saving that to disk.
Related
I want to save a reference to an image that will be stored in the database.
But I am not sure how to approach this in C# (Entityframework).
Using EF's code first approach.
In the Model class, must i do String imageReference, og must I use byte? Or is there another and better solution to this? What I want once the database is created, for that column, it should say Blob or what ever is used to hold large objects like images.
I am also thinking that only saving a reference in the database, instead of the image itself might be a solution. But I don't know which is better?
You need to create it as a byte, and your db should be blob
var image = new ImageEntity(){
imageReference= convertImageToByteArray(image)
}
_Context.Images.Add(image);
_Context.SaveChanges();
Convert ur image to a byte array:
public byte[] convertImageToByteArray(Image imageIn)
{
MemoryStream memStream = new MemoryStream();
imageIn.Save(memStream , ImageFormat.Gif); //u may choose other formats
return memStream .ToArray();
}
I would recommend saving the file path as reference instead of storing it as a blob unless you have no choice. This is because a larger DB will degrade the performance, the hard disk would do a better job at handling files. If your image files are larger than 1MB, the file system has an advantage over a SQL Server. Also storing it in the file system has greater flexibility (i.e. you may migrate your files elsewhere next time, and change the link in the DB during migration, you can't do that on the DB)
I have a silverlight application running on an IIS which currently has some data lists hard coded into the c#, not a good idea I know but this was for a proof of concept demo and now I need to move on to getting the data from another source which can be modified.
I've looked at xml files as well as an sql database. The problem is that the client is reluctant to allow anything extra to be installed on the machine (long security process) and so sql express may not be practical. I've also tried to look into sql compact edition but I cannot seem to be able to find any decent tutorials about it.
The data is made up of three, fairly short, lists of small objects which contain strings and integers. I'm looking for a, preferably, simple and quick to implement solution which ideally does not need anything extra installing on the server.
Does anyone have any suggestions or links which may be handy?
Thanks in advance
Cap
If you are comfortable using LINQ to query your data instead of SQL, Sterling DB sounds perfect for you. It's extremely lightweight, and requires nothing extra on the server or the client (other than including it in your code obviously). It uses isolated storage to store data. All of the serialization/deserialization is taken care of for you by the library.
Edit:
Based on your comment that the data is "static" (meaning all clients consume the same data), it's probably best not to use a client-side database like Sterling or even (as you mentioned) SQL CE. You are right to have reservations about hard-coding this type of "catalog" data, as changes in that data would require a new release of software.
A simple way to make the abstraction is to simply host an XML file alongside your XAP that contains all your data. You can author the XML in any way you want. In the software, it should be fairly straightforward to download the XML file, parse it, and populate your catalog each time the app runs. When changes to the catalog are necessary, it's just a matter of modifying the XML file.
I know this is not an ideal solution but you could try using tab separated text files. They are the easiest to create.
I use XML (web.config) to store data use by all clients such as pre-configure or default user setting value and use Isolated Storage for client-independent data, such as, user UI-layout setting.
I would serialize the objects to XML and store them on the server, it's relatively easy to do
You can pull the values into and XDocument
XDocument ConnectionStrings = XDocument.Load(System.AppDomain.CurrentDomain.BaseDirectory + "ConnectionStrings.xml");
Here are the serialization function i'm using
private static XDocument Serialize<T>(object obj)
{
XDocument ReturnValue = new XDocument();
//Create our Serializer with the type that was passed in
XmlSerializer Serializer = new XmlSerializer(typeof(T));
//Serialize our object to a string writer
System.IO.StringWriter sw = new System.IO.StringWriter();
Serializer.Serialize(sw, obj);
//We use a string reader to read the string from our Writer (created when serialized)
System.IO.StringReader sr;
sr = new System.IO.StringReader(sw.ToString());
//Then we can load the string reader giving us an XDocument
ReturnValue = XDocument.Load(sr);
return ReturnValue;
}
private static T Deserialize<T>(XDocument Xdoc)
{
T ReturnValue;
//Create our Serializer with the type that was passed in
XmlSerializer Serializer = new XmlSerializer(typeof(T));
//Create a string reader to access the XML data in our XDocument
System.IO.StringReader sr = new System.IO.StringReader(Xdoc.ToString());
//Deserialize the XML into our object
ReturnValue = (T)Serializer.Deserialize(sr);
return ReturnValue;
}
Here is my problem: I need to store HTML in a MySQL database. Afterwards, I need to be able to retrieve the HTML and have it be valid HTML that a browser can render.
My question: How can I store HTML in a MySQL database using .Net? How do I retrieve it afterwards? As this is the design phase, I can create the database any way that is needed. Thank you.
P.S. I have seen some posts on this using PHP and JAva but I am not using PHP or Java and those posts did not really answer my question.
You can store HTML as a binary stream in MySQL's BLOB format. Also you can retrieve it in .NET.
To retrieve and store it, you can simply use Byte[] in .NET.
This is a sample using BLOB: http://msdn.microsoft.com/en-us/library/87z0hy49.aspx
First of all, do want want to store a file or just the html text?
Since you say php, I take it that u are using web based.
If so, I suggest storing the html text as string.
First of read the content of the html file using something like this:
using( StreamReader reader = new StreamReader( #"c:\index.html" ) )
{
String line = String.Emtpy;
while( (line = reader.ReadLine()) != null )
{
Console.WriteLine( line );
}
}
Then, just do a normal insertion of string in a reasonable string data type of MySQL. (Cant recall, but if really need alot, can consider BLOB)
After that, when you want to display, at the code behind of the aspx page, retrieve the html as string, and use use
Response.Write()
You'll be needing the .NET driver for MySQL. If you have experience building C# applications that connect to MSSQL or any other database server, then you'll know where to go next.
As far as storing in the database is concerned, have a text field in your table, to store the HTML code in.
I want to be able to copy a database into a byte array and then query it. Is this possible?
For example, with a text file I can use..
byte[] file = File.ReadAllBytes;
..and then read the byte array with..
StreamReader rdr = new StreamReader(new MemoryStream(file));
No. In order to query it, the database classes will require the database to reside on disk. MDB files, in particular, require a lock file to be generated when you open the database.
I am wondering if its even possible. I am returning files from database (blob) and have them as bytes array. I would like to let the user to show the data content by clicking on associated object - something like opening in the WebBrowser which automatically selects the appropriate program..but I understand I would need to save the file to the disk.
Is there any other solution which would work only from streams/byte arrays?
You could try setting the WebBrowser.DocumentStream property:
browser.DocumentStream = new MemoryStream(blob);