Skip to content

Commit

Permalink
adding database message logging
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexCuse committed May 14, 2012
1 parent 7643f5f commit 80f90d7
Show file tree
Hide file tree
Showing 25 changed files with 4,483 additions and 43 deletions.
15 changes: 15 additions & 0 deletions PlayR/App_Readme/Elmah.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
A new HTTP handler has been configured in your application for consulting the
error log and its feeds. It is reachable at elmah.axd under your application
root. If, for example, your application is deployed at http://www.example.com,
the URL for ELMAH would be http://www.example.com/elmah.axd. You can, of
course, change this path in your application's configuration file.

ELMAH is also set up to be secure such that it can only be accessed locally.
You can enable remote access but then it is paramount that you secure access
to authorized users or/and roles only. This can be done using standard
authorization rules and configuration already built into ASP.NET. For more
information, see http://code.google.com/p/elmah/wiki/SecuringErrorLogPages on
the project site.

Please review the commented out authorization section under
<location path="elmah.axd"> and make the appropriate changes.
23 changes: 23 additions & 0 deletions PlayR/Areas/Admin/AdminAreaRegistration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System.Web.Mvc;

namespace PlayR.Areas.Admin
{
public class AdminAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Admin";
}
}

public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional } );
}
}
}
108 changes: 108 additions & 0 deletions PlayR/Areas/Admin/Controllers/ElmahController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
using System;
using System.Web;
using System.Web.Mvc;
using Elmah;

namespace PlayR.Areas.Admin.Controllers
{
//[Authorize(Roles = "Admin")]
public class ElmahController : Controller
{
public ActionResult Index()
{
return new ElmahResult();
}

public ActionResult Stylesheet()
{
return new ElmahResult("stylesheet");
}

public ActionResult Rss()
{
return new ElmahResult("rss");
}

public ActionResult DigestRss()
{
return new ElmahResult("digestrss");
}

public ActionResult About()
{
return new ElmahResult("about");
}

public ActionResult Detail()
{
return new ElmahResult("detail");
}

public ActionResult Download()
{
return new ElmahResult("download");
}

public ActionResult Json()
{
return new ElmahResult("json");
}

public ActionResult Xml()
{
return new ElmahResult("xml");
}
}

internal class ElmahResult : ActionResult
{
private readonly string _resouceType;

public ElmahResult()
: this(null)
{
}

public ElmahResult(string resouceType)
{
_resouceType = resouceType;
}

public override void ExecuteResult(ControllerContext context)
{
var factory = new ErrorLogPageFactory();

if (!string.IsNullOrEmpty(_resouceType))
{
string pathInfo = "/" + _resouceType;
context.HttpContext.RewritePath(FilePath(context), pathInfo,
context.HttpContext.Request.QueryString.ToString());
}

var currentContext = GetCurrentContextAsHttpContext(context);

var httpHandler = factory.GetHandler(currentContext, null, null, null);
var httpAsyncHandler = httpHandler as IHttpAsyncHandler;

if (httpAsyncHandler != null)
{
httpAsyncHandler.BeginProcessRequest(currentContext, r => { }, null);
return;
}

httpHandler.ProcessRequest(currentContext);
}

private static HttpContext GetCurrentContextAsHttpContext(ControllerContext context)
{
return context.HttpContext.ApplicationInstance.Context;
}

private string FilePath(ControllerContext context)
{
return _resouceType != "stylesheet"
? context.HttpContext.Request.Path.Replace(String.Format("/{0}", _resouceType), string.Empty)
: context.HttpContext.Request.Path;
}
}
}
52 changes: 52 additions & 0 deletions PlayR/Core/DatabaseMessageLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using System;
using System.Data.SqlClient;

namespace PlayR.Core
{
public class DatabaseMessageLogger : IMessageLogger, IDisposable
{
SqlConnection connection;

public DatabaseMessageLogger()
{
connection = GetConnection();
}

public void LogMessage(string message, string user)
{
using(var command = new SqlCommand("insert into Messages values (@user, @message)", connection))
{
command.Parameters.AddWithValue("user", user);
command.Parameters.AddWithValue("message", message);

connection.Open();
command.ExecuteNonQuery();
}
}

SqlConnection GetConnection()
{
return new SqlConnection(GetConnectionString());
}

string GetConnectionString()
{
System.Configuration.Configuration rootWebConfig =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/");
System.Configuration.ConnectionStringSettings connString;
if(rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
{
connString =
rootWebConfig.ConnectionStrings.ConnectionStrings["playr"];
if(connString != null)
return connString.ConnectionString;
}
return null;
}

public void Dispose()
{
connection.Dispose();
}
}
}
7 changes: 7 additions & 0 deletions PlayR/Core/IMessageLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace PlayR.Core
{
public interface IMessageLogger
{
void LogMessage(string message, string user);
}
}
29 changes: 24 additions & 5 deletions PlayR/Global.asax.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using PlayR.Core;
using PlayR.Hubs;
using PlayR.Infrastructure;
using SignalR;
using SquishIt.Framework;
using SignalR.Hosting.AspNet;
using SignalR.Hubs;
using SignalR.Infrastructure;
using StructureMap;
using IDependencyResolver = SignalR.IDependencyResolver;

namespace PlayR
{
Expand All @@ -20,7 +26,6 @@ public static void RegisterGlobalFilters(GlobalFilterCollection filters)
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
RouteTable.Routes.MapHubs();
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
Expand All @@ -29,14 +34,28 @@ public static void RegisterRoutes(RouteCollection routes)

}

DatabaseMessageLogger logger = new DatabaseMessageLogger();

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
//ObjectFactory.Initialize(c => {
// c.For<IMessageLogger>().Singleton().Use(() => logger);
// c.For<Chat>().Use<Chat>();
// c.For<IDependencyResolver>().Add<StructureMapResolver>();
//});


//GlobalHost.DependencyResolver = ObjectFactory.GetInstance<IDependencyResolver>();
RouteTable.Routes.MapHubs();

AreaRegistration.RegisterAllAreas();

RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}

