Skip to content

Instantly share code, notes, and snippets.

@raghuramn
Created May 2, 2013 18:08
Show Gist options
  • Save raghuramn/5504100 to your computer and use it in GitHub Desktop.
Save raghuramn/5504100 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.OData;
using System.Web.Http.OData.Builder;
using Microsoft.Data.Edm;
using Microsoft.Data.OData;
namespace InstanceAnnotations
{
class Program
{
static void Main(string[] args)
{
HttpServer server = new HttpServer();
server.Configuration.Routes.MapODataRoute("default", "", GetModel());
HttpClient client = new HttpClient(server);
var response = client.GetAsync("http://localhost/Customers").Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
private static IEdmModel GetModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Customer>("Customers");
builder.ComplexType<CustomODataError>();
return builder.GetEdmModel();
}
}
public class Customer
{
public int ID { get; set; }
}
public class CustomODataError
{
public CustomODataError(string code, string message)
{
Code = code;
Message = message;
}
public string Code { get; set; }
public string Message { get; set; }
}
public class CustomersController : ODataController
{
public ODataError GetCustomers()
{
ODataError error = new ODataError();
error.AddCustomError("Code1", "Some Custom Error1");
error.AddCustomError("Code2", "Some Custom Error2");
return error;
}
}
public static class ODataErrorExtensions
{
private const string _typeName = "Collection(InstanceAnnotations.CustomODataError)";
private const string _customErrorsAnnotationName = "ns.errors";
public static void AddCustomError(this ODataError error, string code, string message)
{
ODataInstanceAnnotation annotation = error.InstanceAnnotations.Where(a => a.Name == _customErrorsAnnotationName).SingleOrDefault();
if (annotation == null)
{
annotation = new ODataInstanceAnnotation(_customErrorsAnnotationName, new ODataCollectionValue { Items = new List<ODataComplexValue>(), TypeName = _typeName });
error.InstanceAnnotations.Add(annotation);
}
List<ODataComplexValue> errorStrings = (annotation.Value as ODataCollectionValue).Items as List<ODataComplexValue>;
errorStrings.Add(ToComplexValue(new CustomODataError(code, message)));
}
private static ODataComplexValue ToComplexValue(CustomODataError error)
{
ODataComplexValue complexValue = new ODataComplexValue();
complexValue.Properties = new ODataProperty[]
{
new ODataProperty{ Name= "Code", Value = error.Code },
new ODataProperty{ Name= "Message", Value = error.Message },
};
return complexValue;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment