store and display of file from sql database - asp.net

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.

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

Image Comparison in ASP.NET

I'm developing a web application, Computerized Voting System using ASP.NET. i want to compare thumb impression from database. I'm using disconnected data access. is it possible to compare an input thumb impression with a thumb print already saved in SQL database? if yes then then how?
please describe some details of the application.
The images that are saved in the database, are they uploaded with the same application ? If so, you should add a new column where you will store the hash of the image.
You will have a table like this: |ID|ImageData|Hash|
This is how you can compute the hash:
string hash;
using(SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())
{
hash = Convert.ToBase64String(sha1.ComputeHash(byteArray));
}
Then, when you want to check if an uploaded image already exists in the database, you should compute the hash for it and send a query like:
string.Format("SELECT ID FROM Images WHERE Hash={0}", hash);
This will tell you if the exact same bytes are already in the database. If the image is similar, it will not work. It must be identical.
NOTE: you will have to convert your image into a byte array. This should not be a problem if you already do this when saving images in the database.
You might want to look in Computer Vision and Principal Component Analysis if you want to look for similarities between images.

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 retrieve images from file system instead of database

I need a place to store images. My first thought was to use the database, but many seems to recommend using the filesystem. This seems to fit my case, but how do I implement it?
The filenames need to be unique, how to do that. Should I use a guid?
How to retrieve the files, should I go directly to the database using the filename, make a aspx page and passing either filename or primary key as a querystring and then read the file.
What about client side caching, is that enabled when using a page like image.aspx?id=123 ?
How do I delete the files, when the associated record is deleted?
I guess there are many other things that I still haven't thought about.
Links, samples and guidelines are very welcome!
Uploading Files in ASP.NET 2.0
You seem up in the air about how to do this, so I'll give you a few ideas to get you going.
If you want to use a file system make sure you know the limit of how many files are permitted per directory, so you can set up a system that creates subdirectories. http://ask-leo.com/is_there_a_limit_to_what_a_single_folder_or_directory_can_hold.html
I would make a table something like this :
FileUpload
UploadID int identity/auto generate PK, used as FK in other tables
InternalFileName string
DisplayFileName string
Comment string
MimeType string
FileSizeBytes int
FileHash string MD5 Hash of a File
UploadUserID int FK to UserID
UploadDate date
You would include the UploadID in the table that "owns" this upload, like the Order associated with it, etc. You could add the InternalDirectory column, but I prefer to calculate this based on a constant Root value + some key specific value. For example, the complete file name and directory would be:
Constant_Root+'\'+OrderID+'\'+InternalFileName
You could make the InternalFileName be the UploadID and the file extension from the original file. That way it would be unique, but You'll have to insert the row as the first part of the process, and update it after after you know the file name and identity/auto generate row value. You could make the InternalFileName something like YYYMMDDhhmissmmm and the file extension from the original file, which may be unique enough based on how you use subdirectories.
I like to store a MD5 Hash of a File which makes detecting duplicates easy.
MimeType and FileSizeBytes can be found from the file system, but if you store them in the database, it makes some maintenance easier since you can query for large files or files of certain types.

How to load, save and display data from GridView to XML?

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 ('|')

Resources