Skip to content

Instantly share code, notes, and snippets.

@benfoster
benfoster / gist:3160260
Created July 22, 2012 16:51
JSONP to requests to ASP.NET Web API
$(function () {
$.ajax({
url: "http://localhost:62351/api/projects/jsonp?siteId=10",
dataType: "jsonp",
contentType: "text/javascript",
success: function (data) {
if (!data)
return;
$.each(data, function (i, post) {
@benfoster
benfoster / gist:3160663
Created July 22, 2012 18:40
Web Api JSONP

WebApi Configuration

public class WebApiConfig
{
    public static void Configure(HttpConfiguration config)
    {
        // remove xml formatter
		config.Formatters.Remove(config.Formatters.XmlFormatter);

// use camelcase for json

@benfoster
benfoster / gist:3274578
Created August 6, 2012 13:51
Enforcing lower case routes in ASP.NET Web Api
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { url = new LowercaseRouteConstraint() }
);
@benfoster
benfoster / gist:3304337
Created August 9, 2012 13:49
Performing one time migrations with RavenDB
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting migration.");
using (var store = new DocumentStore { ConnectionStringName = "RavenDb" }.Initialize())
{
using (var session = store.OpenSession())
{
@benfoster
benfoster / gist:3478125
Created August 26, 2012 12:00
Paged results in web api
public class PagedResult<T>
{
public PagedResult(IEnumerable<T> source, int pageIndex, int pageSize) :
this(source.GetPage(pageIndex, pageSize), pageIndex, pageSize, source.Count()) { }
public PagedResult(IEnumerable<T> source, int pageIndex, int pageSize, int totalCount)
{
Ensure.Argument.NotNull(source, "source");
this.TotalCount = totalCount;
@benfoster
benfoster / gist:3487285
Created August 27, 2012 10:30
My API so far
public class SitesController : ApiControllerBase
{
// GET api/sites
public PagedResult<Site> Get([FromUri]GetSitesCommand command)
{
RavenQueryStatistics stats;
var sites = Session.Query<Domain.Site>()
.Statistics(out stats)
.NotDeleted()
.If(command.Hostname.IsNotNullOrEmpty(), q => q.WithHostname(command.Hostname))
@benfoster
benfoster / gist:3488495
Created August 27, 2012 13:42
API Controller for sub resources
public class ProjectMediaController : ApiControllerBase
{
/// <summary>
/// Adds a new media item to a project.
/// </summary>
/// <example>
/// POST /api/projects/1/media
/// </example>
public HttpResponseMessage Post(int projectId, AddProjectMediaCommand command)
{
@benfoster
benfoster / gist:3491067
Created August 27, 2012 18:21
RavenDB WhereAll extension method
public static IDocumentQuery<T> WhereAll<T>(this IDocumentQuery<T> query, string fieldName, object[] values)
{
if (values == null || values.Length == 0)
throw new ArgumentException("Cannot be a null or empty array.", "values");
query.OpenSubclause();
query.WhereEquals(fieldName, values[0]);
for (int i = 1; i < values.Length; i++)
@benfoster
benfoster / gist:3497518
Created August 28, 2012 11:58
RavenDB querying one range using another
if (criteria.HasSalaryCriteria)
{
var salaryFrom = criteria.SalaryFrom ?? 0;
var salaryTo = criteria.SalaryTo ?? int.MaxValue;
query.AndAlso()
.OpenSubclause()
// is Criteria.From between Salary.From and Salary.To?
@benfoster
benfoster / gist:3514548
Created August 29, 2012 15:40
Injecting links
public class CustomJsonFormatter : JsonMediaTypeFormatter
{
public override Task WriteToStreamAsync(Type type, object value, System.IO.Stream writeStream,
System.Net.Http.HttpContent content, System.Net.TransportContext transportContext)
{
var objectWithLinks = value as IResourceWithLinks;
if (objectWithLinks != null)
{
objectWithLinks.Links = new[] { new Link { Rel = "Self", Href = "???" } };
}