Archive for Maggio 21st, 2008

add SQL para

CodeKeep C# Feed Maggio 21st, 2008

Description: add SQL para

Link: http://www.codekeep.net/snippets/32b4567a-416d-47e0-8dd1-ecbbff58900c.aspx

SqlParameter para = dbCmd.Parameters.Add("para", SqlDbType.Int, 4);
para.Value = ;

Streaming Object to DB in Binary format

CodeKeep C# Feed Maggio 21st, 2008

Description: Take an objsct, serialize it, store it in a db, retrieve it and recreate the object

Link: http://www.codekeep.net/snippets/3a616b3f-a02c-400c-bb91-b118549ead82.aspx

		/// <summary>
		/// Cache the gpEncounter to DB
		/// </summary>
		private void SaveToCache()
		{
			// Serialize to a memory stream
			MemoryStream stream = new MemoryStream();
			DataContractSerializer serializer = new DataContractSerializer(typeof(GpEncounter));
			serializer.WriteObject(stream, _gpEncounter);
			// Just make sure we're pointing at the beginning of the stream
			stream.Seek(0, SeekOrigin.Begin);
			// Save stream to the DB
			CachingDataAccess.CacheGpEncounter(_guid, stream);
			//Clean up
		}
		/// <summary>
		/// Retrieve the GpEncounter from the DB
		/// </summary>
		private void RetrieveFromCache()
		{
			byte[] rawdata = CachingDataAccess.UnCacheGpEncounter(_guid);
			MemoryStream stream = new MemoryStream(rawdata);
			DataContractSerializer serializer = new DataContractSerializer(typeof(GpEncounter));
			stream.Seek(0, SeekOrigin.Begin);
			_gpEncounter = (GpEncounter) serializer.ReadObject(stream);
		}

		public static bool CacheGpEncounter(Guid guid, MemoryStream gpEncounterMemoryStream)
		{
			Database db = DatabaseFactory.CreateDatabase("StatConnection");
			byte[] bytes = gpEncounterMemoryStream.ToArray();//NB Do Not use GetBuffer()
			string sqlCommand = @"Delete from Cache where CacheGUID = @guid;
								INSERT INTO Cache (CacheGUID, Blob) VALUES  (@guid, @data )";
			DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand);
			db.AddInParameter(dbCommand, "guid", DbType.Guid, guid);
			db.AddInParameter(dbCommand, "data", DbType.Binary, bytes);
			db.ExecuteNonQuery(dbCommand);
			return true;

		}
		public static Byte[] UnCacheGpEncounter(Guid guid)
		{
			Database db = DatabaseFactory.CreateDatabase("StatConnection");
			string sqlCommand = @"SELECT Blob FROM Cache WHERE CacheGUID = @guid";
			DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand);
			db.AddInParameter(dbCommand, "guid", DbType.Guid, guid);
			DataTable table = new DataTable();
			byte[] bytes = (byte[]) db.ExecuteScalar(dbCommand);

			return bytes;
		}