Skip to content

Commit

Permalink
backend .NET using Web API
Browse files Browse the repository at this point in the history
  • Loading branch information
draptik committed Jul 18, 2014
1 parent 93d2ce8 commit 47cd287
Show file tree
Hide file tree
Showing 95 changed files with 139,122 additions and 0 deletions.
22 changes: 22 additions & 0 deletions backend/dotnet-backend/WebService/WebService.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.30501.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebService", "WebService\WebService.csproj", "{2E5EF8F0-373D-4D80-B47D-A5E59A63B08A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2E5EF8F0-373D-4D80-B47D-A5E59A63B08A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2E5EF8F0-373D-4D80-B47D-A5E59A63B08A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2E5EF8F0-373D-4D80-B47D-A5E59A63B08A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2E5EF8F0-373D-4D80-B47D-A5E59A63B08A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using System.Net.Http.Headers;
using System.Web.Http;
using Microsoft.Practices.Unity;
using WebService.IoC;
using WebService.Service;

namespace WebService
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// IoC container
//
// http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver
var container = new UnityContainer();
// Note: for this demo we want the user service to be a singleton ('ContainerControlledLifetimeManager' in Unity syntax)
container.RegisterType<IUserService, UserService>(new ContainerControlledLifetimeManager());
config.DependencyResolver = new UnityResolver(container);

// Web API configuration and services

config.EnableCors();

// Return JSON instead of XML http://stackoverflow.com/a/13277616/1062607
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

// Web API routes
config.MapHttpAttributeRoutes();

const string baseUrl = "ngdemo/web";

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: baseUrl + "/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System.Web.Http;
using System.Web.Http.Cors;
using WebService.Models;

namespace WebService.Controllers
{
[EnableCors(origins: "http://localhost:9000", headers: "*", methods: "*")]
public class DummyController : ApiController
{
public Dummy Get()
{
return new Dummy {Id = 0, FirstName = "JonFromREST", LastName = "Doe"};
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebService.Controllers
{
[EnableCors(origins: "http://localhost:9000", headers: "*", methods: "*")]
public class TestController : ApiController
{
public HttpResponseMessage Get()
{
return new HttpResponseMessage
{
Content = new StringContent("GET: Test message")
};
}

public HttpResponseMessage Post()
{
return new HttpResponseMessage
{
Content = new StringContent("POST: Test message")
};
}

public HttpResponseMessage Put()
{
return new HttpResponseMessage
{
Content = new StringContent("PUT: Test message")
};
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Cors;
using WebService.Models;
using WebService.Service;

namespace WebService.Controllers
{
[EnableCors(origins: "http://localhost:9000", headers: "*", methods: "*")]
public class UsersController : ApiController
{
private readonly IUserService userService;

public UsersController(IUserService userService)
{
this.userService = userService;
}

public ICollection<User> Get()
{
return this.userService.GetAllUsers();
}

public User Get(int id)
{
return this.userService.GetById(id);
}

public User Put(User user)
{
return this.userService.UpdateUser(user);
}

public User Post(User user)
{
return this.userService.CreateNewUser(user);
}

public void Delete(int id)
{
this.userService.RemoveUserById(id);
}
}
}
1 change: 1 addition & 0 deletions backend/dotnet-backend/WebService/WebService/Global.asax
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<%@ Application Codebehind="Global.asax.cs" Inherits="WebService.WebApiApplication" Language="C#" %>
21 changes: 21 additions & 0 deletions backend/dotnet-backend/WebService/WebService/Global.asax.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System.Web;
using System.Web.Http;
using Newtonsoft.Json.Serialization;

namespace WebService
{
public class WebApiApplication : HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);

// lower case property names in serialized JSON: http://stackoverflow.com/a/22130487/1062607
GlobalConfiguration.Configuration
.Formatters
.JsonFormatter
.SerializerSettings
.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
}
}
54 changes: 54 additions & 0 deletions backend/dotnet-backend/WebService/WebService/IoC/UnityResolver.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Web.Http.Dependencies;
using Microsoft.Practices.Unity;

namespace WebService.IoC
{
/// <summary>
/// http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver
/// </summary>
public class UnityResolver : IDependencyResolver
{
private readonly IUnityContainer container;

public UnityResolver(IUnityContainer container)
{
if (container == null) {
throw new ArgumentNullException("container");
}
this.container = container;
}

public void Dispose()
{
this.container.Dispose();
}

public object GetService(Type serviceType)
{
try {
return this.container.Resolve(serviceType);
}
catch (ResolutionFailedException) {
return null;
}
}

public IEnumerable<object> GetServices(Type serviceType)
{
try {
return this.container.ResolveAll(serviceType);
}
catch (ResolutionFailedException) {
return new List<object>();
}
}

public IDependencyScope BeginScope()
{
var child = this.container.CreateChildContainer();
return new UnityResolver(child);
}
}
}
9 changes: 9 additions & 0 deletions backend/dotnet-backend/WebService/WebService/Models/Dummy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace WebService.Models
{
public class Dummy
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
9 changes: 9 additions & 0 deletions backend/dotnet-backend/WebService/WebService/Models/User.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace WebService.Models
{
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WebService")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WebService")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a59d3efe-df66-4732-a6f8-6891e2886763")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System.Collections.Generic;
using WebService.Models;

namespace WebService.Service
{
public interface IUserService
{
ICollection<User> GetAllUsers();
User GetById(int userId);
User UpdateUser(User user);
User CreateNewUser(User user);
void RemoveUserById(int userId);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using WebService.Models;

namespace WebService.Service
{
public class UserService : IUserService
{
public UserService()
{
this.Users = new Collection<User>();
this.CreateUsers();
}

private ICollection<User> Users { get; set; }

public ICollection<User> GetAllUsers()
{
return this.Users;
}

public User GetById(int userId)
{
return this.Users.SingleOrDefault(x => x.Id.Equals(userId));
}

public User UpdateUser(User user)
{
var u = this.Users.SingleOrDefault(x => x.Id.Equals(user.Id));
if (u != null) {
u.FirstName = user.FirstName;
u.LastName = user.LastName;
}
return u;
}

public User CreateNewUser(User user)
{
var newUser = new User
{
Id = this.Users.Max(x => x.Id) + 1,
FirstName = user.FirstName,
LastName = user.LastName
};

this.Users.Add(newUser);

return newUser;
}

public void RemoveUserById(int userId)
{
this.Users.Remove(this.Users.SingleOrDefault(x => x.Id.Equals(userId)));
}

private void CreateUsers()
{
const int numberOfUsers = 10;
for (int id = 1; id <= numberOfUsers; id++) {
this.Users.Add(new User {Id = id, FirstName = "Foo" + id, LastName = "Bar" + id});
}
}
}
}
Loading

0 comments on commit 47cd287

Please sign in to comment.