[libagilejedi commit] r21 - in trunk: AgileJedi.MemcachedForMonorail AgileJedi.MemcachedForMonorail.Tests Thirdparty/Ca...

1 view
Skip to first unread message

codesite...@google.com

unread,
Dec 1, 2008, 10:42:21 PM12/1/08
to libagileje...@googlegroups.com
Author: Daniel.Pupek
Date: Mon Dec 1 19:41:25 2008
New Revision: 21

Modified:

trunk/AgileJedi.MemcachedForMonorail.Tests/AgileJedi.MemcachedForMonorail.Tests.csproj

trunk/AgileJedi.MemcachedForMonorail.Tests/MemcachedSessionDictionaryTests.cs
trunk/AgileJedi.MemcachedForMonorail/ARSessionItem.cs

trunk/AgileJedi.MemcachedForMonorail/AgileJedi.MemcachedForMonorail.csproj
trunk/AgileJedi.MemcachedForMonorail/MemCacheDB.cs
trunk/Thirdparty/CastleProjects/build/net-2.0/release/nunit.framework.dll
trunk/Thirdparty/Memcached/InstallService.bat
trunk/Thirdparty/Memcached/memcached.exe

Log:
Now uses ASP session as temporary local cache

Modified:
trunk/AgileJedi.MemcachedForMonorail.Tests/AgileJedi.MemcachedForMonorail.Tests.csproj
==============================================================================
---
trunk/AgileJedi.MemcachedForMonorail.Tests/AgileJedi.MemcachedForMonorail.Tests.csproj
(original)
+++
trunk/AgileJedi.MemcachedForMonorail.Tests/AgileJedi.MemcachedForMonorail.Tests.csproj
Mon Dec 1 19:41:25 2008
@@ -56,12 +56,25 @@
<SpecificVersion>False</SpecificVersion>
<HintPath>..\Thirdparty\Memcached\Enyim.Caching.dll</HintPath>
</Reference>
+ <Reference Include="NHibernate, Version=2.0.0.1001, Culture=neutral,
PublicKeyToken=aa95f207798dfdb4, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+
<HintPath>..\Thirdparty\CastleProjects\build\net-2.0\release\NHibernate.dll</HintPath>
+ </Reference>
+ <Reference Include="nunit.core.extensions, Version=2.4.8.0,
Culture=neutral, PublicKeyToken=96d09a1eb7f44a77,
processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+
<HintPath>..\Thirdparty\CastleProjects\build\net-2.0\release\nunit.core.extensions.dll</HintPath>
+ </Reference>
<Reference Include="nunit.framework, Version=2.2.8.0, Culture=neutral,
PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
- <HintPath>..\..\..\..\..\..\..\Program
Files\CastleProject\Bin\Dependencies\nunit.framework.dll</HintPath>
+
<HintPath>..\Thirdparty\CastleProjects\build\net-2.0\release\nunit.framework.dll</HintPath>
+ </Reference>
+ <Reference Include="nunit.framework.extensions, Version=2.4.8.0,
Culture=neutral, PublicKeyToken=96d09a1eb7f44a77,
processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+
<HintPath>..\Thirdparty\CastleProjects\build\net-2.0\release\nunit.framework.extensions.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Data" />
+ <Reference Include="System.Web" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>

Modified:
trunk/AgileJedi.MemcachedForMonorail.Tests/MemcachedSessionDictionaryTests.cs
==============================================================================
---
trunk/AgileJedi.MemcachedForMonorail.Tests/MemcachedSessionDictionaryTests.cs
(original)
+++
trunk/AgileJedi.MemcachedForMonorail.Tests/MemcachedSessionDictionaryTests.cs
Mon Dec 1 19:41:25 2008
@@ -8,6 +8,8 @@
using Enyim.Caching.Memcached;
using Castle.ActiveRecord;
using System.Collections;
+using System.Web.SessionState;
+using System.Web;

namespace AgileJedi.MemcachedForMonorail.Tests
{
@@ -17,19 +19,28 @@
[TestFixture()]
public class MemcachedSessionDictionaryTests
{
- private IDictionary session;
+ private MemCachedSessionDictionary session;
+ private MemCachedSessionDictionary httpSession;
private MemcachedClient client;
string configPath =
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(MemCachedSessionDictionary)).CodeBase);

- private bool useActiveRecord = true;
+ private bool useActiveRecord = false;
+ private HttpSessionState sessionState;

