How to load, save and display data from GridView to XML? - asp.net

How to load, save and display data from GridView to XML? Not XML file on the hard disk, but a temporary XML variable to save it all in a single field of XML type in a database.

The gridview per se doesn't have any data - so you can't save any to disk.
Your gridview will be bound to a data source - a list of objects, a DataTable, anything - that's the data, and that can be saved to (and loaded from) disk.
Your easiest choice is to XML serialize the data to disk - or load it from there. You need to check into XML serialization.
Or check out the DataTable's ReadXml and WriteXml methods - they allow you to save a DataTable onto disk in XML format - or load it from a XML file on disk.
It can be as simple as this:
DataTable myData = new DataTable();
myData.ReadXml(#"C:\temp\mydatafile.xml");
// do some processing
myData.WriteXml(#"C:\temp\mydatafile.xml", XmlWriteMode.WriteSchema);
UPDATE:
if you want to store the XML into a string so you can dump it into a database, use this:
// write DataTable to memory stream as XML
MemoryStream memStm = new MemoryStream();
myData.WriteXml(memStm);
// read memory stream into a string variable
memStm.Position = 0;
string xmlContents = new StreamReader(memStm).ReadToEnd();
and then store your xmlContents to the database.
Marc

Why do you want to store the historical data in the database? Why not save the QueryString or whatever data was used to populate the gridview and rebind the data accordingly?
For instance if your user navigates to mypage.aspx?id=56&size=large&date=yesterday
you could load those options in a json object {"Id":"56","size":"large","date":"yesterday"} and store that in the database. Then, your data is up-to-date, and large datasets don't fill up your database table with redundant/outdated data.
Check out:
http://www.codeplex.com/Json
edit: and if you don't want to mess around with adding json, you can use anything as a delimiter, for example, have key/value pairs on separate lines and separate them with a pipe ('|')

Related

Determine File Type of attachments stored in SQL Server as varbinary(MAX)

I need some help. We migrated an Access database to SQL Server. One column had attachment data the Attachment data type in MS Access. The MS Access application is being replaces by an ASP.NET web application.
This data now lives in a column of data type varbinary(MAX), there is no indication of the file name and or type (most attachments are Excel, Word and PDF docs).
In my ASP.Net application I am using a data reader that will allow users to retrieve the attachments by downloading them using a browser. (I have a new table for new attachments that contains the full file name and content type, and when present it works like a charm). Without the file types, all attachments come across as xml/garbles data files like shown in this image below (can't yet post images, been a long time reader, first contribution. Here is the text in which I had planned to highlight some key values:
ÿÿÿÿWorksheetExcel.Sheet.12****Access.OLE2Link¾ÐÏࡱá>þÿ þÿÿÿÿÿÿÿÿÿÿÿÿÿ]þÿÿÿþÿÿÿ !"#$%&'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\þÿÿÿþÿÿÿÿÿRoot EntryÿÿÿÿÿÿÿÿàÆ©÷òï…ÝŒkˆZ‚Å7Ï€Ole ÿÿÿÿÿÿÿÿÿÿÿÿCompObjÿÿÿÿeOlePres000ÿÿÿÿÿÿÿÿš­ þÿÿÿþÿÿÿþÿÿ‹ÀF CENTRA~1.XLSÿÿ­ÞHBCentral Dispatch Process Map.xlsxºÀF'C:\Users\MA~1\Desktop\CENTRA~1.XLSÿÿ­Þ]|C:\Users\ine\Desktop\Central Dispatch Process Map.xlsxÕLÀFƒ •Æh5)ÏBy>*Ϧc{>*ÏS5ŽŒ2S5&D%¯ CENTRA~1.XLSpï¾&D6®&D%¯*ƒœ2Central Dispatch Process Map.xlsxm-lkÑÊC:\Users\ine\Desktop\Central Dispatch Process Map.xlsx(
It appears that the content is there from which I should be able to extract the file name and types.
Here is my question, how do I migrate my attached files. I need to determine the content type and file names from the original data stored in varbinary(max), I then need to move the files from the current location into my new table with the attributes that describes the file name and file type.
Thanks

Save and restore XML from xml field

Sorry for simple question:
I want to load XML file by fileupload and save it in the field of Table with xml type. then restore it from sql and bind it to dropdown list with Handler?
One of the simplest ways is to use XmlDocument to load your file and process it
XmlDocument xmlDoc= new XmlDocument(); // Create an XML document object
xmlDoc.Load("yourXMLFile.xml"); // Load the XML document from the specified file
// Get elements
XmlNodeList foo = xmlDoc.GetElementsByTagName("foo");
XmlNodeList bar = xmlDoc.GetElementsByTagName("bar");
// Display the results
Console.WriteLine("foo: " + foo[0].InnerText);
Console.WriteLine("bar: " + bar[0].InnerText);
Because you're using it to return ALL elements based on their known name it will pop everything into an array. This makes it a lot easier to process multiple entries, for example:
<document>
<entry>
<foo>foo</foo>
<bar>bar</bar>
</entry>
<entry>
<foo>foo</foo>
<bar>bar</bar>
</entry>
</document>
Depending on the type of data I would recommend making your own class and storing the entries in an array or list of that class.
Once that's done you can easily reference them and use .net's SQL functions to insert the entries from the list into the database
You can find details of how to bind your dropdown list to the dataset here: Populating an ASP.Net Drop Down List with DataSet data from DataSet created with DataSet designer

how to cache a data source contents?

how to cache data source contents?
suppose I'm retrieving some records from my sql server database and fill them in a data source or a data table.
How can I cache the data source or data table contents?
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
DataSet ds = new DataSet();
SqlCon.Open();
string sq = "exec RetrieveLastVariableWorkerInfo #RealCode";
SqlCom = new SqlCommand(sq, SqlCon);
SqlCom.Parameters.Add("#RealCode", SqlDbType.NChar).Value = RealCode;
da = new SqlDataAdapter(SqlCom);
da.Fill(dt1);
Basically you need to use the Cache object provided by ASP.NET. This is shared globally across your application and any objects stored there are available to all page requests. You can specify the amount of time an object should stay in the cache (either and absolute time or with a sliding expiration) and define a dependency which will remove the cached object if it is triggered e.g. a Sql dependency will remove the object from the cache if a change is made to the table(s) where the data has come from.
This MSDN article gives a good overview of the subject, specifically the section on Caching API, Using the Object Cache.
You may also want to look at the CacheDependency (specifically SqlCacheDependency in your case) object to refresh you cached items as changes occur in your database.
Things to be aware of are the size of the objects your are storing, how long they are stored for before they are outdated and should be removed from the cache and if there should be any external triggers which should remove them from the cache.
ASP.Net offers several APIs to store data.
The Cache object can be used to store any object. The API is pretty flexible.
Cache["MyObject"] = dt1;
Cache.Insert("MyObject", dt1)
This will put your data table into the system cache. You can place expiration times on the cache if the data goes stale or link it to an external dependency (such as SQL server or a file) so that changes in the external reference automatically invalide the cache.
It's also worth noting that ASP.Net will clear the cache automatically if memory becomes tight. Any data you place in the cache is available to all requests.
If the data is more specific to one user, you could place the data table into the user's Session object. The Session is generally linked to one user's browsing session by a unique ID. This way you can read several different data tables into memory without any conflict.

updating batches of data

I am using GridView in asp .net and editing data with edit command field property (as we know after updating the edited row, we automatically update the database), and I want to use transactions (with begin to commit statement - including rollback) to commit this update query in database, after clicking in some button (after some events for example), not automatically to insert or update the edited data from grid directly to the DB...so I want to save them somewhere temporary (even many edited rows - not just one row) and then to confirm the transaction - to update the real tables in database...
Any suggestions are welcomed...
I've used some good links, but very helpful, like:
http://www.asp.net/learn/data-access/tutorial-63-cs.aspx
http://www.asp.net/learn/data-access/tutorial-66-cs.aspx
etc...
Well,
you can store your edited data in a DataTable in session. and then pass this data table as a bulk insert in to the database. 2 options are available for this
if you are using SQL Server 2005 you can use OpenXML to achieve this, as i have stated here
if you are using SQL Server 2008 youc an use Table Variables like i did here.
i hope it helps
First way:
Create session variable that will contain your DB object (DataTable or mapped objects).
The GridView should work with this instance instead of sending the data to the database.
Once editing is finished you may take the object from the session and save it in the way you normally do.
Second way:
I would use javascript to collect all changes on the client side while he is editing as a array of objects (each object is separate row).
Once the editing done, you can create json string from the collection and pass it to the server.
If your json object configuration is same as server class then you can use JavaScriptSerializer to deserialize your string into collection of object.
After that, you can save your objects in the way you normally do.

store and display of file from sql database

how to store files (pdf and word files) into sql database and how to display that files with an option of "save" , "open" from sql data base when user click. i am doing project using c# + asp.net web application
You need to do several things here:
1) Create UI page that allows users to upload files.
This page will have a FileUpload control to check for the desired extentions
2) Write code to save these files to a database
The files can be stored as binary blobs. It will be up to you and your application to decide the schema of your database. You may also choose one of many ORM tools to provide you access to the database from your code see
Linq2SQL
EntityFramework
ADO.net
Or see Creating A Data Access Layer
You have many choices, choose whatever seems most natural / easy for you.
3) Create a UI for the user to select existing files
This will use your ORM data layer to read back the lists of files and display some sort of buttons / links for the user to select and download
4) Retrieve the files from the database once the user selects one and return the file
Read this MSDN article about returning binary files
Furthermore, google around a bit, you'll probably find lots of existing solutions with frameworks like DNN etc.
To store files, you should check out Filestream from SQL Server 2008: http://msdn.microsoft.com/en-us/library/cc716724.aspx
Other traditional platforms have similar support (with binary or image data types).
An alternative is you can store the file in a shared filesystem, and only store the path to the file in the SQL table.
The most common way is to have two columns in the database for the file to be stored propley. 1 column holds the filename with its extensions(ex: file1.txt) and the 2nd column will be of datatype binary.
at the application level. a method gets the uploaded filename and converts it to an array of bytes. then this array is stored in sql in the binary field. the filename is stored in the 1st field.
to read the file back, another method will read the binary field from sql and convert it back to a FileStream then save it with the original filename(extension).
Use a fileUploaded to upload the file.
Read the file into a byte array:
byte[] data = System.File.ReadAllByte(File Path);
convert the byte[] to hex and store it in a nvarchhar data field in SQL
stringBuilder sb = new StringBuilder()
foreach(byte b in data)
{
sb.Append(b.ToString("X");
}
When you need to display it, convert it back to byte[] and create a file out of it, and let the user Open/Save it from there.

Resources