Instantly share code, notes, and snippets.

@GaProgMan /BookService.cs Secret
Last active Feb 1, 2017

Embed
What would you like to do?
Code listings for the blog post /2017/02/02/tutorial-webapi-services-and-dbcontexts
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Trace",
"System": "Information",
"Microsoft": "Information"
}
},
"Data": {
"SqliteConnection":{
"ConnectionString":"Data Source=dwDatabase.db"
}
}
}
namespace webApiTutorial.Models
{
public class Book
{
public int BookId { get; set; }
public int BookOrdinal { get; set; }
public string BookName { get; set; }
public string BookIsbn10 { get; set; }
public string BookIsbn13 { get; set; }
public string BookDescription { get; set; }
}
}
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using webApiTutorial.DatabaseContexts;
using webApiTutorial.Models;
namespace webApiTutorial.Services
{
public class BookService : IBookService
{
private DwContext _dwContext;
public BookService (DwContext dwContext)
{
_dwContext = dwContext;
}
public Book FindByOrdinal (int id)
{
return BaseQuery()
.FirstOrDefault(book => book.BookOrdinal == id);
}
public IEnumerable<Book> Search(string searchKey)
{
var blankSearchString = string.IsNullOrWhiteSpace(searchKey);
var results = BaseQuery();
if (!blankSearchString)
{
searchKey = searchKey.ToLower();
results = results
.Where(book => book.BookName.ToLower().Contains(searchKey)
|| book.BookDescription.ToLower().Contains(searchKey)
|| book.BookIsbn10.ToLower().Contains(searchKey)
|| book.BookIsbn13.ToLower().Contains(searchKey));
}
return results.OrderBy(book => book.BookOrdinal);
}
private IEnumerable<Book> BaseQuery()
{
return _dwContext.Books.AsNoTracking();
}
}
}
using Microsoft.EntityFrameworkCore;
using webApiTutorial.Models;
namespace webApiTutorial.DatabaseContexts
{
public class DwContext : DbContext
{
public DwContext(DbContextOptions<DwContext> options) : base(options) { }
public DwContext() { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
public override int SaveChanges()
{
return base.SaveChanges();
}
public DbSet<Book> Books { get; set; }
}
}
{
"projects": [
"src"
],
"sdk": {
"version": "1.0.0-preview2-final"
}
}
using System.Collections.Generic;
using webApiTutorial.Models;
namespace webApiTutorial.Services
{
public interface IBookService
{
// Search and Get
Book FindByOrdinal (int id);
IEnumerable<Book> Search(string searchKey);
}
}
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
namespace webApiTutorial
{
public class Program
{
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.Build();
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
{
"tooling": {
"defaultNamespace": "webApiTutorial"
},
"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.1.0",
"type": "platform"
},
"Microsoft.AspNetCore.Mvc": "1.1.0",
"Microsoft.AspNetCore.Routing": "1.1.0",
"Microsoft.AspNetCore.Server.IISIntegration": "1.1.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.1.0",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.1.0",
"Microsoft.Extensions.Configuration.FileExtensions": "1.1.0",
"Microsoft.Extensions.Configuration.Json": "1.1.0",
"Microsoft.Extensions.Configuration.CommandLine": "1.1.0",
"Microsoft.Extensions.Logging": "1.1.0",
"Microsoft.Extensions.Logging.Console": "1.1.0",
"Microsoft.Extensions.Logging.Debug": "1.1.0",
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.1.0",
"Microsoft.EntityFrameworkCore.Design": "1.1.0",
"Microsoft.EntityFrameworkCore": "1.1.0",
"Microsoft.EntityFrameworkCore.Sqlite": "1.1.0",
"Microsoft.EntityFrameworkCore.Sqlite.Design": {
"version": "1.1.0",
"type": "build"
},
"Microsoft.EntityFrameworkCore.Tools": {
"version": "1.0.0-preview2-final",
"type": "build"
}
},
"tools": {
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.1.0-preview4-final",
"Microsoft.EntityFrameworkCore.Tools.DotNet": "1.0.0-preview3-final"
},
"frameworks": {
"netcoreapp1.1": {
"imports": [
"dotnet5.6",
"dnxcore50",
"portable-net45+win8"
]
}
},
"buildOptions": {
"emitEntryPoint": true,
"preserveCompilationContext": true
},
"runtimeOptions": {
"configProperties": {
"System.GC.Server": true
}
},
"publishOptions": {
"include": [
"wwwroot",
"**/*.cshtml",
"appsettings.json",
"web.config"
]
},
"scripts": {
"postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
},
"tooling": {
"defaultNamespace": "src"
}
"name": "webApiTutorial"
}
mkdir webApiTutorial
cd webApiTutorial/
touch global.json
touch appsettings.json
yo aspnet
dotnet restore
dotnet watch run
dotnet restore
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"Data": {
"SqliteConnection":{
"ConnectionString":"Data Source=dwDatabase.db"
}
}
}
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using webApiTutorial.DatabaseContexts;
using webApiTutorial.Services;
namespace webApiTutorial
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
// Give ourselves access to the DwContext
services.AddDbContext<DwContext>(options =>
options.UseSqlite(Configuration["Data:SqliteConnection:ConnectionString"]));
// DI our Book service into our controllers
services.AddTransient<IBookService, BookService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMvc();
}
}
}
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using webApiTutorial.Services;
namespace webApiTutorial.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
private IBookService _bookService;
public ValuesController(IBookService bookService)
{
_bookService = bookService;
}
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
if (_bookService != null)
{
return new string[] { "Book service is ready" };
}
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment