Home
Manage Your Code
Snippet: Streaming Object to DB in Binary format (C#)
Title: Streaming Object to DB in Binary format Language: C#
Description: Take an objsct, serialize it, store it in a db, retrieve it and recreate the object Views: 86
Author: Max Young Date Added: 5/20/2008
Copy Code  
1		/// <summary>
2		/// Cache the gpEncounter to DB
3		/// </summary>
4		private void SaveToCache()
5		{
6			// Serialize to a memory stream        
7			MemoryStream stream = new MemoryStream();
8			DataContractSerializer serializer = new DataContractSerializer(typeof(GpEncounter));
9			serializer.WriteObject(stream, _gpEncounter);
10			// Just make sure we're pointing at the beginning of the stream
11			stream.Seek(0, SeekOrigin.Begin);
12			// Save stream to the DB
13			CachingDataAccess.CacheGpEncounter(_guid, stream);
14			//Clean up
15		}
16		/// <summary>
17		/// Retrieve the GpEncounter from the DB
18		/// </summary>
19		private void RetrieveFromCache()
20		{
21			byte[] rawdata = CachingDataAccess.UnCacheGpEncounter(_guid);
22			MemoryStream stream = new MemoryStream(rawdata);
23			DataContractSerializer serializer = new DataContractSerializer(typeof(GpEncounter));
24			stream.Seek(0, SeekOrigin.Begin);
25			_gpEncounter = (GpEncounter) serializer.ReadObject(stream);
26		}
27
28		public static bool CacheGpEncounter(Guid guid, MemoryStream gpEncounterMemoryStream)
29		{
30			Database db = DatabaseFactory.CreateDatabase("StatConnection");
31			byte[] bytes = gpEncounterMemoryStream.ToArray();//NB Do Not use GetBuffer()
32			string sqlCommand = @"Delete from Cache where CacheGUID = @guid;
33								INSERT INTO Cache (CacheGUID, Blob) VALUES  (@guid, @data )";
34			DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand);
35			db.AddInParameter(dbCommand, "guid", DbType.Guid, guid);
36			db.AddInParameter(dbCommand, "data", DbType.Binary, bytes);
37			db.ExecuteNonQuery(dbCommand);
38			return true;
39
40		}
41		public static Byte[] UnCacheGpEncounter(Guid guid)
42		{
43			Database db = DatabaseFactory.CreateDatabase("StatConnection");
44			string sqlCommand = @"SELECT Blob FROM Cache WHERE CacheGUID = @guid";
45			DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand);
46			db.AddInParameter(dbCommand, "guid", DbType.Guid, guid);
47			DataTable table = new DataTable();
48			byte[] bytes = (byte[]) db.ExecuteScalar(dbCommand);
49
50			return bytes;
51		}
52
Usage
Assumes a table called Cache, with columns CacheGUID and data