Permalink
Browse files

first commit

  • Loading branch information...
0 parents commit e6a21a615d9ab502400e1ea9bf50250431243719 @Sedward Sedward committed Mar 18, 2010
67 MongoDBSessionStore/MongoSessionStore.csproj
@@ -0,0 +1,67 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <ProductVersion>9.0.30729</ProductVersion>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{354D379B-E16C-40DE-B26F-8CCF2EDE94D8}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>MongoDBSessionStore</RootNamespace>
+ <AssemblyName>MongoDBSessionStore</AssemblyName>
+ <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
+ <FileAlignment>512</FileAlignment>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ <DebugSymbols>true</DebugSymbols>
+ <DebugType>full</DebugType>
+ <Optimize>false</Optimize>
+ <OutputPath>bin\Debug\</OutputPath>
+ <DefineConstants>DEBUG;TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ <DebugType>pdbonly</DebugType>
+ <Optimize>true</Optimize>
+ <OutputPath>bin\Release\</OutputPath>
+ <DefineConstants>TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <ItemGroup>
+ <Reference Include="MongoDB.Driver, Version=1.0.3729.17015, Culture=neutral, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>..\..\mongo\mongodb-csharp\MongoDBDriver\bin\Debug\MongoDB.Driver.dll</HintPath>
+ </Reference>
+ <Reference Include="System" />
+ <Reference Include="System.configuration" />
+ <Reference Include="System.Core">
+ <RequiredTargetFramework>3.5</RequiredTargetFramework>
+ </Reference>
+ <Reference Include="System.Web" />
+ <Reference Include="System.Xml.Linq">
+ <RequiredTargetFramework>3.5</RequiredTargetFramework>
+ </Reference>
+ <Reference Include="System.Data.DataSetExtensions">
+ <RequiredTargetFramework>3.5</RequiredTargetFramework>
+ </Reference>
+ <Reference Include="System.Data" />
+ <Reference Include="System.Xml" />
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="MongoSessionStoreProvider.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="Session.cs" />
+ <Compile Include="SessionStore.cs" />
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
+ Other similar extension points exist, see Microsoft.Common.targets.
+ <Target Name="BeforeBuild">
+ </Target>
+ <Target Name="AfterBuild">
+ </Target>
+ -->
+</Project>
369 MongoDBSessionStore/MongoSessionStoreProvider.cs
@@ -0,0 +1,369 @@
+using System;
+using System.Diagnostics;
+using System.IO;
+using System.Text;
+using System.Collections.Specialized;
+using System.Web;
+using System.Web.Configuration;
+using System.Configuration;
+using System.Configuration.Provider;
+using System.Web.SessionState;
+using MongoDB.Driver;
+using MongoDB.Driver.Configuration;
+
+
+namespace MongoDBSessionStore
+{
+ public sealed class MongoSessionStoreProvider : SessionStateStoreProviderBase
+ {
+ private SessionStateSection sessionStateSection = null;
+ private string eventSource = "MongoSessionStore";
+ private string eventLog = "Application";
+
+ private bool _logExceptions = false;
+ public bool WriteExceptionsToEventLog
+ {
+ get { return _logExceptions; }
+ set { _logExceptions = value; }
+ }
+
+ //
+ // The ApplicationName property is used to differentiate sessions
+ // in the data source by application.
+ //
+ public string _applicationName;
+ public string ApplicationName
+ {
+ get { return _applicationName; }
+ }
+
+ public override void Initialize(string name, NameValueCollection config)
+ {
+ if (config == null)
+ throw new ArgumentNullException("config");
+
+ if (name == null || name.Length == 0)
+ name = "MongoSessionStore";
+
+ if (String.IsNullOrEmpty(config["description"]))
+ {
+ config.Remove("description");
+ config.Add("description", "MongoDB Session State Store provider");
+ }
+ // Initialize the abstract base class.
+ base.Initialize(name, config);
+
+ _applicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
+
+ Configuration cfg = WebConfigurationManager.OpenWebConfiguration(ApplicationName);
+ sessionStateSection = (SessionStateSection)cfg.GetSection("system.web/sessionState");
+ if (config["writeExceptionsToEventLog"] != null)
+ {
+ if (config["writeExceptionsToEventLog"].ToUpper() == "TRUE")
+ _logExceptions = true;
+ }
+ }
+
+ public override void Dispose()
+ {
+ }
+
+ public override bool SetItemExpireCallback(SessionStateItemExpireCallback expireCallback)
+ {
+ return false;
+ }
+
+ public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem)
+ {
+ string sessionItems = Serialize((SessionStateItemCollection)item.Items);
+
+ try
+ {
+ if (newItem)
+ {
+ // Delete an existing expired session if it exists.
+ SessionStore.EvictExpiredSession(id, _applicationName);
+
+ // insert new session item.
+ Session session = new Session(id, this._applicationName, item.Timeout, sessionItems, item.Items.Count,0);
+ SessionStore.Insert(session);
+ }
+ else
+ {
+ SessionStore.UpdateSession(id, DateTime.Now.AddMinutes((Double)item.Timeout), sessionItems, this._applicationName, item.Items.Count, lockId);
+ }
+ }
+ catch (Exception e)
+ {
+ if (WriteExceptionsToEventLog)
+ {
+ WriteToEventLog(e, "SetAndReleaseItemExclusive");
+ throw new ProviderException(e.Message, e.InnerException);
+ }
+ else
+ throw e;
+ }
+ }
+
+
+ public override SessionStateStoreData GetItem(HttpContext context,
+ string id,
+ out bool locked,
+ out TimeSpan lockAge,
+ out object lockId,
+ out SessionStateActions actionFlags)
+ {
+ return GetSessionStoreItem(false, context, id, out locked, out lockAge, out lockId, out actionFlags);
+ }
+
+ public override SessionStateStoreData GetItemExclusive(HttpContext context,
+ string id,
+ out bool locked,
+ out TimeSpan lockAge,
+ out object lockId,
+ out SessionStateActions actionFlags)
+ {
+ return GetSessionStoreItem(true, context, id, out locked, out lockAge, out lockId, out actionFlags);
+ }
+
+
+ //
+ // GetSessionStoreItem is called by both the GetItem and
+ // GetItemExclusive methods. GetSessionStoreItem retrieves the
+ // session data from the data source. If the lockRecord parameter
+ // is true (in the case of GetItemExclusive), then GetSessionStoreItem
+ // locks the record and sets a new LockId and LockDate.
+ //
+ private SessionStateStoreData GetSessionStoreItem(bool lockRecord,
+ HttpContext context,
+ string id,
+ out bool locked,
+ out TimeSpan lockAge,
+ out object lockId,
+ out SessionStateActions actionFlags)
+ {
+ // Initial values for return value and out parameters.
+ SessionStateStoreData item = null;
+ lockAge = TimeSpan.Zero;
+ lockId = null;
+ locked = false;
+ actionFlags = 0;
+
+ // String to hold serialized SessionStateItemCollection.
+ string serializedItems = "";
+ // Timeout value from the data store.
+ int timeout = 0;
+
+ try
+ {
+ Session session = SessionStore.Get(id, this._applicationName);
+ // lockRecord is true when called from GetItemExclusive and
+ // false when called from GetItem.
+ // Obtain a lock if possible. Evict the record if it is expired.
+ if (session == null)
+ {
+ // Not found. The locked value is false.
+ locked = false;
+ }
+ else if(session.Expires < DateTime.Now)
+ {
+ locked = false;
+ SessionStore.EvictSession(session);
+
+ }
+ else if (session.Locked)
+ {
+ locked = true;
+ lockAge = DateTime.Now.Subtract(session.LockDate);
+ lockId = session.LockID;
+ }
+ else
+ {
+ locked = false;
+ lockId = session.LockID;
+ actionFlags = (SessionStateActions)session.Flags;
+ //timeout = reader.GetInt32(5);
+
+ if (lockRecord)
+ {
+ lockId = (int)lockId + 1;
+ session.LockID = lockId;
+ session.Flags = 0;
+ SessionStore.LockSession(session);
+ }
+
+ if (actionFlags == SessionStateActions.InitializeItem)
+ item = CreateNewStoreData(context, sessionStateSection.Timeout.Minutes);
+ else
+ item = Deserialize(context, serializedItems, timeout);
+ }
+
+ }
+ catch (Exception e)
+ {
+ if (WriteExceptionsToEventLog)
+ {
+ WriteToEventLog(e, "GetSessionStoreItem");
+ throw new ProviderException(e.Message,e.InnerException);
+ }
+ else
+ throw e;
+ }
+ return item;
+ }
+
+ //
+ // Serialize is called by the SetAndReleaseItemExclusive method to
+ // convert the SessionStateItemCollection into a Base64 string to
+ // be stored in an Access Memo field.
+ //
+
+ private string Serialize(SessionStateItemCollection items)
+ {
+ MemoryStream ms = new MemoryStream();
+ BinaryWriter writer = new BinaryWriter(ms);
+
+ if (items != null)
+ items.Serialize(writer);
+
+ writer.Close();
+
+ return Convert.ToBase64String(ms.ToArray());
+ }
+
+ //
+ // DeSerialize is called by the GetSessionStoreItem method to
+ // convert the Base64 string stored in the Access Memo field to a
+ // SessionStateItemCollection.
+ //
+
+ private SessionStateStoreData Deserialize(HttpContext context, string serializedItems, int timeout)
+ {
+ MemoryStream ms =
+ new MemoryStream(Convert.FromBase64String(serializedItems));
+
+ SessionStateItemCollection sessionItems =
+ new SessionStateItemCollection();
+
+ if (ms.Length > 0)
+ {
+ BinaryReader reader = new BinaryReader(ms);
+ sessionItems = SessionStateItemCollection.Deserialize(reader);
+ }
+
+ return new SessionStateStoreData(sessionItems,
+ SessionStateUtility.GetSessionStaticObjects(context),
+ timeout);
+ }
+
+ //
+ // SessionStateProviderBase.ReleaseItemExclusive
+ //
+ public override void ReleaseItemExclusive(HttpContext context, string id, object lockId)
+ {
+ try
+ {
+ SessionStore.ReleaseLock(id, this._applicationName, lockId);
+ }
+ catch (Exception e)
+ {
+ if (WriteExceptionsToEventLog)
+ {
+ WriteToEventLog(e, "ReleaseItemExclusive");
+ throw new ProviderException(e.Message,e.InnerException);
+ }
+ else
+ throw e;
+ }
+
+ }
+
+
+ //
+ // SessionStateProviderBase.RemoveItem
+ //
+
+ public override void RemoveItem(HttpContext context, string id, object lockId, SessionStateStoreData item)
+ {
+ try
+ {
+ SessionStore.EvictSession(id, this._applicationName, lockId);
+ }
+ catch (Exception e)
+ {
+ if (WriteExceptionsToEventLog)
+ {
+ WriteToEventLog(e, "RemoveItem");
+ throw new ProviderException(e.Message,e.InnerException);
+ }
+ else
+ throw e;
+ }
+ }
+
+ public override void CreateUninitializedItem(HttpContext context,string id,int timeout)
+ {
+ Session session = new Session(id,this._applicationName, timeout, String.Empty, 0, SessionStateActions.InitializeItem);
+
+ try
+ {
+ SessionStore.Insert(session);
+ }
+ catch (Exception e)
+ {
+ if (WriteExceptionsToEventLog)
+ {
+ WriteToEventLog(e, "CreateUninitializedItem");
+ throw new ProviderException(e.Message,e.InnerException);
+ }
+ else
+ throw e;
+ }
+ }
+
+ public override SessionStateStoreData CreateNewStoreData(HttpContext context,int timeout)
+ {
+ return new SessionStateStoreData(new SessionStateItemCollection(),SessionStateUtility.GetSessionStaticObjects(context),timeout);
+ }
+
+ public override void ResetItemTimeout(HttpContext context, string id)
+ {
+ try
+ {
+ SessionStore.UpdateSessionExpiration(id, DateTime.Now.AddMinutes(sessionStateSection.Timeout.TotalMinutes));
+ }
+ catch (Exception e)
+ {
+ if (WriteExceptionsToEventLog)
+ {
+ WriteToEventLog(e, "ResetItemTimeout");
+ throw new ProviderException(e.Message,e.InnerException);
+ }
+ else
+ throw e;
+ }
+ }
+
+ public override void InitializeRequest(HttpContext context)
+ {
+ }
+
+
+ public override void EndRequest(HttpContext context)
+ {
+ }
+
+ private void WriteToEventLog(Exception e, string action)
+ {
+ EventLog log = new EventLog();
+ log.Source = eventSource;
+ log.Log = eventLog;
+
+ string message =
+ "An exception occurred ";
+ message += "Action: " + action + "\n\n";
+ message += "Exception: " + e.ToString();
+ log.WriteEntry(message);
+ }
+ }
+}
36 MongoDBSessionStore/Properties/AssemblyInfo.cs
@@ -0,0 +1,36 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("MongoDBSessionStore")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("Microsoft")]
+[assembly: AssemblyProduct("MongoDBSessionStore")]
+[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("a73ef248-cdcf-40f0-9f41-f393abfc1825")]
+
+// Version information for an assembly consists of the following four values:
+//
+// Major Version
+// Minor Version
+// Build Number
+// Revision
+//
+// You can specify all the values or you can default the Build and Revision Numbers
+// by using the '*' as shown below:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
114 MongoDBSessionStore/Session.cs
@@ -0,0 +1,114 @@
+using System;
+using System.Configuration;
+using System.Collections.Generic;
+using System.Web.SessionState;
+using System.Text;
+using MongoDB.Driver;
+using MongoDB.Driver.Configuration;
+
+namespace MongoDBSessionStore
+{
+ public class Session
+ {
+ private string _sessionID;
+ private DateTime _created;
+ private DateTime _expires;
+ private string _applicationName;
+ private DateTime _lockDate;
+ private object _lockID;
+ private int _timeout;
+ private bool _locked;
+ private string _sessionItems;
+ private int _sessionItemsCount;
+ private int _flags;
+
+
+ private OidGenerator oGen;
+
+ public Session() { }
+
+ public Session(string id, string applicationName, int timeout, string sessionItems, int sessionItemsCount,SessionStateActions actionFlags )
+ {
+ this._sessionID = id;
+ this._applicationName = applicationName;
+ this._lockDate = DateTime.Now;
+ this._lockID = 0;
+ this._timeout = timeout;
+ this._locked = false;
+ this._sessionItems = sessionItems;
+ this._sessionItemsCount = sessionItemsCount;
+ this._flags = (int)actionFlags;
+ this._created = DateTime.Now;
+ this._expires = DateTime.Now.AddMinutes((Double)this._timeout);
+ }
+
+ #region Properties
+ public string SessionID
+ {
+ get { return this._sessionID; }
+ set { this._sessionID = value; }
+ }
+
+ public DateTime Created
+ {
+ get { return this._created; }
+ set { this._created = value; }
+ }
+
+ public DateTime Expires
+ {
+ get { return this._expires; }
+ set { this._expires = value; }
+ }
+
+ public string ApplicationName
+ {
+ get { return this._applicationName; }
+ set { this._applicationName = value; }
+ }
+
+ public DateTime LockDate
+ {
+ get { return this._lockDate; }
+ set { this._lockDate = value; }
+ }
+
+ public object LockID
+ {
+ get { return this._lockID; }
+ set { this._lockID = value; }
+ }
+
+ public int Timeout
+ {
+ get { return this._timeout; }
+ set { this._timeout = value; }
+ }
+
+ public bool Locked
+ {
+ get { return this._locked; }
+ set { this._locked = value; }
+ }
+
+ public string SessionItems
+ {
+ get { return this._sessionItems; }
+ set { this._sessionItems = value; }
+ }
+
+ public int SessionItemsCount
+ {
+ get { return this._sessionItemsCount; }
+ set { this._sessionItemsCount = value; }
+ }
+
+ public int Flags
+ {
+ get { return this._flags; }
+ set { this._flags = value; }
+ }
+ #endregion
+
+ }
+}
16 MongoDBSessionStore/SessionStore.cs
@@ -0,0 +1,16 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace MongoDBSessionStore
+{
+ public class SessionStore
+ {
+
+ public static void Insert(Session session)
+ {
+
+ }
+ }
+}
7 MongoDBSessionStore/obj/Debug/MongoDBSessionStore.csproj.FileListAbsolute.txt
@@ -0,0 +1,7 @@
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\MongoDBSessionStore\obj\Debug\ResolveAssemblyReference.cache
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\MongoDBSessionStore\bin\Debug\MongoDBSessionStore.dll
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\MongoDBSessionStore\bin\Debug\MongoDBSessionStore.pdb
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\MongoDBSessionStore\bin\Debug\MongoDB.Driver.dll
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\MongoDBSessionStore\bin\Debug\MongoDB.Driver.pdb
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\MongoDBSessionStore\obj\Debug\MongoDBSessionStore.dll
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\MongoDBSessionStore\obj\Debug\MongoDBSessionStore.pdb
1 MongoDBSessionStore/obj/Debug/MongoSessionStore.csproj.FileListAbsolute.txt
@@ -0,0 +1 @@
+C:\Users\Seth\Projects\MongoSessionStore\MongoDBSessionStore\obj\Debug\ResolveAssemblyReference.cache
32 MongoSessionStore.sln
@@ -0,0 +1,32 @@
+
+Microsoft Visual Studio Solution File, Format Version 10.00
+# Visual Studio 2008
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoSessionStore", "MongoDBSessionStore\MongoSessionStore.csproj", "{354D379B-E16C-40DE-B26F-8CCF2EDE94D8}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SessionStoreTest", "SessionStoreTest\SessionStoreTest.csproj", "{BEF9F11E-FD05-4761-B772-A592CBCC5728}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoSessionTest", "MongoSessionTest\MongoSessionTest.csproj", "{883E3A81-A85D-4C7E-BC3A-D68738A951AF}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {354D379B-E16C-40DE-B26F-8CCF2EDE94D8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {354D379B-E16C-40DE-B26F-8CCF2EDE94D8}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {354D379B-E16C-40DE-B26F-8CCF2EDE94D8}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {354D379B-E16C-40DE-B26F-8CCF2EDE94D8}.Release|Any CPU.Build.0 = Release|Any CPU
+ {BEF9F11E-FD05-4761-B772-A592CBCC5728}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {BEF9F11E-FD05-4761-B772-A592CBCC5728}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {BEF9F11E-FD05-4761-B772-A592CBCC5728}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {BEF9F11E-FD05-4761-B772-A592CBCC5728}.Release|Any CPU.Build.0 = Release|Any CPU
+ {883E3A81-A85D-4C7E-BC3A-D68738A951AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {883E3A81-A85D-4C7E-BC3A-D68738A951AF}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {883E3A81-A85D-4C7E-BC3A-D68738A951AF}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {883E3A81-A85D-4C7E-BC3A-D68738A951AF}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
BIN MongoSessionStore.suo
Binary file not shown.
16 MongoSessionTest/Default.aspx
@@ -0,0 +1,16 @@
+<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MongoSessionTest._Default" %>
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml" >
+<head runat="server">
+ <title></title>
+</head>
+<body>
+ <form id="form1" runat="server">
+ <div>
+
+ </div>
+ </form>
+</body>
+</html>
21 MongoSessionTest/Default.aspx.cs
@@ -0,0 +1,21 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Web;
+using System.Web.UI;
+using System.Web.UI.WebControls;
+
+namespace MongoSessionTest
+{
+ public partial class _Default : System.Web.UI.Page
+ {
+ protected void Page_Load(object sender, EventArgs e)
+ {
+ System.Web.SessionState.SessionIDManager manager = new System.Web.SessionState.SessionIDManager();
+
+ string sessionID = manager.CreateSessionID(HttpContext.Current);
+ Response.Write(sessionID);
+
+ }
+ }
+}
27 MongoSessionTest/Default.aspx.designer.cs
@@ -0,0 +1,27 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+// This code was generated by a tool.
+// Runtime Version:2.0.50727.42
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace MongoSessionTest
+{
+
+
+ public partial class _Default
+ {
+
+ /// <summary>
+ /// form1 control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.HtmlControls.HtmlForm form1;
+ }
+}
100 MongoSessionTest/MongoSessionTest.csproj
@@ -0,0 +1,100 @@
+<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <ProductVersion>9.0.30729</ProductVersion>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{883E3A81-A85D-4C7E-BC3A-D68738A951AF}</ProjectGuid>
+ <ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>MongoSessionTest</RootNamespace>
+ <AssemblyName>MongoSessionTest</AssemblyName>
+ <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ <DebugSymbols>true</DebugSymbols>
+ <DebugType>full</DebugType>
+ <Optimize>false</Optimize>
+ <OutputPath>bin\</OutputPath>
+ <DefineConstants>DEBUG;TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ <DebugType>pdbonly</DebugType>
+ <Optimize>true</Optimize>
+ <OutputPath>bin\</OutputPath>
+ <DefineConstants>TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <ItemGroup>
+ <Reference Include="System" />
+ <Reference Include="System.Data" />
+ <Reference Include="System.Core">
+ <RequiredTargetFramework>3.5</RequiredTargetFramework>
+ </Reference>
+ <Reference Include="System.Data.DataSetExtensions">
+ <RequiredTargetFramework>3.5</RequiredTargetFramework>
+ </Reference>
+ <Reference Include="System.Web.Extensions">
+ <RequiredTargetFramework>3.5</RequiredTargetFramework>
+ </Reference>
+ <Reference Include="System.Xml.Linq">
+ <RequiredTargetFramework>3.5</RequiredTargetFramework>
+ </Reference>
+ <Reference Include="System.Drawing" />
+ <Reference Include="System.Web" />
+ <Reference Include="System.Xml" />
+ <Reference Include="System.Configuration" />
+ <Reference Include="System.Web.Services" />
+ <Reference Include="System.EnterpriseServices" />
+ <Reference Include="System.Web.Mobile" />
+ </ItemGroup>
+ <ItemGroup>
+ <Content Include="Default.aspx" />
+ <Content Include="Web.config" />
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="Default.aspx.cs">
+ <SubType>ASPXCodeBehind</SubType>
+ <DependentUpon>Default.aspx</DependentUpon>
+ </Compile>
+ <Compile Include="Default.aspx.designer.cs">
+ <DependentUpon>Default.aspx</DependentUpon>
+ </Compile>
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <Folder Include="App_Data\" />
+ </ItemGroup>
+ <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v9.0\WebApplications\Microsoft.WebApplication.targets" />
+ <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
+ Other similar extension points exist, see Microsoft.Common.targets.
+ <Target Name="BeforeBuild">
+ </Target>
+ <Target Name="AfterBuild">
+ </Target>
+ -->
+ <ProjectExtensions>
+ <VisualStudio>
+ <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
+ <WebProjectProperties>
+ <UseIIS>False</UseIIS>
+ <AutoAssignPort>True</AutoAssignPort>
+ <DevelopmentServerPort>51949</DevelopmentServerPort>
+ <DevelopmentServerVPath>/</DevelopmentServerVPath>
+ <IISUrl>
+ </IISUrl>
+ <NTLMAuthentication>False</NTLMAuthentication>
+ <UseCustomServer>False</UseCustomServer>
+ <CustomServerUrl>
+ </CustomServerUrl>
+ <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
+ </WebProjectProperties>
+ </FlavorProperties>
+ </VisualStudio>
+ </ProjectExtensions>
+</Project>
32 MongoSessionTest/MongoSessionTest.csproj.user
@@ -0,0 +1,32 @@
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <ProjectExtensions>
+ <VisualStudio>
+ <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}" xmlns="">
+ <WebProjectProperties>
+ <StartPageUrl>
+ </StartPageUrl>
+ <StartAction>CurrentPage</StartAction>
+ <AspNetDebugging>True</AspNetDebugging>
+ <NativeDebugging>False</NativeDebugging>
+ <SQLDebugging>False</SQLDebugging>
+ <PublishCopyOption>RunFiles</PublishCopyOption>
+ <PublishTargetLocation>
+ </PublishTargetLocation>
+ <PublishDeleteAllFiles>False</PublishDeleteAllFiles>
+ <PublishCopyAppData>True</PublishCopyAppData>
+ <ExternalProgram>
+ </ExternalProgram>
+ <StartExternalURL>
+ </StartExternalURL>
+ <StartCmdLineArguments>
+ </StartCmdLineArguments>
+ <StartWorkingDirectory>
+ </StartWorkingDirectory>
+ <EnableENC>False</EnableENC>
+ <AlwaysStartWebServerOnDebug>True</AlwaysStartWebServerOnDebug>
+ <EnableWcfTestClientForSVC>False</EnableWcfTestClientForSVC>
+ </WebProjectProperties>
+ </FlavorProperties>
+ </VisualStudio>
+ </ProjectExtensions>
+</Project>
35 MongoSessionTest/Properties/AssemblyInfo.cs
@@ -0,0 +1,35 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("MongoSessionTest")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("Microsoft")]
+[assembly: AssemblyProduct("MongoSessionTest")]
+[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("3d5900ae-111a-45be-96b3-d9e4606ca793")]
+
+// Version information for an assembly consists of the following four values:
+//
+// Major Version
+// Minor Version
+// Build Number
+// Revision
+//
+// You can specify all the values or you can default the Revision and Build Numbers
+// by using the '*' as shown below:
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
107 MongoSessionTest/Web.config
@@ -0,0 +1,107 @@
+<?xml version="1.0"?>
+<configuration>
+ <configSections>
+ <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
+ <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
+ <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
+ <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
+ <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
+ <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
+ <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
+ <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
+ </sectionGroup>
+ </sectionGroup>
+ </sectionGroup>
+ </configSections>
+ <appSettings/>
+ <connectionStrings/>
+ <system.web>
+ <!--
+ Set compilation debug="true" to insert debugging
+ symbols into the compiled page. Because this
+ affects performance, set this value to true only
+ during development.
+ -->
+ <compilation debug="true">
+ <assemblies>
+ <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
+ <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
+ <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
+ <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
+ </assemblies>
+ </compilation>
+ <!--
+ The <authentication> section enables configuration
+ of the security authentication mode used by
+ ASP.NET to identify an incoming user.
+ -->
+ <authentication mode="Windows"/>
+ <!--
+ The <customErrors> section enables configuration
+ of what to do if/when an unhandled error occurs
+ during the execution of a request. Specifically,
+ it enables developers to configure html error pages
+ to be displayed in place of a error stack trace.
+
+ <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
+ <error statusCode="403" redirect="NoAccess.htm" />
+ <error statusCode="404" redirect="FileNotFound.htm" />
+ </customErrors>
+ -->
+ <pages>
+ <controls>
+ <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
+ <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
+ </controls>
+ </pages>
+ <httpHandlers>
+ <remove verb="*" path="*.asmx"/>
+ <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
+ <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
+ <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
+ </httpHandlers>
+ <httpModules>
+ <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
+ </httpModules>
+ </system.web>
+ <system.codedom>
+ <compilers>
+ <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
+ <providerOption name="CompilerVersion" value="v3.5"/>
+ <providerOption name="WarnAsError" value="false"/>
+ </compiler>
+ </compilers>
+ </system.codedom>
+ <!--
+ The system.webServer section is required for running ASP.NET AJAX under Internet
+ Information Services 7.0. It is not necessary for previous version of IIS.
+ -->
+ <system.webServer>
+ <validation validateIntegratedModeConfiguration="false"/>
+ <modules>
+ <remove name="ScriptModule"/>
+ <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
+ </modules>
+ <handlers>
+ <remove name="WebServiceHandlerFactory-Integrated"/>
+ <remove name="ScriptHandlerFactory"/>
+ <remove name="ScriptHandlerFactoryAppServices"/>
+ <remove name="ScriptResource"/>
+ <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
+ <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
+ <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
+ </handlers>
+ </system.webServer>
+ <runtime>
+ <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
+ <dependentAssembly>
+ <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
+ <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
+ </dependentAssembly>
+ <dependentAssembly>
+ <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
+ <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
+ </dependentAssembly>
+ </assemblyBinding>
+ </runtime>
+</configuration>
BIN MongoSessionTest/bin/MongoSessionTest.dll
Binary file not shown.
BIN MongoSessionTest/bin/MongoSessionTest.pdb
Binary file not shown.
10 MongoSessionTest/obj/Debug/MongoSessionTest.csproj.FileListAbsolute.txt
@@ -0,0 +1,10 @@
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\MongoSessionTest\bin\MongoSessionTest.dll
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\MongoSessionTest\bin\MongoSessionTest.pdb
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\MongoSessionTest\obj\Debug\ResolveAssemblyReference.cache
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\MongoSessionTest\obj\Debug\MongoSessionTest.dll
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\MongoSessionTest\obj\Debug\MongoSessionTest.pdb
+C:\Users\Seth\Projects\MongoSessionStore\MongoSessionTest\bin\MongoSessionTest.dll
+C:\Users\Seth\Projects\MongoSessionStore\MongoSessionTest\bin\MongoSessionTest.pdb
+C:\Users\Seth\Projects\MongoSessionStore\MongoSessionTest\obj\Debug\ResolveAssemblyReference.cache
+C:\Users\Seth\Projects\MongoSessionStore\MongoSessionTest\obj\Debug\MongoSessionTest.dll
+C:\Users\Seth\Projects\MongoSessionStore\MongoSessionTest\obj\Debug\MongoSessionTest.pdb
BIN MongoSessionTest/obj/Debug/MongoSessionTest.dll
Binary file not shown.
BIN MongoSessionTest/obj/Debug/MongoSessionTest.pdb
Binary file not shown.
0 README
No changes.
11 SessionStoreTest/App.config
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<configuration>
+ <configSections>
+ <section name="Mongo" type="MongoDB.Driver.Configuration.MongoConfiguration, MongoDB.Driver" />
+ </configSections>
+ <Mongo>
+ <connections>
+ <add key="mongoserver" connectionString="Server=localhost:27018"/>
+ </connections>
+ </Mongo>
+</configuration>
36 SessionStoreTest/Properties/AssemblyInfo.cs
@@ -0,0 +1,36 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("SessionStoreTest")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("Microsoft")]
+[assembly: AssemblyProduct("SessionStoreTest")]
+[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("3436ad0f-8129-4b22-83e3-837b4aa89f31")]
+
+// Version information for an assembly consists of the following four values:
+//
+// Major Version
+// Minor Version
+// Build Number
+// Revision
+//
+// You can specify all the values or you can default the Build and Revision Numbers
+// by using the '*' as shown below:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
251 SessionStoreTest/SessionOpsTest.cs
@@ -0,0 +1,251 @@
+using System;
+using System.IO;
+using System.Configuration;
+using System.Collections.Generic;
+using System.Web;
+using System.Web.Configuration;
+using System.Configuration;
+using System.Configuration.Provider;
+using System.Web.SessionState;
+using System.Text;
+using NUnit.Framework;
+using MongoDB.Driver;
+using MongoDB.Driver.Connections;
+using MongoDB.Driver.Configuration;
+
+namespace SessionStoreTest
+{
+ [TestFixture]
+ public class SessionOpsTest
+ {
+ Connection conn;
+ Database db;
+ IMongoCollection sessions;
+ string ApplicationName = "TestApp";
+ SessionStateStoreData item;
+
+
+ Oid sessionID;
+
+ [SetUp]
+ public void SetUp()
+ {
+ MongoConfiguration config = (MongoConfiguration)System.Configuration.ConfigurationManager.GetSection("Mongo");
+ conn = ConnectionFactory.GetConnection(config.Connections["mongoserver"].ConnectionString);
+ db = new Database(conn, "SessionTest");
+ sessions = db.GetCollection("sessions");
+
+ SessionStateItemCollection sessionItems = new SessionStateItemCollection();
+ HttpStaticObjectsCollection staticObjects = new HttpStaticObjectsCollection();
+ item = new SessionStateStoreData(sessionItems, staticObjects, 1);
+ }
+
+ [Test]
+ public void TearDown()
+ {
+ conn.Open();
+ db["$cmd"].FindOne(new Document().Append("drop", "sessions"));
+ conn.Close();
+ }
+
+ [Test]
+ public void InsertNewSession()
+ {
+ string sessionItems = Serialize((SessionStateItemCollection)item.Items);
+ OidGenerator oGen = new OidGenerator();
+ sessionID = oGen.Generate();
+ Document newSession = new Document() { { "SessionId",sessionID }, {"ApplicationName",ApplicationName},{"Created",DateTime.Now},
+ {"Expires",DateTime.Now.AddMinutes((Double)item.Timeout)},{"LockDate",DateTime.Now},{"LockId",0},{"Timeout",item.Timeout},{"Locked",false},
+ {"SessionItems",sessionItems},{"SessionItemsCount",item.Items.Count},{"Flags",0}};
+
+ conn.Open();
+ sessions.Insert(newSession);
+ Document storedSession = sessions.FindOne(new Document() { { "SessionId", sessionID } });
+ conn.Close();
+
+ Assert.AreEqual(newSession["SessionItems"], storedSession["SessionItems"]);
+ }
+
+ [Test]
+ public void LockSession()
+ {
+ conn.Open();
+ string sessionItems = Serialize((SessionStateItemCollection)item.Items);
+ OidGenerator oGen = new OidGenerator();
+ sessionID = oGen.Generate();
+ Document newSession = new Document() { { "SessionId",sessionID }, {"ApplicationName",ApplicationName},{"Created",DateTime.Now},
+ {"Expires",DateTime.Now.AddMinutes((Double)item.Timeout)},{"LockDate",DateTime.Now},{"LockId",0},{"Timeout",item.Timeout},{"Locked",false},
+ {"SessionItems",sessionItems},{"SessionItemsCount",item.Items.Count},{"Flags",0}};
+
+ sessions.Insert(newSession);
+ Document storedSession = sessions.FindOne(new Document() { { "SessionId", sessionID } });
+ Document selector = new Document() { { "SessionId", sessionID }, { "ApplicationName", ApplicationName }, { "Expires", new Document() { { "$gt", DateTime.Now } } } };
+ Document session = new Document() { { "$set", new Document(){{ "LockDate", DateTime.Now }, { "LockId",1 }, { "Locked", true } }}};
+ sessions.Update(session, selector, 0, false);
+
+ Document lockedSession = sessions.FindOne(selector);
+ Assert.IsTrue((bool)lockedSession["Locked"]);
+
+ conn.Close();
+
+ }
+
+ [Test]
+ public void UpdateOrInsertSession()
+ {
+ conn.Open();
+ Document existingSession = sessions.FindOne(new Document(){{"Expires", new Document(){{"$gt", DateTime.Now}}}});
+ if (existingSession != null)
+ {
+ sessionID = (Oid)existingSession["SessionId"];
+ }
+ else
+ {
+ OidGenerator oGen = new OidGenerator();
+ sessionID = oGen.Generate();
+ }
+
+ object lockId = 0;
+ item.Items["ItemOne"] = "test one value updated";
+ item.Items["ItemTwo"] = 3;
+ item.Items["ItemThree"] = false;
+
+ string sessionItems = Serialize((SessionStateItemCollection)item.Items);
+ Document session = new Document() { { "SessionId",sessionID }, {"ApplicationName",ApplicationName},{"Created",DateTime.Now},
+ {"Expires",DateTime.Now.AddMinutes((Double)item.Timeout)},{"LockDate",DateTime.Now},{"LockId",0},{"Timeout",item.Timeout},{"Locked",false},
+ {"SessionItems",sessionItems},{"SessionItemsCount",item.Items.Count},{"Flags",0}};
+
+ Document selector = new Document(){{"SessionId",sessionID}};
+ sessions.Update(session,selector,1,false);
+
+
+ Document updatedSession = sessions.FindOne(session);
+ SessionStateItemCollection updatedItems = Deserialize((string)session["SessionItems"],item.Timeout);
+ Assert.AreEqual("test one value updated", (string)updatedItems["ItemOne"]);
+ Assert.AreEqual(3, (int)updatedItems["ItemTwo"]);
+ Assert.AreEqual(false, (bool)updatedItems["ItemThree"]);
+ Console.WriteLine((string)updatedItems["ItemOne"]);
+ conn.Close();
+ }
+
+ [Test]
+ public void DeleteExpiredSessions()
+ {
+
+ conn.Open();
+ //Add a Sessions that is expired by a couple of minutes;
+ string sessionItemsExpired = Serialize((SessionStateItemCollection)item.Items);
+ OidGenerator oGen = new OidGenerator();
+ sessionID = oGen.Generate();
+ Document expiredSession = new Document() { { "SessionId",sessionID }, {"ApplicationName",ApplicationName},{"Created",DateTime.Now},
+ {"Expires",DateTime.Now.Subtract(new TimeSpan(0,2,0))},{"LockDate",DateTime.Now},{"LockId",0},{"Timeout",item.Timeout},{"Locked",false},
+ {"SessionItems",sessionItemsExpired},{"SessionItemsCount",item.Items.Count},{"Flags",0}};
+ sessions.Insert(expiredSession);
+
+ //Add a Session that is not expired
+ string sessionItems = Serialize((SessionStateItemCollection)item.Items);
+ sessionID = oGen.Generate();
+ Document newSession = new Document() { { "SessionId",sessionID }, {"ApplicationName",ApplicationName},{"Created",DateTime.Now},
+ {"Expires",DateTime.Now.AddMinutes((Double)item.Timeout)},{"LockDate",DateTime.Now},{"LockId",0},{"Timeout",item.Timeout},{"Locked",false},
+ {"SessionItems",sessionItems},{"SessionItemsCount",item.Items.Count},{"Flags",0}};
+
+ sessions.Insert(newSession);
+
+ int i = 0;
+ ICursor before = sessions.FindAll();
+ foreach (Document d in before.Documents)
+ {
+ i++;
+ }
+ Assert.AreEqual(2, i);
+ conn.Close();
+
+ //Delete expired sessions
+
+ Document expiredSelector = new Document(){{ "Expires", new Document(){{ "$lt", DateTime.Now }}}};
+ sessions.Delete(expiredSelector);
+ ICursor after = sessions.FindAll();
+
+ i = 0;
+ foreach (Document d in after.Documents)
+ {
+ i++;
+ }
+ Assert.AreEqual(1,i);
+
+
+ }
+
+ [Test]
+ public void FindExpired()
+ {
+ Document expiredSelector = new Document() {{"Expires", new Document(){{"$lt", DateTime.Now }}}};
+ conn.Open();
+ ICursor expired = sessions.Find(expiredSelector);
+ Console.WriteLine(DateTime.Now.ToString());
+ foreach (Document session in expired.Documents)
+ {
+ string id = (string)session["SessionId"];
+ DateTime created = (DateTime)session["Created"];
+ created = created.ToLocalTime();
+ DateTime expires = (DateTime)session["Expires"];
+ expires = expires.ToLocalTime();
+ string applicationName = (string)session["ApplicationName"];
+ int sessionItemsCount = (int)session["SessionItemsCount"];
+ Console.WriteLine("SessionId:" + id + "| Created:" + created.ToString() + "| Expires:" + expires.ToString() + "| Application:" + applicationName + "| Total Items:" + sessionItemsCount.ToString());
+ }
+ conn.Close();
+ }
+
+
+ [Test]
+ public void DumpSessions()
+ {
+ conn.Open();
+ ICursor allSessions = sessions.FindAll();
+ foreach (Document session in allSessions.Documents)
+ {
+ string sessionid = (string)session["SessionId"];
+
+ DateTime created = (DateTime)session["Created"];
+ created = created.ToLocalTime();
+ DateTime expires = (DateTime)session["Expires"];
+ expires = expires.ToLocalTime();
+ string applicationName = (string)session["ApplicationName"];
+ int sessionItemsCount = (int)session["SessionItemsCount"];
+ bool locked = (bool)session["Locked"];
+ Console.WriteLine("SessionId:" + sessionid + " | Created:" + created.ToString() + " | Expires:" + expires.ToString() +" | Locked?: "+ locked.ToString() +" | Application:" + applicationName + " | Total Items:" + sessionItemsCount.ToString());
+ }
+ conn.Close();
+ }
+
+ private string Serialize(SessionStateItemCollection items)
+ {
+ MemoryStream ms = new MemoryStream();
+ BinaryWriter writer = new BinaryWriter(ms);
+ if (items != null)
+ items.Serialize(writer);
+ writer.Close();
+ return Convert.ToBase64String(ms.ToArray());
+ }
+
+
+ private SessionStateItemCollection Deserialize(string serializedItems, int timeout)
+ {
+ MemoryStream ms = new MemoryStream(Convert.FromBase64String(serializedItems));
+ SessionStateItemCollection sessionItems = new SessionStateItemCollection();
+
+ if (ms.Length > 0)
+ {
+ BinaryReader reader = new BinaryReader(ms);
+ sessionItems = SessionStateItemCollection.Deserialize(reader);
+ }
+
+ return sessionItems;
+ }
+
+
+
+
+ }
+}
125 SessionStoreTest/SessionStoreTest.cs
@@ -0,0 +1,125 @@
+using System;
+using System.IO;
+using System.Configuration;
+using System.Collections.Generic;
+using System.Web;
+using System.Web.SessionState;
+using System.Web.Configuration;
+using System.Configuration.Provider;
+using System.Text;
+using NUnit.Framework;
+using MongoDB.Driver;
+using MongoDB.Driver.Configuration;
+using MongoDB.Driver.Connections;
+using MongoSessionStore;
+
+
+namespace SessionStoreTest
+{
+ [TestFixture]
+ public class SessionStoreTest
+ {
+ Connection conn;
+ Database db;
+ IMongoCollection sessions;
+ string ApplicationName = "TestApp";
+ int Timeout = 2;
+ SessionStateStoreData item;
+ string sessionID;
+
+ [SetUp]
+ public void SetUp()
+ {
+ MongoConfiguration config = (MongoConfiguration)System.Configuration.ConfigurationManager.GetSection("Mongo");
+ conn = ConnectionFactory.GetConnection(config.Connections["mongoserver"].ConnectionString);
+ db = new Database(conn, "SessionTest");
+ sessions = db.GetCollection("sessions");
+
+ SessionStateItemCollection sessionItemsCollection = new SessionStateItemCollection();
+ HttpStaticObjectsCollection staticObjectsCollection = new HttpStaticObjectsCollection();
+ item = new SessionStateStoreData(sessionItemsCollection, staticObjectsCollection, 1);
+ }
+
+ [Test]
+ public void TearDown()
+ {
+ conn.Open();
+ db["$cmd"].FindOne(new Document().Append("drop", "sessions"));
+ conn.Close();
+ }
+
+ [Test]
+ public void InsertNewSession()
+ {
+
+ try
+ {
+ string sessionItems = Serialize((SessionStateItemCollection)item.Items);
+ OidGenerator oGen = new OidGenerator();
+ string id = oGen.Generate().ToString();
+ Session session = new Session(id, this.ApplicationName, this.Timeout, sessionItems, item.Items.Count, SessionStateActions.None);
+ SessionStore.Insert(session);
+ //Session storedSession = SessionStore.Get(id, this.ApplicationName);
+
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine(ex.Message + " " + ex.InnerException.Message);
+ }
+
+ //Session storedSession = SessionStore.Get(id, this.ApplicationName);
+ //if (storedSession == null)
+ //{
+ // Console.WriteLine("It's null");
+ //}
+ //Assert.AreEqual(session.SessionID, storedSession.SessionID);
+ //Assert.AreEqual(session.ApplicationName, storedSession.ApplicationName);
+ //Assert.AreEqual(session.Created, storedSession.Created);
+ }
+
+ [Test]
+ public void DumpSessions()
+ {
+ conn.Open();
+ ICursor allSessions = sessions.FindAll();
+ foreach (Document session in allSessions.Documents)
+ {
+ string id = (string)session["SessionId"];
+ DateTime created = (DateTime)session["Created"];
+ created = created.ToLocalTime();
+ DateTime expires = (DateTime)session["Expires"];
+ expires = expires.ToLocalTime();
+ string applicationName = (string)session["ApplicationName"];
+ int sessionItemsCount = (int)session["SessionItemsCount"];
+ bool locked = (bool)session["Locked"];
+ Console.WriteLine("SessionId:" + id + " | Created:" + created.ToString() + " | Expires:" + expires.ToString() + " | Locked?: " + locked.ToString() + " | Application:" + applicationName + " | Total Items:" + sessionItemsCount.ToString());
+ }
+ conn.Close();
+ }
+
+ private string Serialize(SessionStateItemCollection items)
+ {
+ MemoryStream ms = new MemoryStream();
+ BinaryWriter writer = new BinaryWriter(ms);
+ if (items != null)
+ items.Serialize(writer);
+ writer.Close();
+ return Convert.ToBase64String(ms.ToArray());
+ }
+
+
+ private SessionStateItemCollection Deserialize(string serializedItems, int timeout)
+ {
+ MemoryStream ms = new MemoryStream(Convert.FromBase64String(serializedItems));
+ SessionStateItemCollection sessionItems = new SessionStateItemCollection();
+
+ if (ms.Length > 0)
+ {
+ BinaryReader reader = new BinaryReader(ms);
+ sessionItems = SessionStateItemCollection.Deserialize(reader);
+ }
+
+ return sessionItems;
+ }
+ }
+}
79 SessionStoreTest/SessionStoreTest.csproj
@@ -0,0 +1,79 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <ProductVersion>9.0.30729</ProductVersion>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{BEF9F11E-FD05-4761-B772-A592CBCC5728}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>SessionStoreTest</RootNamespace>
+ <AssemblyName>SessionStoreTest</AssemblyName>
+ <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
+ <FileAlignment>512</FileAlignment>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ <DebugSymbols>true</DebugSymbols>
+ <DebugType>full</DebugType>
+ <Optimize>false</Optimize>
+ <OutputPath>bin\Debug\</OutputPath>
+ <DefineConstants>DEBUG;TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ <DebugType>pdbonly</DebugType>
+ <Optimize>true</Optimize>
+ <OutputPath>bin\Release\</OutputPath>
+ <DefineConstants>TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <ItemGroup>
+ <Reference Include="MongoDB.Driver, Version=1.0.3729.17015, Culture=neutral, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>..\..\mongo\mongodb-csharp\MongoDBDriver\bin\Debug\MongoDB.Driver.dll</HintPath>
+ </Reference>
+ <Reference Include="nunit.framework, Version=2.5.3.9345, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>..\..\..\..\..\..\..\API\NUnit\NUnit-2.5.3.9345\bin\net-2.0\nunit.framework.dll</HintPath>
+ </Reference>
+ <Reference Include="System" />
+ <Reference Include="System.configuration" />
+ <Reference Include="System.Core">
+ <RequiredTargetFramework>3.5</RequiredTargetFramework>
+ </Reference>
+ <Reference Include="System.Web" />
+ <Reference Include="System.Xml.Linq">
+ <RequiredTargetFramework>3.5</RequiredTargetFramework>
+ </Reference>
+ <Reference Include="System.Data.DataSetExtensions">
+ <RequiredTargetFramework>3.5</RequiredTargetFramework>
+ </Reference>
+ <Reference Include="System.Data" />
+ <Reference Include="System.Xml" />
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="SessionOpsTest.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="SessionStoreTest.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="App.config" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\MongoDBSessionStore\MongoSessionStore.csproj">
+ <Project>{354D379B-E16C-40DE-B26F-8CCF2EDE94D8}</Project>
+ <Name>MongoSessionStore</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
+ Other similar extension points exist, see Microsoft.Common.targets.
+ <Target Name="BeforeBuild">
+ </Target>
+ <Target Name="AfterBuild">
+ </Target>
+ -->
+</Project>
12 SessionStoreTest/obj/Debug/SessionStoreTest.csproj.FileListAbsolute.txt
@@ -0,0 +1,12 @@
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\SessionStoreTest\obj\Debug\ResolveAssemblyReference.cache
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\SessionStoreTest\bin\Debug\SessionStoreTest.dll.config
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\SessionStoreTest\bin\Debug\SessionStoreTest.dll
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\SessionStoreTest\bin\Debug\SessionStoreTest.pdb
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\SessionStoreTest\bin\Debug\MongoDB.Driver.dll
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\SessionStoreTest\bin\Debug\nunit.framework.dll
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\SessionStoreTest\bin\Debug\MongoDB.Driver.pdb
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\SessionStoreTest\obj\Debug\SessionStoreTest.dll
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\SessionStoreTest\obj\Debug\SessionStoreTest.pdb
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\SessionStoreTest\bin\Debug\MongoDBSessionStore.dll
+C:\Users\Seth\Documents\Visual Studio 2008\Projects\MytradeExperiment\SessionStoreTest\bin\Debug\MongoDBSessionStore.pdb
+C:\Users\Seth\Projects\MongoSessionStore\SessionStoreTest\obj\Debug\ResolveAssemblyReference.cache

0 comments on commit e6a21a6

Please sign in to comment.