using Newtonsoft.Json; using Projects.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Web.Http; namespace Projects.Controllers.api { [AllowCrossSiteJson] public class ActivityController : ApiController { private ProjectsDBEntities db = new ProjectsDBEntities(); // GET: api/Activity public HttpResponseMessage GetActivity() { var results = (from pt in db.ProjectTasks join ts in db.TaskStatuses on pt.task_status_id equals ts.id where ts.status == "Done" group pt.User by pt.User.id into g join u in db.Users on g.Key equals u.id select new ActivityResult { user = u.login, count = g.Count() }) .ToList(); return new HttpResponseMessage() { Content = new JsonContent(results) }; } } public class JsonContent : HttpContent { private readonly MemoryStream _Stream = new MemoryStream(); public JsonContent(object value) { Headers.ContentType = new MediaTypeHeaderValue("application/json"); var jw = new JsonTextWriter(new StreamWriter(_Stream)); jw.Formatting = Formatting.Indented; var serializer = new JsonSerializer(); serializer.Serialize(jw, value); jw.Flush(); _Stream.Position = 0; } protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { return _Stream.CopyToAsync(stream); } protected override bool TryComputeLength(out long length) { length = _Stream.Length; return true; } } }