protected void Application_End()
{
logger.Dispose();
}
}
}
17 changes: 16 additions & 1 deletion PlayR/Hubs/Chat.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,28 @@
using SignalR.Hubs;
using PlayR.Core;
using SignalR.Hubs;

namespace PlayR.Hubs
{
public class Chat : Hub
{
readonly IMessageLogger _messageLogger;

public Chat()
: this(new DatabaseMessageLogger())
{
}

public Chat(IMessageLogger messageLogger)
{
_messageLogger = messageLogger;
}

public void Send(string message, string user)
{
// Call the addMessage method on all clients
Clients.addMessage(message, user);
_messageLogger.LogMessage(message, user);
}

}
}
42 changes: 42 additions & 0 deletions PlayR/Infrastructure/StructureMapResolver.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using SignalR;
using StructureMap;

namespace PlayR.Infrastructure
{
public class StructureMapResolver : DefaultDependencyResolver
{
private IContainer _container;

public StructureMapResolver(IContainer container)
{
_container = container;
}

public override object GetService(Type serviceType)
{
object service = null;
if(!serviceType.IsAbstract && !serviceType.IsInterface && serviceType.IsClass)
{
// Concrete type resolution
service = _container.GetInstance(serviceType);
}
else
{
// Other type resolution with base fallback
service = _container.TryGetInstance(serviceType) ?? base.GetService(serviceType);
}
return service;
}

public override IEnumerable<object> GetServices(Type serviceType)
{
var objects = _container.GetAllInstances(serviceType).Cast<object>();
objects.Concat(base.GetServices(serviceType));
return objects;
}
}

}
12 changes: 12 additions & 0 deletions PlayR/PlayR.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@
<Reference Include="EcmaScript.NET.modified">
<HintPath>..\packages\YUICompressor.NET.1.7.1.0\lib\net35\EcmaScript.NET.modified.dll</HintPath>
</Reference>
<Reference Include="Elmah">
<HintPath>..\packages\elmah.corelibrary.1.2.2\lib\Elmah.dll</HintPath>
</Reference>
<Reference Include="Jurassic">
<HintPath>..\packages\Jurassic.2.1.1\lib\Jurassic.dll</HintPath>
</Reference>
Expand All @@ -66,6 +69,9 @@
<Reference Include="SquishIt.Framework">
<HintPath>..\packages\SquishIt.0.8.6\lib\SquishIt.Framework.dll</HintPath>
</Reference>
<Reference Include="StructureMap">
<HintPath>..\packages\structuremap.2.6.3\lib\StructureMap.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" />
Expand All @@ -92,17 +98,23 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Areas\Admin\AdminAreaRegistration.cs" />
<Compile Include="Areas\Admin\Controllers\ElmahController.cs" />
<Compile Include="Controllers\AccountController.cs" />
<Compile Include="Controllers\ChatController.cs" />
<Compile Include="Controllers\HomeController.cs" />
<Compile Include="Core\IMessageLogger.cs" />
<Compile Include="Global.asax.cs">
<DependentUpon>Global.asax</DependentUpon>
</Compile>
<Compile Include="Hubs\Chat.cs" />
<Compile Include="Core\DatabaseMessageLogger.cs" />
<Compile Include="Infrastructure\StructureMapResolver.cs" />
<Compile Include="Models\AccountModels.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="App_Readme\Elmah.txt" />
<Content Include="Global.asax" />
<Content Include="Scripts\jquery-1.6.4-vsdoc.js" />
<Content Include="Scripts\jquery-1.6.4.js" />
Expand Down
4 changes: 2 additions & 2 deletions PlayR/Views/Chat/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
@Html.Raw(SquishIt.Framework.Bundle.JavaScript()
.Add("Scripts/jquery.signalR-0.5.0.min.js")
//force packaging hubs with signalr
.AddRemote(null, HttpContext.Current.Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped) + "/signalr/hubs", true)
.ForceRelease()
.AddRemote("/signalr/hubs", HttpContext.Current.Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped) + "/signalr/hubs", true)
//.ForceRelease()
.Render("~/Scripts/combined/signalrAndHubs_#.js"))
<script type="text/javascript">
$(document).ready(function () {
Expand Down
Loading

0 comments on commit 80f90d7

Please sign in to comment.