Permalink
Browse files

Added RavenDb base controller and ActionFilterAttribute

  • Loading branch information...
1 parent 6729084 commit 8a7474df7a4af6ed6df8926f8e55d557ee2d6dfd @AlexZeitler AlexZeitler committed with pedroreys Apr 4, 2012
View
@@ -26,6 +26,7 @@ EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebApiContrib.Formatting.ProtoBuf", "src\WebApiContrib.Formatting.ProtoBuf\WebApiContrib.Formatting.ProtoBuf.csproj", "{2537E1C1-0212-4595-9F73-C0DEAE31BD62}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebApiContrib.Testing", "src\WebApiContrib.Testing\WebApiContrib.Testing.csproj", "{DDEB5F68-7E22-4F54-9B04-63518083B83E}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebApiContrib.RavenDb", "src\WebApiContrib.RavenDb\WebApiContrib.RavenDb.csproj", "{3D3C4640-9365-471A-A160-59E7C394B228}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -73,6 +74,10 @@ Global
{DDEB5F68-7E22-4F54-9B04-63518083B83E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DDEB5F68-7E22-4F54-9B04-63518083B83E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DDEB5F68-7E22-4F54-9B04-63518083B83E}.Release|Any CPU.Build.0 = Release|Any CPU
+ {3D3C4640-9365-471A-A160-59E7C394B228}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {3D3C4640-9365-471A-A160-59E7C394B228}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {3D3C4640-9365-471A-A160-59E7C394B228}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {3D3C4640-9365-471A-A160-59E7C394B228}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -0,0 +1,39 @@
+using System;
+using System.Web.Http.Controllers;
+using System.Web.Http.Filters;
+using WebApiContrib.RavenDb.RavenDb;
+
+namespace WebApiContrib.RavenDb.ActionFilters {
+ /// <summary>
+ /// This filter will manage the session for all of the controllers that needs a Raven Document Session.
+ /// It does so by automatically injecting a session to the first public property of type IDocumentSession available
+ /// on the controller.
+ /// </summary>
+ public class RavenActionFilterAttribute : ActionFilterAttribute {
+ readonly string _connectionStringName;
+ readonly Uri _uri;
+
+ public RavenActionFilterAttribute(Uri uri) {
+ _uri = uri;
+ }
+
+ public RavenActionFilterAttribute(string connectionStringName) {
+ _connectionStringName = connectionStringName;
+ }
+
+ public override void OnActionExecuting(HttpActionContext filterContext) {
+ DocumentStoreHolder.Url = _uri ?? null;
+ DocumentStoreHolder.ConnectionStringName = !string.IsNullOrEmpty(_connectionStringName)
+ ? _connectionStringName
+ : null;
+ filterContext.Request.Properties["RavenDocumentStore"] =
+ DocumentStoreHolder.TryAddSession(filterContext.ControllerContext.Controller);
+ }
+
+
+ public override void OnActionExecuted(HttpActionExecutedContext filterContext) {
+ DocumentStoreHolder
+ .TryComplete(filterContext.ActionContext.ControllerContext.Controller, filterContext.Exception == null);
+ }
+ }
+}
@@ -0,0 +1,11 @@
+using System.Web.Http;
+using Raven.Client;
+
+namespace WebApiContrib.RavenDb.Controllers {
+ /// <summary>
+ /// This class contains a ASP.NET Web API base controller for use with RavenDb
+ /// </summary>
+ public class RavenDbController : ApiController {
+ public new IDocumentSession Session { get; set; }
+ }
+}
@@ -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("WebApiContrib.RavenDb")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("WebApiContrib.RavenDb")]
+[assembly: AssemblyCopyright("Copyright © 2012")]
+[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("6aa85823-952f-4c9c-be01-73c33b24e412")]
+
+// 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")]
@@ -0,0 +1,100 @@
+using System;
+using System.Collections.Concurrent;
+using System.Linq;
+using Raven.Client;
+using Raven.Client.Document;
+
+namespace WebApiContrib.RavenDb.RavenDb {
+ /// <summary>
+ /// This class manages the state of objects that desire a document session. We aren't relying on an IoC container here
+ /// because this is the sole case where we actually need to do injection.
+ /// </summary>
+ public class DocumentStoreHolder {
+ private static IDocumentStore _documentStore;
+
+ public static IDocumentStore DocumentStore {
+ get { return (_documentStore ?? (_documentStore = CreateDocumentStore())); }
+ }
+
+ private static IDocumentStore CreateDocumentStore() {
+ IDocumentStore store = null;
+ store = ConnectionStringName != null
+ ? new DocumentStore {
+ ConnectionStringName = ConnectionStringName
+ }
+ : null;
+
+ store = Url != null
+ ? new DocumentStore {
+ Url = Url.OriginalString
+ }
+ : store;
+
+ store.Initialize();
+
+ return store;
+ }
+
+ public static Uri Url { get; set; }
+ public static string ConnectionStringName { get; set; }
+
+ private static readonly ConcurrentDictionary<Type, Accessors> AccessorsCache = new ConcurrentDictionary<Type, Accessors>();
+
+ private static Accessors CreateAccessorsForType(Type type) {
+ var sessionProp =
+ type.GetProperties().FirstOrDefault(
+ x => x.PropertyType == typeof(IDocumentSession) && x.CanRead && x.CanWrite);
+ if (sessionProp == null)
+ return null;
+
+ return new Accessors {
+ Set = (instance, session) => sessionProp.SetValue(instance, session, null),
+ Get = instance => (IDocumentSession)sessionProp.GetValue(instance, null)
+ };
+ }
+
+ public static IDocumentSession TryAddSession(object instance) {
+ var accessors = AccessorsCache.GetOrAdd(instance.GetType(), CreateAccessorsForType);
+
+ if (accessors == null)
+ return null;
+
+ var documentSession = DocumentStore.OpenSession();
+ accessors.Set(instance, documentSession);
+
+ return documentSession;
+ }
+
+ public static void TryComplete(object instance, bool succcessfully) {
+ Accessors accesors;
+ if (AccessorsCache.TryGetValue(instance.GetType(), out accesors) == false || accesors == null)
+ return;
+
+ using (var documentSession = accesors.Get(instance)) {
+ if (documentSession == null)
+ return;
+
+ if (succcessfully)
+ documentSession.SaveChanges();
+ }
+ }
+
+ private class Accessors {
+ public Action<object, IDocumentSession> Set;
+ public Func<object, IDocumentSession> Get;
+ }
+
+ public static void Initailize() {
+
+ }
+
+ public static void TrySetSession(object instance, IDocumentSession documentSession) {
+ var accessors = AccessorsCache.GetOrAdd(instance.GetType(), CreateAccessorsForType);
+
+ if (accessors == null)
+ return;
+
+ accessors.Set(instance, documentSession);
+ }
+ }
+}
@@ -0,0 +1,82 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <ProductVersion>8.0.30703</ProductVersion>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{3D3C4640-9365-471A-A160-59E7C394B228}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>WebApiContrib.RavenDb</RootNamespace>
+ <AssemblyName>WebApiContrib.RavenDb</AssemblyName>
+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
+ <FileAlignment>512</FileAlignment>
+ <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
+ <RestorePackages>true</RestorePackages>
+ </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="Raven.Abstractions">
+ <HintPath>..\..\packages\RavenDB-Client.1.0.888\lib\net40\Raven.Abstractions.dll</HintPath>
+ </Reference>
+ <Reference Include="Raven.Client.Debug">
+ <HintPath>..\..\packages\RavenDB-Client.1.0.888\lib\net40\Raven.Client.Debug.dll</HintPath>
+ </Reference>
+ <Reference Include="Raven.Client.Lightweight">
+ <HintPath>..\..\packages\RavenDB-Client.1.0.888\lib\net40\Raven.Client.Lightweight.dll</HintPath>
+ </Reference>
+ <Reference Include="Raven.Client.Lightweight.FSharp">
+ <HintPath>..\..\packages\RavenDB-Client.1.0.888\lib\net40\Raven.Client.Lightweight.FSharp.dll</HintPath>
+ </Reference>
+ <Reference Include="Raven.Client.MvcIntegration">
+ <HintPath>..\..\packages\RavenDB-Client.1.0.888\lib\net40\Raven.Client.MvcIntegration.dll</HintPath>
+ </Reference>
+ <Reference Include="System" />
+ <Reference Include="System.ComponentModel.Composition" />
+ <Reference Include="System.Core" />
+ <Reference Include="System.Net.Http, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
+ <Reference Include="System.Web.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
+ <Reference Include="System.Xml.Linq" />
+ <Reference Include="System.Data.DataSetExtensions" />
+ <Reference Include="Microsoft.CSharp" />
+ <Reference Include="System.Data" />
+ <Reference Include="System.Xml" />
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="ActionFilters\RavenActionFilterAttribute.cs" />
+ <Compile Include="Controllers\RavenDbController.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="RavenDb\DocumentStoreHolder.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="packages.config">
+ <SubType>Designer</SubType>
+ </None>
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(SolutionDir)\.nuget\nuget.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>
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<packages>
+ <package id="Newtonsoft.Json" version="4.0.8" />
+ <package id="NLog" version="2.0.0.2000" />
+ <package id="RavenDB-Client" version="1.0.888" />
+</packages>

0 comments on commit 8a7474d

Please sign in to comment.