[TestFixtureSetUp]
public void TestFixtureSetup()
{
configPath = System.IO.Path.Combine(configPath, "ActiveRecord.config");
+
+ HttpContext.Current = new HttpContext(new
HttpRequest("", "http://localhost/", ""), new HttpResponse(new
System.IO.StringWriter()));
+ SessionStateUtility.AddHttpSessionStateToContext(
+ HttpContext.Current, new HttpSessionStateContainer(
+ "testSessionState", new SessionStateItemCollection(), new
HttpStaticObjectsCollection(), 20000, true, HttpCookieMode.UseCookies,
SessionStateMode.Off, false));

+ sessionState = HttpContext.Current.Session;
+
MemCachedSessionDictionary.SetupActiveRecordDBConnection(configPath);
- MemCachedSessionDictionary.SetupRawDBConnection();
+
MemCachedSessionDictionary.SetupRawDBConnection(ActiveRecordMediator.GetSessionFactoryHolder().GetSessionFactory(typeof(ARSessionItem)).Settings.ConnectionProvider.GetConnection().ConnectionString);
}

[TestFixtureTearDown]
@@ -44,8 +55,9 @@
[SetUp]
public void Setup()
{
- client = new
MemcachedClient(MemCachedSessionDictionary.STR_Sessionstate);
+ client = new
MemcachedClient(MemCachedSessionDictionary.DEFAULT_MEMCACHED_CONFIG_SECTION);
session = new MemCachedSessionDictionary(Guid.NewGuid(), client);
+ httpSession = new MemCachedSessionDictionary(Guid.NewGuid(),
this.sessionState, client);
((MemCachedSessionDictionary)session).UseActiveRecord = useActiveRecord;
}

@@ -53,12 +65,24 @@
public void TearDown()
{
session.Clear();
+ httpSession.Clear();
+ }
+
+ private IDictionary getSession(string arg)
+ {
+ if (arg == "session")
+ return session;
+ else
+ return httpSession;
}

#region Standard Smoke Tests
- [Test]
- public void SetValueAndReadItTest()
+ [NUnit.Framework.Extensions.RowTest]
+ [NUnit.Framework.Extensions.Row("session")]
+ [NUnit.Framework.Extensions.Row("httpSession")]
+ public void SetValueAndReadItTest(string arg)
{
+ IDictionary session = getSession(arg);
string testValue = "the value";
string testKey = "testvalue";
session.Add(testKey, testValue);
@@ -67,9 +91,12 @@

}

- [Test]
- public void RemoveValueTest()
+ [NUnit.Framework.Extensions.RowTest]
+ [NUnit.Framework.Extensions.Row("session")]
+ [NUnit.Framework.Extensions.Row("httpSession")]
+ public void RemoveValueTest(string arg)
{
+ IDictionary session = getSession(arg);
string testKey = "removethisvalue";
string testValue = "this should be removed";
session.Add(testKey, testValue);
@@ -78,18 +105,210 @@

session.Remove(testKey);

+ ((MemCachedSessionDictionary)session).persistValues();
+
Assert.IsNull(session[testKey]);
}

- [Test]
- public void StoreSerializableObject()
+ [NUnit.Framework.Extensions.RowTest]
+ [NUnit.Framework.Extensions.Row("session")]
+ [NUnit.Framework.Extensions.Row("httpSession")]
+ public void RemoveValueTestAfterPersist(string arg)
+ {
+ IDictionary session = getSession(arg);
+ string testKey = "removethisvalue";
+ string testValue = "this should be removed";
+ session.Add(testKey, testValue);
+
+ Assert.AreEqual(testValue, session[testKey], "RemoveValueTest cannot
continue. Setting Failed.");
+
+ ((MemCachedSessionDictionary)session).persistValues();
+
+ Assert.AreEqual(testValue, session[testKey], "RemoveValueTest cannot
continue. Setting Failed.");
+
+ session.Remove(testKey);
+
+ Assert.IsNull(session[testKey]);
+ }
+
+ [NUnit.Framework.Extensions.RowTest]
+ [NUnit.Framework.Extensions.Row("session")]
+ [NUnit.Framework.Extensions.Row("httpSession")]
+ public void RemoveValueTestAfterPersist2(string arg)
+ {
+ IDictionary session = getSession(arg);
+ string testKey = "removethisvalue";
+ string testValue = "this should be removed";
+ session.Add(testKey, testValue);
+
+ Assert.AreEqual(testValue, session[testKey], "RemoveValueTest cannot
continue. Setting Failed.");
+
+ ((MemCachedSessionDictionary)session).persistValues();
+
+ Assert.AreEqual(testValue, session[testKey], "RemoveValueTest cannot
continue. Setting Failed.");
+
+ session.Remove(testKey);
+
+ ((MemCachedSessionDictionary)session).persistValues();
+
+ Assert.IsNull(session[testKey]);
+ }
+
+ [NUnit.Framework.Extensions.RowTest]
+ [NUnit.Framework.Extensions.Row("session")]
+ [NUnit.Framework.Extensions.Row("httpSession")]
+ public void RemoveValueTestAfterPersistAndMemcacheFlush(string arg)
+ {
+ IDictionary session = getSession(arg);
+ string testKey = "removethisvalue";
+ string testValue = "this should be removed";
+ session.Add(testKey, testValue);
+
+ Assert.AreEqual(testValue, session[testKey], "RemoveValueTest cannot
continue. Setting Failed.");
+
+ ((MemCachedSessionDictionary)session).persistValues();
+
+ Assert.AreEqual(testValue, session[testKey], "RemoveValueTest cannot
continue. Setting Failed.");
+
+ session[testKey] = null;
+ Assert.IsNull(session[testKey], "The key should return null after being
set to null.");
+ Assert.IsFalse(session.Contains(testKey), "The key should return not
contains after being set to null.");
+
+ ((MemCachedSessionDictionary)session).persistValues();
+
+ Assert.IsNull(session[testKey], "The key should return null after being
set to null.");
+ Assert.IsFalse(session.Contains(testKey), "The key should return not
contains after being set to null.");
+
+ client.FlushAll();
+
+ Assert.IsNull(session[testKey], "The key should return null after being
set to null.");
+ Assert.IsFalse(session.Contains(testKey), "The key should return not
contains after being set to null.");
+
+
+
+ }
+
+ [NUnit.Framework.Extensions.RowTest]
+ [NUnit.Framework.Extensions.Row("session")]
+ [NUnit.Framework.Extensions.Row("httpSession")]
+ public void AddDuplicates(string arg)
+ {
+ IDictionary session = getSession(arg);
+
+ string testKey = "removethisvalue";
+ string testValue = "this should be removed";
+ session.Add(testKey, testValue);
+
+ Assert.AreEqual(testValue, session[testKey], "RemoveValueTest cannot
continue. Setting Failed.");
+
+ ((MemCachedSessionDictionary)session).persistValues();
+
+ Assert.AreEqual(testValue, session[testKey], "RemoveValueTest cannot
continue. Setting Failed.");
+
+ session.Add(testKey, testValue);
+
+ Assert.AreEqual(testValue, session[testKey], "RemoveValueTest cannot
continue. Setting Failed.");
+
+
+ ((MemCachedSessionDictionary)session).persistValues();
+
+ Assert.AreEqual(testValue, session[testKey], "RemoveValueTest cannot
continue. Setting Failed.");
+
+ session.Add(testKey, testValue);
+
+ Assert.AreEqual(testValue, session[testKey], "RemoveValueTest cannot
continue. Setting Failed.");
+
+ ((MemCachedSessionDictionary)session).persistValues();
+
+ Assert.AreEqual(testValue, session[testKey], "RemoveValueTest cannot
continue. Setting Failed.");
+
+ session.Add(testKey, testValue);
+
+ Assert.AreEqual(testValue, session[testKey], "RemoveValueTest cannot
continue. Setting Failed.");
+
+
+ ((MemCachedSessionDictionary)session).persistValues();
+ client.FlushAll();
+
+ Assert.AreEqual(testValue, session[testKey], "RemoveValueTest cannot
continue. Setting Failed.");
+
+ session.Add(testKey, testValue);
+
+ Assert.AreEqual(testValue, session[testKey], "RemoveValueTest cannot
continue. Setting Failed.");
+
+
+
+ }
+
+ [NUnit.Framework.Extensions.RowTest]
+ [NUnit.Framework.Extensions.Row("session")]
+ [NUnit.Framework.Extensions.Row("httpSession")]
+ public void StoreSerializableObject(string arg)
{
+ IDictionary session = getSession(arg);
TestingObject obj = new TestingObject();
obj.SomeString = "This is a test";
session.Add("testobject", obj);
obj = (TestingObject)session["testobject"];
+ Assert.AreEqual("This is a test", obj.SomeString);
+
+ ///
+ /// Now clear the local cache and flush the memcach client
+ ///
+ ((MemCachedSessionDictionary)session).ClearLocalCache();
+
+
+
+ client.FlushAll();
+ obj = (TestingObject)session["testobject"];

Assert.AreEqual("This is a test", obj.SomeString);
+
+ }
+
+ [NUnit.Framework.Extensions.RowTest]
+ [NUnit.Framework.Extensions.Row("session")]
+ [NUnit.Framework.Extensions.Row("httpSession")]
+ [Category("Performance Tests")]
+ public void StoreLARGESerializableObject(string arg)
+ {
+ IDictionary session = getSession(arg);
+ Hashtable obj = new Hashtable();
+
+
+ const int tableSize = 100000;
+ for (int i = 0; i < tableSize; i++)
+ {
+ obj.Add(i, Guid.NewGuid());
+ }
+ Console.WriteLine("Finished Creating Hashtable");
+ Console.WriteLine(DateTime.Now.ToString());
+ session.Add("test", obj);
+
+ Console.WriteLine("Finished Adding");
+ Console.WriteLine(DateTime.Now.ToString());
+
+ ((MemCachedSessionDictionary)session).persistValues();
+ Console.WriteLine("Finished Persisting");
+ Console.WriteLine(DateTime.Now.ToString());
+ ///
+ /// Now clear the local cache and flush the memcach client
+ ///
+ ((MemCachedSessionDictionary)session).ClearLocalCache();
+
+ obj = (Hashtable)session["test"];
+ Console.WriteLine("Finished Retrieving after Flushing Local Cache");
+ Console.WriteLine(DateTime.Now.ToString());
+
+ client.FlushAll();
+ obj = (Hashtable)session["test"];
+
+ Console.WriteLine("Finished Retrieving after Flushing Memcache");
+ Console.WriteLine(DateTime.Now.ToString());
+
+ Assert.IsNotNull(obj);
+ Assert.AreEqual(obj.Count, tableSize);
+
}

[Test, Ignore]
@@ -110,9 +329,12 @@
Assert.Fail("Test Not Implemented");
}

- [Test]
- public void ClearTheSessionTest()
+ [NUnit.Framework.Extensions.RowTest]
+ [NUnit.Framework.Extensions.Row("session")]
+ [NUnit.Framework.Extensions.Row("httpSession")]
+ public void ClearTheSessionTest(string arg)
{
+ IDictionary session = getSession(arg);
for (int i = 0; i < 100; i++)
{
session.Add("testKey" + i.ToString(), "testValue");
@@ -128,17 +350,24 @@
}
}

- [Test]
- public void UnsetItemReturnsNullTest()
+ [NUnit.Framework.Extensions.RowTest]
+ [NUnit.Framework.Extensions.Row("session")]
+ [NUnit.Framework.Extensions.Row("httpSession")]
+ public void UnsetItemReturnsNullTest(string arg)
{
+ IDictionary session = getSession(arg);
Assert.IsNull(session["nonexistentkey"]);
}
#endregion

#region DB Persistence Tests
+ [NUnit.Framework.Extensions.RowTest]
+ [NUnit.Framework.Extensions.Row("session")]
+ [NUnit.Framework.Extensions.Row("httpSession")]
[Test]
- public void SaveObjectAndClearMemcached()
+ public void SaveObjectAndClearMemcached(string arg)
{
+ IDictionary session = getSession(arg);
TestingObject obj = new TestingObject();
session["testobject"] = obj;
client.FlushAll();
@@ -147,29 +376,37 @@
#endregion

#region Performance Tests
- [Test]
- public void InsertionPerformanceTest()
+ [NUnit.Framework.Extensions.RowTest]
+ [NUnit.Framework.Extensions.Row("session")]
+ [NUnit.Framework.Extensions.Row("httpSession")]
+ [Category("Performance Tests")]
+ public void InsertionPerformanceTest(string arg)
{
- int insertions = 10000;
+ IDictionary session = getSession(arg);
+ int insertions = 1000;
Queue<TimingRecord> durationQueue = new Queue<TimingRecord>();

+
+
((MemCachedSessionDictionary)session).UseDatabase = true;
((MemCachedSessionDictionary)session).UseActiveRecord = true;
durationQueue.Enqueue(new TimingRecord("ActiveRecord",
InsertionPerformanceFunc("ActiveRecordDB", insertions)));
+ session.Clear();

((MemCachedSessionDictionary)session).UseDatabase = true;
((MemCachedSessionDictionary)session).UseActiveRecord = false;
durationQueue.Enqueue(new TimingRecord("direct database connection",
InsertionPerformanceFunc("directDB------", insertions)));
+ session.Clear();

((MemCachedSessionDictionary)session).UseDatabase = false;
durationQueue.Enqueue(new TimingRecord("no database persistance",
InsertionPerformanceFunc("NoDB----------", insertions)));

- while (durationQueue.Count != 0)
+ foreach(TimingRecord record in durationQueue)
{
- Console.Out.WriteLine(String.Format("{0} insertions with {1} database
persistance : {2}", insertions, durationQueue.Peek().recordType,
durationQueue.Dequeue().recordDuration));
+ Console.Out.WriteLine(String.Format("{0} insertions with {1} database
persistance : {2}", insertions, record.recordType, record.recordDuration));
}
}

@@ -181,6 +418,7 @@
{
session.Add(keyPrefix + i.ToString(), "testValue");
}
+ ((MemCachedSessionDictionary)session).persistValues();
stop = DateTime.UtcNow;
return (stop - start);
}
@@ -259,6 +497,49 @@
Console.Write(" seconds for defaultSerialize");
Console.WriteLine();
client.FlushAll();
+ }
+ #endregion
+
+ #region Multi Server Tests
+
+ [Test]
+ public void SameServerSequentialRequests()
+ {
+ // use the session to write a value
+ this.httpSession["foo"] = "bar";
+ httpSession.persistValues(); // commit
+
+ // erase the value in memcached
+ int revision = MemCachedSessionDictionary.GetSessionRevision(client,
httpSession.SessionId);
+
client.Remove(MemCachedSessionDictionary.GetMemCachedKey(httpSession.SessionId,
revision, "foo"));
+
+ // create a new memcached dictionary
+ httpSession = new MemCachedSessionDictionary(httpSession.SessionId,
this.sessionState, client);
+
+ // read te value
+ Assert.AreEqual("bar", httpSession["foo"]);
+ }
+
+ [Test]
+ public void TwoServers()
+ {
+ MemCachedSessionDictionary serverA = this.httpSession;
+ MemCachedSessionDictionary serverB = new
MemCachedSessionDictionary(httpSession.SessionId, this.sessionState,
client);
+
+ // use the session to write a value
+ serverA["foo"] = "bar";
+ serverA.persistValues(); // commit
+
+ // read the value on server B
+ Assert.AreEqual("bar", serverB["foo"]);
+
+ // server B makes changes:
+ serverB["foo"] = "qux";
+
+ // server A should not get this untill it is re-initialized:
+ Assert.AreEqual("bar", serverA["foo"]);
+ serverA.ClearLocalCache();
+ Assert.AreEqual("qux", serverA["foo"]);
}
#endregion


Modified: trunk/AgileJedi.MemcachedForMonorail/ARSessionItem.cs
==============================================================================
--- trunk/AgileJedi.MemcachedForMonorail/ARSessionItem.cs (original)
+++ trunk/AgileJedi.MemcachedForMonorail/ARSessionItem.cs Mon Dec 1
19:41:25 2008
@@ -16,7 +16,7 @@
/// <summary>
/// Used to persist session items to a database
/// </summary>
- [ActiveRecord("SessionItems")]
+ [ActiveRecord("SessionItems", Lazy=true, BatchSize=100)]
public class ARSessionItem
{
private static BinaryFormatter serializer = new BinaryFormatter();
@@ -35,13 +35,14 @@

private Guid _id = Guid.NewGuid();
[PrimaryKey(PrimaryKeyType.Assigned, Access =
PropertyAccess.NosetterLowercaseUnderscore)]
- public Guid Id
+ public virtual Guid Id
{
get { return _id; }
}

- [Property(Access=PropertyAccess.Property, NotNull=false)]
- public byte[] ItemData
+
+ [Property(Access = PropertyAccess.Property, ColumnType
= "BinaryBlob",SqlType="image", NotNull = false)]
+ public virtual byte[] ItemData
{
get
{
@@ -60,7 +61,7 @@
}

private object _value = null;
- public object Value
+ public virtual object Value
{
get {

@@ -72,18 +73,18 @@

}
}
-
+
private Guid _sessionId;
- [Property]
- public Guid SessionId
+ [Property(UniqueKey = "SessionIdKey", NotNull = true)]
+ public virtual Guid SessionId
{
get { return _sessionId; }
set { _sessionId = value; }
}

private string _key;
- [Property("[Key]")]
- public string Key
+ [Property("ItemKey", UniqueKey = "SessionIdKey", NotNull=true)]
+ public virtual string Key
{
get { return _key; }
set { _key = value; }
@@ -94,17 +95,23 @@
return ActiveRecordMediator.FindOne(typeof(ARSessionItem),
Restrictions.And(Restrictions.Eq("SessionId", sessionId),
Restrictions.Eq("Key", key))) as ARSessionItem;
}

- internal void Create()
+ internal virtual void Create()
{
ActiveRecordMediator<ARSessionItem>.Create(this);
}

- internal void Remove()
+ internal virtual void Remove()
{
ActiveRecordMediator<ARSessionItem>.Delete(this);
}

- internal static void RemoveSession(Guid guid)
+ internal static void Remove(Guid sessionid, string key)
+ {
+ ActiveRecordMediator<ARSessionItem>.DeleteAll(typeof(ARSessionItem),
String.Format("SessionId = '{0}' AND ItemKey = '{1}'",sessionid, key));
+
+ }
+
+ internal static void RemoveSession(Guid guid)
{

ActiveRecordMediator<ARSessionItem>.DeleteAll(typeof(ARSessionItem), "SessionId
= '" + guid + "'");
}

Modified:
trunk/AgileJedi.MemcachedForMonorail/AgileJedi.MemcachedForMonorail.csproj
==============================================================================
---
trunk/AgileJedi.MemcachedForMonorail/AgileJedi.MemcachedForMonorail.csproj
(original)
+++
trunk/AgileJedi.MemcachedForMonorail/AgileJedi.MemcachedForMonorail.csproj
Mon Dec 1 19:41:25 2008
@@ -75,8 +75,8 @@
</ItemGroup>
<ItemGroup>
<Compile Include="ARSessionItem.cs" />
- <Compile Include="CustomSessionState\MemCacheSessionFactory.cs" />
- <Compile Include="CustomSessionState\MemCachedSession.cs" />
+ <Compile
Include="CustomSessionStateExtensions\MemCacheSessionFactory.cs" />
+ <Compile
Include="CustomSessionStateExtensions\MemCachedSessionDictionary.cs" />
<Compile Include="MemCacheDB.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Transcoders\FastSerializerTranscoder.cs" />

Modified: trunk/AgileJedi.MemcachedForMonorail/MemCacheDB.cs
==============================================================================
--- trunk/AgileJedi.MemcachedForMonorail/MemCacheDB.cs (original)
+++ trunk/AgileJedi.MemcachedForMonorail/MemCacheDB.cs Mon Dec 1 19:41:25
2008
@@ -10,42 +10,62 @@
{
public class MemCacheDB : IDisposable
{
- private static string cnStr = "Data Source=.\\SQLEXPRESS;Initial
Catalog=MEMCACHED;Integrated Security=true;";
- private static int guidLength = Guid.Empty.ToString().Length;
- private static String persistSQL = "Insert Into [SessionItems]
(SessionId, [Key], ItemData) Values (@SESSIONID_VAL, @KEY_VAL,
@ITEMDATA_VAL)";
- private static String removeSQL = "Delete From SessionItems Where
SessionId = @SESSIONID_VAL and [Key] = @KEY_VAL";
- private static String retrieveSQL = "Select ItemData From SessionItems
Where SessionId = @SESSIONID_VAL and [Key] = @KEY_VAL";
- private static String removeSessionSQL = "Delete From SessionItems Where
SessionId = @SESSIONID_VAL";
+
+ private string cnStr = "Data Source=.\\SQLEXPRESS;Initial
Catalog=MEMCACHED;Integrated Security=true;";
+
+ private static int guidLength = Guid.Empty.ToString().Length;
+ private const String persistSQL = @"IF NOT EXISTS (Select SessionId FROM
SessionItems
+ WHERE SessionId = @SESSIONID_VAL AND ItemKey = @KEY_VAL)
+ Insert Into [SessionItems] (Id, SessionId, [ItemKey], ItemData)
+ Values (NewId(), @SESSIONID_VAL, @KEY_VAL, @ITEMDATA_VAL)
+ ELSE
+ UPDATE SessionItems
+ SET ItemData = @ITEMDATA_VAL
+ WHERE SessionId = @SESSIONID_VAL AND ItemKey = @KEY_VAL";
+ private const String removeSQL = "Delete From SessionItems Where
SessionId = @SESSIONID_VAL and [ItemKey] = @KEY_VAL";
+ private const String retrieveSQL = "Select ItemData From SessionItems
Where SessionId = @SESSIONID_VAL and [ItemKey] = @KEY_VAL";
+ private const String removeSessionSQL = "Delete From SessionItems Where
SessionId = @SESSIONID_VAL";
+ private const String countSQL = "Select count(*) as ItemCount From
SessionItems Where SessionId = @SESSIONID_VAL and [ItemKey] = @KEY_VAL";

private SqlConnection cn;
- private SqlCommand persistCommand, removeCommand, retrieveCommand,
clearSessionCommand;
+ private SqlCommand persistCommand, removeCommand, retrieveCommand,
clearSessionCommand, countCommand;
private SqlDataReader reader;
private MemoryStream ms;
private BinaryFormatter serializer = new BinaryFormatter();
- private static int SessionIndex = 0;
- private static int KeyIndex = 1;
+
+ public void SetConnectionString(string cnStr)
+ {
+ this.cnStr = cnStr;
+ SetupConnection();
+ }

public void InitParams()
{
- persistCommand = new SqlCommand(persistSQL, cn);
- persistCommand.Parameters.Add(new SqlParameter("@SESSIONID_VAL",
System.Data.SqlDbType.UniqueIdentifier, 36));
- persistCommand.Parameters.Add(new SqlParameter("@KEY_VAL",
System.Data.SqlDbType.VarChar, 50));
- persistCommand.Parameters.Add(new SqlParameter("@ITEMDATA_VAL",
System.Data.SqlDbType.Image, int.MaxValue));
- //persistCommand.Prepare();
-
- removeCommand = new SqlCommand(removeSQL, cn);
- removeCommand.Parameters.Add(new SqlParameter("@SESSIONID_VAL",
System.Data.SqlDbType.UniqueIdentifier, 36));
- removeCommand.Parameters.Add(new SqlParameter("@KEY_VAL",
System.Data.SqlDbType.VarChar, 50));
- //removeCommand.Prepare();
-
- retrieveCommand = new SqlCommand(retrieveSQL, cn);
- retrieveCommand.Parameters.Add(new SqlParameter("@SESSIONID_VAL",
System.Data.SqlDbType.UniqueIdentifier, 36));
- retrieveCommand.Parameters.Add(new SqlParameter("@KEY_VAL",
System.Data.SqlDbType.VarChar, 50));
- //retrieveCommand.Prepare();
-
- clearSessionCommand = new SqlCommand(removeSessionSQL, cn);
- clearSessionCommand.Parameters.Add(new SqlParameter("@SESSIONID_VAL",
System.Data.SqlDbType.UniqueIdentifier, 36));
- //clearSessionCommand.Prepare();
+ persistCommand = new SqlCommand(persistSQL);
+ persistCommand.Parameters.Add(new SqlParameter("SESSIONID_VAL",
System.Data.SqlDbType.UniqueIdentifier, 36));
+ persistCommand.Parameters.Add(new SqlParameter("KEY_VAL",
System.Data.SqlDbType.VarChar, 50));
+ persistCommand.Parameters.Add(new SqlParameter("ITEMDATA_VAL",
System.Data.SqlDbType.Image, int.MaxValue));
+ persistCommand.CommandType = System.Data.CommandType.Text;
+
+
+ removeCommand = new SqlCommand(removeSQL);
+ removeCommand.Parameters.Add(new SqlParameter("SESSIONID_VAL",
System.Data.SqlDbType.UniqueIdentifier, 36));
+ removeCommand.Parameters.Add(new SqlParameter("KEY_VAL",
System.Data.SqlDbType.VarChar, 50));
+
+
+ retrieveCommand = new SqlCommand(retrieveSQL);
+ retrieveCommand.Parameters.Add(new SqlParameter("SESSIONID_VAL",
System.Data.SqlDbType.UniqueIdentifier, 36));
+ retrieveCommand.Parameters.Add(new SqlParameter("KEY_VAL",
System.Data.SqlDbType.VarChar, 50));
+
+
+ countCommand = new SqlCommand(countSQL);
+ countCommand.Parameters.Add(new SqlParameter("SESSIONID_VAL",
System.Data.SqlDbType.UniqueIdentifier, 36));
+ countCommand.Parameters.Add(new SqlParameter("KEY_VAL",
System.Data.SqlDbType.VarChar, 50));
+
+
+ clearSessionCommand = new SqlCommand(removeSessionSQL);
+ clearSessionCommand.Parameters.Add(new SqlParameter("SESSIONID_VAL",
System.Data.SqlDbType.UniqueIdentifier, 36));
+
}
public void SetupConnection()
{
@@ -77,53 +97,155 @@

public void PersistRecord(Guid sessionId, String key, object value)
{
- ms = new MemoryStream();
- serializer.Serialize(ms, value);
- ms.Position = 0;
- persistCommand.Parameters[0].Value = sessionId;
- persistCommand.Parameters[1].Value = key;
- persistCommand.Parameters[2].Value = ms.ToArray();
- persistCommand.ExecuteNonQuery();
+ using (SqlConnection connection = new SqlConnection(this.cnStr))
+ {
+ connection.Open();
+ SqlCommand cmd = persistCommand.Clone();
+ cmd.Connection = connection;
+ cmd.Prepare();
+ try
+ {
+
+ if (cmd.Connection.State == System.Data.ConnectionState.Closed)
+ {
+ cmd.Connection.Open();
+ }
+
+
+ ms = new MemoryStream();
+ serializer.Serialize(ms, value);
+ ms.Position = 0;
+ cmd.Parameters[0].Value = sessionId;
+ cmd.Parameters[1].Value = key;
+ cmd.Parameters[2].Value = ms.ToArray();
+ cmd.ExecuteNonQuery();
+ }
+ catch (Exception ex)
+ {
+ throw new System.Data.DataException(String.Format("Failed to persist
record {0} for session {1}", key, sessionId), ex);
+ }
+ finally
+ {
+ cmd.Connection.Close();
+ }
+ }
}

public void RemoveRecord(Guid sessionId, string key)
{
- removeCommand.Parameters[0].Value = sessionId;
- removeCommand.Parameters[1].Value = key;
- removeCommand.ExecuteNonQuery();
+ using (SqlConnection connection = new SqlConnection(this.cnStr))
+ {
+ connection.Open();
+ SqlCommand cmd = removeCommand.Clone();
+ cmd.Connection = connection;
+ cmd.Prepare();
+
+ if (cmd.Connection.State == System.Data.ConnectionState.Closed)
+ {
+ cmd.Connection.Open();
+ }
+ cmd.Parameters[0].Value = sessionId;
+ cmd.Parameters[1].Value = key;
+ cmd.ExecuteNonQuery();
+
+ }
}

public object RetrieveRecord(Guid sessionId, string key)
{
- retrieveCommand.Parameters[0].Value = sessionId;
- retrieveCommand.Parameters[1].Value = key;

- reader = retrieveCommand.ExecuteReader();
- if (reader.Read())
- {
- ms = new MemoryStream((byte[])reader["ItemData"]);
- reader.Close();
- reader.Dispose();
- return serializer.Deserialize(ms);
- }
- else
+ using (SqlConnection connection = new SqlConnection(this.cnStr))
{
- reader.Close();
- reader.Dispose();
- return null;
+ connection.Open();
+
+ SqlCommand cmd = retrieveCommand.Clone();
+ cmd.Connection = connection;
+ cmd.Prepare();
+
+ try
+ {
+ cmd.Parameters[0].Value = sessionId;
+ cmd.Parameters[1].Value = key;
+
+
+ reader = cmd.ExecuteReader();
+ if (reader != null && !reader.IsClosed && reader.Read())
+ {
+ ms = new MemoryStream((byte[])reader["ItemData"]);
+ return serializer.Deserialize(ms);
+ }
+ else
+ {
+ return null;
+ }
+ }
+ catch (Exception ex)
+ {
+ throw ex;
+ }
+ finally
+ {
+ if (!reader.IsClosed) reader.Close();
+ reader.Dispose();
+ }
}
}
- public void RemoveSession(Guid sessionId)
- {
- clearSessionCommand.Parameters[0].Value = sessionId;
- clearSessionCommand.ExecuteNonQuery();
- }

- private void SetVal(int paramIndex, Object value, SqlCommand command)
+ public bool RecordExists(Guid sessionId, string key)
+ {
+
+ using (SqlConnection connection = new
SqlConnection(this.cnStr))
+ {
+ connection.Open();
+
+ SqlCommand cmd = countCommand.Clone();
+ cmd.Connection = connection;
+ cmd.Prepare();
+
+ try
+ {
+ int count = 0;
+ cmd.Parameters[0].Value = sessionId;
+ cmd.Parameters[1].Value = key;
+
+
+ count = (int)cmd.ExecuteScalar();
+ return count > 0;
+
+ }
+ catch (Exception ex)
+ {
+ throw ex;
+ }
+
+ }
+ }
+
+ public void RemoveSession(Guid sessionId)
{
- //persistParams[paramIndex].Value = value;
- //command.Parameters.Add(persistParams[paramIndex]);
+ using (SqlConnection connection = new SqlConnection(this.cnStr))
+ {
+ connection.Open();
+ SqlCommand cmd = clearSessionCommand.Clone();
+ cmd.Connection = connection;
+ cmd.Prepare();
+ try
+ {
+ if (cmd.Connection.State == System.Data.ConnectionState.Closed)
+ {
+ cmd.Connection.Open();
+ }
+
+ cmd.Parameters[0].Value = sessionId;
+ cmd.ExecuteNonQuery();
+ }
+ finally
+ {
+ cmd.Connection.Close();
+ }
+ }
}
+

#region IDisposable Members
public void Dispose()

Modified:
trunk/Thirdparty/CastleProjects/build/net-2.0/release/nunit.framework.dll
==============================================================================
Binary files. No diff available.

Modified: trunk/Thirdparty/Memcached/InstallService.bat
==============================================================================
--- trunk/Thirdparty/Memcached/InstallService.bat (original)
+++ trunk/Thirdparty/Memcached/InstallService.bat Mon Dec 1 19:41:25 2008
@@ -13,9 +13,10 @@

ECHO Copying...
COPY memcached.exe C:\MEMCACHED\*.*
+COPY msvcr71.dll C:\MEMCACHED\*.*
COPY StartMemcached.bat C:\MEMCACHED\*.*
COPY StopMemcached.bat C:\MEMCACHED\*.*
c:\memcached\memcached.exe -d install

-ECHO Use the start script in C:\MEMCACHED to start the service
+ECHO Use the start script in C:\MEMCACHED\StartMemcached.bat to start the
service
pause

Modified: trunk/Thirdparty/Memcached/memcached.exe
==============================================================================
Binary files. No diff available.

Reply all
Reply to author
Forward
0 new messages