Skip to content
Browse files

Added Fluent NHibernate to MVC

  • Loading branch information...
1 parent fecc195 commit 44891f3b603df03c779c172f1d8d8d7a9d29dfd7 gmobydick committed Aug 3, 2011
View
8 .gitignore
@@ -1,3 +1,4 @@
+
# compiled source #
###################
*.com
@@ -8,7 +9,8 @@
*.dll.config
*.cache
*.suo
-# Include dlls if they�re in the NuGet packages directory
+*.txt*
+# Include dlls if they’re in the NuGet packages directory
!/packages/*/lib/*.dll
# VS Upgrade stuff #
####################
@@ -28,7 +30,7 @@ TestResults/
*.ReSharper.*
# Packages #
############
-# its better to unpack these files and commit the raw source
+# its better to unpack these files and commit the raw source
# git has its own built in compression methods
*.7z
*.dmg
@@ -55,4 +57,4 @@ Thumbs.db
# The exception #
#################
!Libs/*.*
-!Libs/*/*.*
+!Libs/*/*.*
View
4 TaskDO/Entities/Project.cs
@@ -15,12 +15,12 @@ public Project()
public virtual IList<Task> Tasks { get; set; }
public virtual IList<Worker> Workers { get; set; }
- public void AddTask(Task task)
+ public virtual void AddTask(Task task)
{
Tasks.Add(task);
}
- public void AddWorker(Worker worker)
+ public virtual void AddWorker(Worker worker)
{
Workers.Add(worker);
}
View
2 TaskDO/Entities/Task.cs
@@ -14,7 +14,7 @@ public Task()
public virtual Project Project { get; set; }
public virtual IList<Worker> Workers { get; set; }
- public void AddWorker(Worker worker)
+ public virtual void AddWorker(Worker worker)
{
Workers.Add(worker);
}
View
2 TaskDO/Entities/TaskTime.cs
@@ -11,7 +11,7 @@ public class TaskTime : Entity
public virtual Task Task { get; set; }
public virtual Worker Worker { get; set; }
- public double WorkTime
+ public virtual double WorkTime
{
get
{
View
2 TaskDO/Entities/Worker.cs
@@ -20,7 +20,7 @@ public Worker()
public virtual IList<Project> Projects { get; set; }
- public void AddHoursTask(TaskTime taskTime)
+ public virtual void AddHoursTask(TaskTime taskTime)
{
TaskTimes.Add(taskTime);
}
View
6 TaskDO/Properties/AssemblyInfo.cs
@@ -8,9 +8,9 @@
[assembly: AssemblyTitle("TaskDO")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Microsoft")]
-[assembly: AssemblyProduct("TaskDO")]
-[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
+[assembly: AssemblyCompany("Cafebabe")]
+[assembly: AssemblyProduct("Tasker")]
+[assembly: AssemblyCopyright("Copyright © Cafebabe 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
View
20 TaskMVC/Areas/Admin/Controllers/ProjectTaskController.cs
@@ -0,0 +1,20 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Web;
+using System.Web.Mvc;
+
+namespace TaskMVC.Areas.Admin.Controllers
+{
+ public class ProjectTaskController : Controller
+ {
+ //
+ // GET: /Admin/ProjectTask/
+
+ public ActionResult Index()
+ {
+ return View();
+ }
+
+ }
+}
View
79 TaskMVC/Global.asax.cs
@@ -1,9 +1,16 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
+using FluentNHibernate.Cfg;
+using FluentNHibernate.Cfg.Db;
+using HibernatingRhinos.Profiler.Appender.NHibernate;
+using NHibernate;
+using NHibernate.Cfg;
+using NHibernate.Context;
+using NHibernate.Tool.hbm2ddl;
+using TaskDO.Entities;
+using log4net;
+using log4net.Config;
namespace TaskMVC
{
@@ -12,6 +19,9 @@ namespace TaskMVC
public class MvcApplication : System.Web.HttpApplication
{
+ private static readonly ILog Log = LogManager.GetLogger(typeof(MvcApplication));
+ public static ISessionFactory SessionFactory { get; private set; }
+
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
@@ -32,11 +42,74 @@ public static void RegisterRoutes(RouteCollection routes)
protected void Application_Start()
{
+ //Configure log4net
+ XmlConfigurator.Configure();
+
+ //Handle Mobile devices. Detect and redirect to Mobile Area
GlobalFilters.Filters.Add(new RedirectMobileDevicesToMobileAreaAttribute(), 1);
+
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
+
+ SessionFactory = Fluently.Configure()
+ .Database(MsSqlConfiguration.MsSql2008
+ .ConnectionString(c => c.FromConnectionStringWithKey("cafebabeDB"))
+ //.ConnectionString(c => c.FromConnectionStringWithKey("kurtDB"))
+ //.Cache(c => c.UseQueryCache().ProviderClass<HashtableCacheProvider>())
+ .ShowSql())
+ .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Task>())
+ .ExposeConfiguration(c => c.SetProperty("current_session_context_class", "web"))
+ //.ExposeConfiguration(preUp =>
+ //{
+ // preUp.EventListeners.PreUpdateEventListeners =
+ // new IPreUpdateEventListener[] { new EntityListener() };
+ //})
+ //.ExposeConfiguration(preIn =>
+ //{
+ // preIn.EventListeners.PreInsertEventListeners =
+ // new IPreInsertEventListener[] { new EntityListener() };
+ //})
+ //.ExposeConfiguration(postUp =>
+ //{
+ // postUp.EventListeners.PostUpdateEventListeners =
+ // new IPostUpdateEventListener[] { new EntityListener() };
+ //})
+ .ExposeConfiguration(BuildSchema)
+ .BuildSessionFactory();
+ NHibernateProfiler.Initialize();
+ Log.Debug("Application started!");
+ Log.Info("Application started!");
+ Log.Error("Application started!");
+ }
+
+ protected void Application_BeginRequest(object sender, EventArgs e)
+ {
+ ISession session = SessionFactory.OpenSession();
+ CurrentSessionContext.Bind(session);
+ }
+
+ protected void Application_EndRequest(object sender, EventArgs e)
+ {
+ ISession session = CurrentSessionContext.Unbind(SessionFactory);
+ session.Dispose();
+ }
+
+ private static void BuildSchema(Configuration config)
+ {
+ //Tries tu update the datamodel without destroying data
+ // 1st parameter - Show DDL (Data Definition Language) in consolet)
+ // 2nd parameter - Run DDL mot databasen(Make tables and relations according to mapping, but only update if table already exists).
+ new SchemaUpdate(config).Execute(false, true);
+
+ //#region Create from scratch
+ //// this NHibernate tool takes a configuration (with mapping info in)
+ //// and exports a database schema from it
+ //// 1st parameter - Show DDL (Data Definition Language) in consolet)
+ //// 2nd parameter - Run DDL mot databasen(Make tables and relations according to mapping).
+ //new SchemaExport(config).Create(true, true);
+ //#endregion
}
}
}
View
6 TaskMVC/Properties/AssemblyInfo.cs
@@ -8,9 +8,9 @@
[assembly: AssemblyTitle("TaskMVC")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Capgemini")]
-[assembly: AssemblyProduct("TaskMVC")]
-[assembly: AssemblyCopyright("Copyright © Capgemini 2011")]
+[assembly: AssemblyCompany("Cafebabe")]
+[assembly: AssemblyProduct("Tasker")]
+[assembly: AssemblyCopyright("Copyright © Cafebabe 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
View
24 TaskMVC/TaskMVC.csproj
@@ -14,6 +14,7 @@
<AssemblyName>TaskMVC</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<MvcBuildViews>false</MvcBuildViews>
+ <UseIISExpress>false</UseIISExpress>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -33,7 +34,22 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
+ <Reference Include="FluentNHibernate">
+ <HintPath>..\Libs\Fluent\FluentNHibernate.dll</HintPath>
+ </Reference>
+ <Reference Include="HibernatingRhinos.Profiler.Appender">
+ <HintPath>..\Libs\NHibernate\HibernatingRhinos.Profiler.Appender.dll</HintPath>
+ </Reference>
+ <Reference Include="log4net">
+ <HintPath>..\Libs\log4net\log4net.dll</HintPath>
+ </Reference>
<Reference Include="Microsoft.CSharp" />
+ <Reference Include="NHibernate">
+ <HintPath>..\Libs\Fluent\NHibernate.dll</HintPath>
+ </Reference>
+ <Reference Include="NHibernate.ByteCode.Castle">
+ <HintPath>..\Libs\Fluent\NHibernate.ByteCode.Castle.dll</HintPath>
+ </Reference>
<Reference Include="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="System.Web.WebPages" />
<Reference Include="System.Web.Helpers" />
@@ -58,6 +74,7 @@
</ItemGroup>
<ItemGroup>
<Compile Include="Areas\Admin\AdminAreaRegistration.cs" />
+ <Compile Include="Areas\Admin\Controllers\ProjectTaskController.cs" />
<Compile Include="Areas\Main\MainAreaRegistration.cs" />
<Compile Include="Areas\Mobile\Controllers\HomeController.cs" />
<Compile Include="Areas\Mobile\MobileAreaRegistration.cs" />
@@ -129,7 +146,6 @@
</ItemGroup>
<ItemGroup>
<Folder Include="App_Data\" />
- <Folder Include="Areas\Admin\Controllers\" />
<Folder Include="Areas\Admin\Models\" />
<Folder Include="Areas\Admin\Views\Shared\" />
<Folder Include="Areas\Main\Controllers\" />
@@ -152,6 +168,12 @@
<ItemGroup>
<Content Include="Areas\Mobile\Views\Shared\_Layout.cshtml" />
</ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\TaskDo\TaskDO.csproj">
+ <Project>{168F9C6F-E791-4712-B3D7-7367A7487516}</Project>
+ <Name>TaskDO</Name>
+ </ProjectReference>
+ </ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
View
129 TaskMVC/Web.config
@@ -5,15 +5,140 @@
-->
<configuration>
+
+ <configSections>
+ <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net" />
+ </configSections>
+ <log4net>
+ <root>
+ <level value="ALL" />
+ <appender-ref ref="DbAppender" />
+ <appender-ref ref="FileAppender" />
+ <appender-ref ref="EmailAppender" />
+ </root>
+ <appender name="DbAppender" type="log4net.Appender.AdoNetAppender">
+ <bufferSize value="1" />
+ <threshold value="INFO" />
+ <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+ <connectionString value="server=178.21.128.115; uid=kurt; pwd=kurt2010; database=dev" />
+ <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
+ <!--
+ CREATE TABLE [dbo].[Log] (
+ [Id] [int] IDENTITY (1, 1) NOT NULL,
+ [Date] [datetime] NOT NULL,
+ [Thread] [varchar] (255) NOT NULL,
+ [Level] [varchar] (50) NOT NULL,
+ [Logger] [varchar] (255) NOT NULL,
+ [Message] [varchar] (4000) NOT NULL,
+ [Exception] [varchar] (2000) NULL
+ )
+ -->
+ <parameter>
+ <parameterName value="@log_date" />
+ <dbType value="DateTime" />
+ <layout type="log4net.Layout.RawTimeStampLayout" />
+ </parameter>
+ <parameter>
+ <parameterName value="@thread" />
+ <dbType value="String" />
+ <size value="255" />
+ <layout type="log4net.Layout.PatternLayout">
+ <conversionPattern value="%thread" />
+ </layout>
+ </parameter>
+ <parameter>
+ <parameterName value="@log_level" />
+ <dbType value="String" />
+ <size value="50" />
+ <layout type="log4net.Layout.PatternLayout">
+ <conversionPattern value="%level" />
+ </layout>
+ </parameter>
+ <parameter>
+ <parameterName value="@logger" />
+ <dbType value="String" />
+ <size value="255" />
+ <layout type="log4net.Layout.PatternLayout">
+ <conversionPattern value="%logger" />
+ </layout>
+ </parameter>
+ <parameter>
+ <parameterName value="@message" />
+ <dbType value="String" />
+ <size value="4000" />
+ <layout type="log4net.Layout.PatternLayout">
+ <conversionPattern value="%message" />
+ </layout>
+ </parameter>
+ <parameter>
+ <parameterName value="@exception" />
+ <dbType value="String" />
+ <size value="2000" />
+ <layout type="log4net.Layout.ExceptionLayout" />
+ </parameter>
+ </appender>
+ <appender name="FileAppender" type="log4net.Appender.RollingFileAppender,log4net">
+ <param name="File" value="log.txt" />
+ <threshold value="ERROR" />
+ <param name="AppendToFile" value="false" />
+ <param name="RollingStyle" value="Date" />
+ <param name="DatePattern" value="yyyy.MM.dd" />
+ <param name="StaticLogFileName" value="true" />
+ <layout type="log4net.Layout.PatternLayout,log4net">
+ <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
+ </layout>
+ </appender>
+ <appender name="EmailAppender" type="log4net.Appender.SmtpAppender">
+ <!--<evaluator type="log4net.Core.LevelEvaluator">
+ <threshold value="ERROR"/>
+ </evaluator>-->
+ <!-- The filters are processed in order:
+ 1) match the Inserted New User message
+ 2) match any WARN or higher messages
+ 3) reject everything else -->
+ <!--<filter type="log4net.Filter.StringMatchFilter">
+ <stringToMatch value="Inserted a new user" />
+ <acceptOnMatch value="true" />
+ </filter>-->
+ <filter type="log4net.Filter.LevelRangeFilter">
+ <levelMin value="ERROR" />
+ <acceptOnMatch value="true" />
+ </filter>
+ <filter type="log4net.Filter.DenyAllFilter" />
+ <!-- The SmtpAppender authenticates against the mail server, the buffersize of 10
+ provides 10 lines of context when an error happens. -->
+ <subject value="GeoPlayGround: Test log event" />
+ <to value="kurt.moan@gmail.com, gmobydick@gmail.com" />
+ <from value="no-reply@geoplayground.com" />
+ <!--bm8tcmVwbHlAZ2VvcGxheWdyb3VuZC5jb20=-->
+ <!--<password value="replyno" />-->
+ <password value="cmVwbHlubw==" />
+ <smtpHost value="smtp.webhuset.no" />
+ <authentication value="Basic" />
+ <username value="no-reply@geoplayground.com" />
+ <password value="replyno" />
+ <port value="587" />
+ <bufferSize value="1" />
+ <lossy value="true" />
+ <layout type="log4net.Layout.PatternLayout">
+ <param name="ConversionPattern" value="%5p [%d] - %m%n" />
+ </layout>
+ </appender>
+ </log4net>
+
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
+ <add name="kurtDB" connectionString="Data Source=178.21.128.115;User ID=kurt;Password=kurt2010"
+ providerName="System.Data.SqlClient" />
+ <add name="cafebabeDB" connectionString="Data Source=mssql01.webhuset.no;User ID=cafebabe;Password=vFIsIZu0y"
+ providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
- <add key="ClientValidationEnabled" value="true"/>
- <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
+ <add key="ClientValidationEnabled" value="true"/>
+ <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<system.web>
View
78 TestTaskDO/TestTaskDO.csproj
@@ -0,0 +1,78 @@
+<?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>
+ </ProductVersion>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{2E8A6C4C-B79E-4B18-943F-DEDE0F8ED58A}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>TestTaskDO</RootNamespace>
+ <AssemblyName>TestTaskDO</AssemblyName>
+ <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
+ <FileAlignment>512</FileAlignment>
+ <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
+ </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="FluentNHibernate">
+ <HintPath>..\Libs\Fluent\FluentNHibernate.dll</HintPath>
+ </Reference>
+ <Reference Include="Microsoft.CSharp" />
+ <Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
+ <Reference Include="NHibernate">
+ <HintPath>..\Libs\Fluent\NHibernate.dll</HintPath>
+ </Reference>
+ <Reference Include="System" />
+ <Reference Include="System.ComponentModel.DataAnnotations" />
+ <Reference Include="System.Core">
+ <RequiredTargetFramework>3.5</RequiredTargetFramework>
+ </Reference>
+ <Reference Include="System.Data" />
+ <Reference Include="System.Data.DataSetExtensions" />
+ <Reference Include="System.Xml" />
+ <Reference Include="System.Xml.Linq" />
+ </ItemGroup>
+ <ItemGroup>
+ <CodeAnalysisDependentAssemblyPaths Condition=" '$(VS100COMNTOOLS)' != '' " Include="$(VS100COMNTOOLS)..\IDE\PrivateAssemblies">
+ <Visible>False</Visible>
+ </CodeAnalysisDependentAssemblyPaths>
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="Entities\TaskTimeTest.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ </ItemGroup>
+ <ItemGroup />
+ <ItemGroup>
+ <ProjectReference Include="..\TaskDo\TaskDO.csproj">
+ <Project>{168F9C6F-E791-4712-B3D7-7367A7487516}</Project>
+ <Name>TaskDO</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <Import Project="$(MSBuildBinPath)\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>

0 comments on commit 44891f3

Please sign in to comment.
Something went wrong with that request. Please try again.