Skip to content

Commit

Permalink
Add 'server/' from commit 'bbf668cd104642c2b9724ee643dc1c820607756d'
Browse files Browse the repository at this point in the history
git-subtree-dir: server
git-subtree-mainline: 3a0dc09
git-subtree-split: bbf668c
  • Loading branch information
yasithdev committed May 8, 2020
2 parents 3a0dc09 + bbf668c commit 599e987
Show file tree
Hide file tree
Showing 12 changed files with 510 additions and 0 deletions.
12 changes: 12 additions & 0 deletions server/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Build
bin/
obj/

# IDE
.vscode

# MacOS
.DS_Store

# Generated Data
data.json
157 changes: 157 additions & 0 deletions server/Controllers/CarController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Cors;
using System.Collections.Generic;
using System.Linq;
using coding.Models;
using System;
using System.IO;
using Newtonsoft.Json;

namespace coding.Controllers
{
[Route("api/[controller]")]
[ApiController]
[EnableCors("MyPolicy")]
public class CarController : ControllerBase
{
private readonly CarContext _context;
private string _path = Path.Combine(Environment.CurrentDirectory, "data.json");
private void AddCarsToContext(){
_context.Cars.Add(new Car { Manufacturer = "Ford",Make="Mustang",Model="GT",Year=2015 });
_context.Cars.Add(new Car { Manufacturer = "Chevrolet",Make="Corvette",Model="Z06",Year=2017 });
_context.Cars.Add(new Car { Manufacturer = "Dodge",Make="Challenger",Model="Hellcat",Year=2016 });
_context.SaveChanges();
}
private void WriteToJSONfile(){

try{
// Create a file to write to.
using (StreamWriter file = System.IO.File.CreateText(_path))
{
JsonSerializer serializer = new JsonSerializer();
//saves cars preserving the order (ID) of cars
serializer.Serialize(file, _context.Cars.OrderBy(s => s.Id).ToList());
}
}catch(Exception e){
Console.WriteLine("Exception information: {0}", e);
}
}
private List<Car> ReadFromJSONfile(){
try{
List<Car> carsList;
using (StreamReader file = System.IO.File.OpenText(_path))
{
JsonSerializer serializer = new JsonSerializer();
carsList = (List<Car>)serializer.Deserialize(file, typeof(List<Car>));
}
foreach (Car c in carsList) {
_context.Cars.Add(new Car { Id =c.Id,Manufacturer = c.Manufacturer,Make=c.Make,Model=c.Model,Year=c.Year });
}
_context.SaveChanges();
}catch(Exception e){
Console.WriteLine("Exception information: {0}", e);
//In case ofan exception, 3 cars still wold be added to the _context
// AddCarsToContext();
}
return _context.Cars.ToList();
}

public CarController(CarContext context)
{
_context = context;

if (_context.Cars.Count() == 0)
{
if (!System.IO.File.Exists(_path))
{
AddCarsToContext();
WriteToJSONfile();
}
else{
Console.WriteLine("\n\ndata file exist\n\n");
ReadFromJSONfile();
}
}
}
//localhost:5000/api/car
//Get all cars
[HttpGet]
public ActionResult<List<Car>> GetAll()
{
WriteToJSONfile();
//returns the list of cars preserving the order (ID) of cars
return _context.Cars.OrderBy(s => s.Id).ToList();
}

//Get one car given the ID
[HttpGet("{id}", Name = "GetCar")]
public ActionResult<Car> GetById(long id)
{
var item = _context.Cars.Find(id);
if (item == null)
{
return NotFound();
}
return item;
}

//localhost:5000/api/car
//Create Car
[HttpPost]
public IActionResult Create(Car car)
{
if(car.Id == 0){
car.Id=1;
}
var item = _context.Cars.Find(car.Id);
while(item!=null){
car.Id = car.Id+1;
item = _context.Cars.Find(car.Id);
}
_context.Cars.Add(car);
_context.SaveChanges();
WriteToJSONfile();
return CreatedAtRoute("GetCar", new { id = car.Id }, car);
}

//localhost:5000/api/car/{id}
//Edit Method
[HttpPut("{id}")]
public IActionResult Update(long id, Car item)
{
var car = _context.Cars.Find(id);
if (car == null)
{
return NotFound();
}
//send in raw-json body
car.Manufacturer = item.Manufacturer;
car.Make = item.Make;
car.Model = item.Model;
car.Year = item.Year;

_context.Cars.Update(car);
_context.SaveChanges();
WriteToJSONfile();
return NoContent();
}
//localhost:5000/api/car/{id}
//Delete Method
[HttpDelete("{id}")]
public IActionResult Delete(long id)
{
var car = _context.Cars.Find(id);
if (car == null)
{
return NotFound();
}

_context.Cars.Remove(car);
_context.SaveChanges();
WriteToJSONfile();
return NoContent();
}
}


}
12 changes: 12 additions & 0 deletions server/Models/Car.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace coding.Models
{
public class Car
{
public long Id { get; set; }
public string Manufacturer { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }

}
}
14 changes: 14 additions & 0 deletions server/Models/CarContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using Microsoft.EntityFrameworkCore;

namespace coding.Models
{
public class CarContext : DbContext
{
public CarContext(DbContextOptions<CarContext> options)
: base(options)
{
}

public DbSet<Car> Cars { get; set; }
}
}
24 changes: 24 additions & 0 deletions server/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace coding
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
30 changes: 30 additions & 0 deletions server/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:26620",
"sslPort": 44386
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/car",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"coding": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "api/car",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
33 changes: 33 additions & 0 deletions server/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using coding.Models;

namespace coding
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<CarContext>(opt =>
opt.UseInMemoryDatabase("CarsList"));
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
}

public void Configure(IApplicationBuilder app)
{
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc();
app.UseCors("MyPolicy");
}
}
}
9 changes: 9 additions & 0 deletions server/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
8 changes: 8 additions & 0 deletions server/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
17 changes: 17 additions & 0 deletions server/coding.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.1.0" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
</ItemGroup>

</Project>
Loading

0 comments on commit 599e987

Please sign in to comment.