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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 5: <strong>FILESTREAM</strong> with ASP.NET and Silverlight{cmd.Transaction = tran;cmd.Parameters.Add(new SqlParameter("itemID",System.Data.SqlDbType.VarChar, 20));cmd.Parameters["itemID"].Value = itemID;using (SqlDataReader dr = cmd.ExecuteReader()){if (dr.HasRows && dr.Read()){using (SqlFileStream sfs = new SqlFileStream(dr.GetString(0),(byte[])dr.GetValue(1), FileAccess.Read)){// This construct is used to avoid problems with a// <strong>FILESTREAM</strong> data file that exceeds 4 GB in sizems = new MemoryStream((int)System.Math.Min(sfs.Length, int.MaxValue));}}}}}// Copy the SqlFileStream contents to the// MemoryStream (requires .NET 4.0 and later)sfs.CopyTo(ms);}}return ms;Listing 5-15:Code for the ItemData class.In this method, new SqlConnection and SqlTransaction objects are created.Those are then used to retrieve the information necessary to create an instance <strong>of</strong> theSqlFileStream class. Recall that in Chapter 4, as part <strong>of</strong> the second Entity Frameworklab, we created a stored procedure that encapsulates this. That stored procedure could bereused here instead <strong>of</strong> the embedded <strong>SQL</strong> statement. <strong>The</strong>n the contents <strong>of</strong> theSqlFileStream are copied to a new instance <strong>of</strong> System.IO.MemoryStream,which is then used as the return value <strong>of</strong> the method.208

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

Saved successfully!

Ooh no, something went wrong!