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.
Related
I would like to store a c# object in SQL server. I thought about the following options:
Read object byte memory stream and save them into the database (but
not readable in sql)
Json, readable, easy to convert but what data type? (only a datatype for sql 2016)
XML, a bit less readable, easy to convert, there is an XML dataType
What's the best practice to store a C# object in a sql column and why?
I am using SQL 2014, so I think option 3 is the best?
Edit:
Note: it's not data to query, I just want to load a object which I have cached into a c# object in memory. And perform some logic on that in c#. It just takes a while to get the data from another database, therefore I save all my data in a custom object. Therefore I don't think I should use ORM
If it's just to throw in a database to read back at some point later by a key, then go with (2) and just use an nvarchar(max) field type.
If it's data to query, then you should probably design a schema to match and use an ORM.
If you are more positive towards option B, then you can store json-serialized string of any object[or datatype] in sql server as NVARCHAR(MAX) field.
And when you want to read it you can easily de-serialize that string in original format.
e.g.
Demo d1=new Demo();
//store this json into database.
string json= JsonConvert.SerializeObject(d);
// Now while reading fron db
Demo d2= JsonConvert.DeserializeObject<Demo>(json);
I'd go for JSON serialisation, it's just text, so when storing things like "user profile settings" or other types of structural data you're covered as you can read and write JSON in any language. Now SQL server has also understood this, like the XML support that was such a hype 8-10 years ago one can now store JSON with a good deal of TSQL support for those that need to update the data, like when you need to fix all updates for all user where...
anyway, have a look at the article. JSON in SQL Server 2016-2017
When going to and from JSON you should test your properties as some data types might not convert back and forward nice depending on things like regional specific settings like date and decimal values.
I have an existing SQL Server database where text is stored in Arabic. The default database collation is FRENCH_CI_AS, but the application uses Arabic. Displaying the data with ASP is not a problem, but I want to create a new database using UTF-8!
Text sample as it's stored in database :
ترأس وزير السكن والعمران ووزير الأشغال العمومية للجنة التقنية لمراقبة البناء
How I can transform text to get clear Arabic text in the database ?
Is there a solution using Excel? http://en.file-upload.net/download-10245297/test.xls.html
first of all use nvarchar() for type of Data in your Tables then when inserting data into your tabel insert like this
string Query="insert into tablename(columnName) values(N'value')...";
The strings need to be stored in the database as NVARCHAR instead of VARCHAR. This allows the database to store UTF16 encoded strings instead of ASCII with a CodePage. Of course this will double the amount of storage needed for the database.
From the screen shot it looks like the string is UTF8 being displayed as if it was ASCII and there does not appear to be a way to tell SQL this detail.
I share a little java project (with dependencies).
This project loads table data first and formats strings. The generated EXCEL worksheet can now imported using SSMS.
Java solution :
String charabia = "ترأس وزير السكن والعمر" ;
try {
String utf8String = new String(charabia.getBytes(), "UTF-8");
} catch (UnsupportedEncodingException e) {
}
My project download link : here
The question basically drill's down to these two C# 2.0, ASP.NET 2.0 webpages.
viewtemplate.aspx
generatetemplate.aspx
Purpose of these:
viewtemplate.aspx - Displays Email template defined in 'generatetemplate.aspx', with client assigned data pulled from database
generatetemplate.aspx - Is the actual page that contains place holders for client to put data.
[i named it so because that's the file i will be generating email to be sent from]
Requirement:
I will be requesting the generatetemplate.aspx from viewtemplate.aspx
, get the rendered output of generatetemplate.aspx and then send that output as email to the recipients.
It is the rendering part which i don't know how to do.
Note:
I will be calling generatetemplate.aspx from viewtemplate.aspx with query string so that generatetemplate.aspx will Pull value from database and then render rather than rendering with default values
You wish to get the rendered HTML output of running the page? You can download it from an HTTP request like a browser would with the WebClient class.
string generated = new WebClient().DownloadString("generatetemplate.aspx?myparams=params");
"generated" will then contain rendered output that you can do whatever you like with.
if I got question right, this is looks dodgy a bit.
I've used XSL + XML for such case. So you just prepare data in XML format, than applying XSL layout and thats it.
I stucked at a condition , where i need to share values between the pages. I want to share value from Codebehind via little or no javascript. I already have a question here on SO , but using JS. Still did'nt got any result so another approach i am asking.
So I want to know can i pass any .net object in query string. SO that i can unbox it on other end conveniently.
Update
Or is there any JavaScript approach, by passing it to windows modal dialog. or something like that.
What I am doing
What i was doing is that on my parent page load. I am extracting the properties from my class that has values fetched from db. and put it in a Session["mySession"]. Some thing like this.
Session["mySession"] = myClass.myStatus which is List<int>;
Now on one my event that checkbox click event from client side, i am opening a popup. and on its page load, extracting the list and filling the checkbox list on the child page.
Now from here user can modify its selection and close this page. Close is done via a button called save , on which i am iterating through the checked items and again sending it in Session["mySession"].
But the problem is here , when ever i again click on radio button to view the updated values , it displays the previous one. That is , If my total count of list is 3 from the db, and after modification it is 1. After reopening it still displays 3 instead of 1.
Yes, you could but you would have to serialize that value so that it could be encoded as a string. I think a much better approach would be to put the object in session rather than on the URL.
I would so something like this.
var stringNumbers = intNumbers.Select(i => i.ToString()).ToArray();
var qsValue = string.Join(",", stringNumbers);
Request.Redirect("Page.aspx?numbers=" + sqValue);
Keep in mind that if there are too many numbers the query string is not the best option. Also remember that anyone can see the query string so if this data needs to be secure do not use the query string. Keep in mind the suggestions of other posters.
Note
If you are using .NET 4 you can simplify the above code:
var qsValue = string.Join(",", intNumbers);
Make the object serializable and store it in an out-of-process session.
All pages on your web application will then be able to access the object.
you could serialize it and make it printable but you shouldn't
really, you shouldn't
The specification does not dictate a minimum or maximum URL length, but implementation varies by browser and version. For example, Internet Explorer does not support URLs that have more than 2083 characters.[6][7] There is no limit on the number of parameters in a URL; only the raw (as opposed to URL encoded) character length of the URL matters. Web servers may also impose limits on the length of the query string, depending on how the URL and query string is stored. If the URL is too long, the web server fails with the 414 Request-URI Too Long HTTP status code.
I would probably use a cookie to store the object.
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.