17.07.2015 Views

The Art of SQL Server FILESTREAM - Red Gate Software

The Art of SQL Server FILESTREAM - Red Gate Software

The Art of SQL Server FILESTREAM - Red Gate Software

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 3: Accessing <strong>FILESTREAM</strong> Data from Client Applicationsusing System.Data.SqlTypes;using System.IO;public void SaveItemImage(){byte[] txContext = null;string filePath = string.Empty;// Create a connection to the databasestring ConStr = ("Data Source=(local);" +"Initial Catalog=NorthPole;Integrated Security=True");SqlConnection con = new SqlConnection(ConStr);con.Open();Listing 3-14:Creating a connection to the <strong>SQL</strong> <strong>Server</strong> instance.Note that to access <strong>FILESTREAM</strong> data through the streaming API, you must connect to<strong>SQL</strong> <strong>Server</strong> using Integrated Security (Windows authentication). If you connect to <strong>SQL</strong><strong>Server</strong> using <strong>SQL</strong> <strong>Server</strong> authentication, you will get an "Access Denied" error when youtry to open the <strong>FILESTREAM</strong> data file.Next, we insert a row with a dummy value into the <strong>FILESTREAM</strong> column in the Itemstable, using the T-<strong>SQL</strong> INSERT statement shown in Listing 3-15. Notice the OUTPUTclause, which returns the path name associated with the <strong>FILESTREAM</strong> column <strong>of</strong> thenewly inserted row, along with the current <strong>FILESTREAM</strong> transaction context.// Insert a record to the table and retrieve the PathName()// A dummy value is inserted to the ItemImage column to obtain a valid PathName()SqlCommand cmd = new SqlCommand();cmd.Connection = con;cmd.CommandText = "INSERT INTO Items " +"(ItemID, ItemNumber, ItemDescription, ItemImage)" +"OUTPUT GET_<strong>FILESTREAM</strong>_TRANSACTION_CONTEXT() AS txContext," +" inserted.ItemImage.PathName() AS filePath " +"SELECT NEWID(), 'A0001', 'Micros<strong>of</strong>t Mouse', 0x";107

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!