Skip to content

Instantly share code, notes, and snippets.

@ayende
Created March 4, 2013 12:38
Show Gist options
  • Save ayende/5081996 to your computer and use it in GitHub Desktop.
Save ayende/5081996 to your computer and use it in GitHub Desktop.
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using Raven.Client;
using Raven.Client.Document;
namespace Webinars.Controllers
{
public abstract class RavenApiController : ApiController
{
public static Lazy<IDocumentStore> DocumentStore = new Lazy<IDocumentStore>(() =>
{
var docStore = new DocumentStore
{
Url = "http://localhost:8080",
DefaultDatabase = "Webinars"
};
docStore.Initialize();
return docStore;
});
private IDocumentSession session;
public IAsyncDocumentSession asyncSession;
public override async Task<HttpResponseMessage> ExecuteAsync(
HttpControllerContext controllerContext,
CancellationToken cancellationToken)
{
var result = await base.ExecuteAsync(controllerContext, cancellationToken);
if (session != null)
session.SaveChanges();
if (asyncSession != null)
await asyncSession.SaveChangesAsync();
return result;
}
public IDocumentSession Session
{
get
{
if (asyncSession != null)
throw new NotSupportedException("Can't use both sync & async sessions in the same action");
return session ?? (session = DocumentStore.Value.OpenSession());
}
set { session = value; }
}
public IAsyncDocumentSession AsyncSession
{
get
{
if (session != null)
throw new NotSupportedException("Can't use both sync & async sessions in the same action");
return asyncSession ?? (asyncSession = DocumentStore.Value.OpenAsyncSession());
}
set { asyncSession = value; }
}
}
}
using System;
using System.Collections.Generic;
namespace Webinars.Models
{
public class Webinar
{
public string Id { get; set; }
public DateTimeOffset ScheduledAt { get; set; }
public string Presenter { get; set; }
public List<string> Tags { get; set; }
public string Description { get; set; }
public Webinar()
{
Tags = new List<string>();
}
}
}
using System;
using System.Threading.Tasks;
using System.Web.Http;
using Webinars.Models;
namespace Webinars.Controllers
{
public class WebinarsController : RavenApiController
{
[HttpGet]
public async Task<string> Create(string presenter,[FromUri] string[] tags, string desc)
{
var webinar = new Webinar
{
Description = desc,
ScheduledAt = DateTime.Today.AddDays(7),
Presenter = presenter,
};
webinar.Tags.AddRange(tags);
await AsyncSession.StoreAsync(webinar);
return webinar.Id;
}
[HttpGet]
public Webinar Load(int id)
{
return Session.Load<Webinar>(id);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment