From d3365ca0b34d48bed1fb485cf5ae4d1d596e02cf Mon Sep 17 00:00:00 2001 From: David Lin Date: Thu, 14 Apr 2022 15:34:25 +1200 Subject: [PATCH] Update RESTful-API section (#14) * Update RESTful API README * Add Message-API source code * Fix a few typos * Fix typo * Tidied up project for PR * Switched for loop to LINQ query * Fixed bad link Co-authored-by: Rodger Gu --- .gitignore | 649 ++++++++++++++++++ 2. Python workshop/README.md | 2 +- .../.idea.MessageAPI.dir/.idea/.gitignore | 13 + .../.idea/.idea.MessageAPI.dir/.idea/.name | 1 + .../.idea.MessageAPI.dir/.idea/encodings.xml | 4 + .../.idea/indexLayout.xml | 8 + .../.idea/.idea.MessageAPI.dir/.idea/vcs.xml | 6 + .../Controllers/MessageItemController.cs | 120 ++++ .../Message-API/MessageAPI.csproj | 20 + .../Message-API/Models/DTO/MessageItemDTO.cs | 7 + .../Models/DTO/MessageUpdateDTO.cs | 6 + .../Message-API/Models/MessageContext.cs | 13 + .../Message-API/Models/MessageItem.cs | 8 + .../Message-API/Program.cs | 34 + .../Properties/launchSettings.json | 31 + 3. RESTful-API workshop/Message-API/README.md | 4 + .../Message-API/appsettings.Development.json | 8 + .../Message-API/appsettings.json | 9 + 3. RESTful-API workshop/README.md | 36 +- 4. Relational DB workshop/README.md | 4 +- 5. C# workshop/README.md | 2 +- README.md | 6 +- 22 files changed, 968 insertions(+), 23 deletions(-) create mode 100644 .gitignore create mode 100644 3. RESTful-API workshop/Message-API/.idea/.idea.MessageAPI.dir/.idea/.gitignore create mode 100644 3. RESTful-API workshop/Message-API/.idea/.idea.MessageAPI.dir/.idea/.name create mode 100644 3. RESTful-API workshop/Message-API/.idea/.idea.MessageAPI.dir/.idea/encodings.xml create mode 100644 3. RESTful-API workshop/Message-API/.idea/.idea.MessageAPI.dir/.idea/indexLayout.xml create mode 100644 3. RESTful-API workshop/Message-API/.idea/.idea.MessageAPI.dir/.idea/vcs.xml create mode 100644 3. RESTful-API workshop/Message-API/Controllers/MessageItemController.cs create mode 100644 3. RESTful-API workshop/Message-API/MessageAPI.csproj create mode 100644 3. RESTful-API workshop/Message-API/Models/DTO/MessageItemDTO.cs create mode 100644 3. RESTful-API workshop/Message-API/Models/DTO/MessageUpdateDTO.cs create mode 100644 3. RESTful-API workshop/Message-API/Models/MessageContext.cs create mode 100644 3. RESTful-API workshop/Message-API/Models/MessageItem.cs create mode 100644 3. RESTful-API workshop/Message-API/Program.cs create mode 100644 3. RESTful-API workshop/Message-API/Properties/launchSettings.json create mode 100644 3. RESTful-API workshop/Message-API/README.md create mode 100644 3. RESTful-API workshop/Message-API/appsettings.Development.json create mode 100644 3. RESTful-API workshop/Message-API/appsettings.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..65f052f --- /dev/null +++ b/.gitignore @@ -0,0 +1,649 @@ + +# Created by https://www.toptal.com/developers/gitignore/api/csharp,rider,visualstudiocode,python +# Edit at https://www.toptal.com/developers/gitignore?templates=csharp,rider,visualstudiocode,python + +### Csharp ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml + +### Python ### +# Byte-compiled / optimized / DLL files +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +### Rider ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### VisualStudioCode ### +!.vscode/*.code-snippets + +# Local History for Visual Studio Code + +# Built Visual Studio Code Extensions +*.vsix + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history +.ionide + +# Support for Project snippet scope + +# End of https://www.toptal.com/developers/gitignore/api/csharp,rider,visualstudiocode,python \ No newline at end of file diff --git a/2. Python workshop/README.md b/2. Python workshop/README.md index 7c6636d..ca1c6bc 100644 --- a/2. Python workshop/README.md +++ b/2. Python workshop/README.md @@ -31,7 +31,7 @@ Fortunately, your years of training at the Microsoft Space Academy had a course ## Exercise 1 -Your first task, like almost anything involving unfamilar data, is to see what it actually looks like and get it into a more usable form for further analysis. +Your first task, like almost anything involving unfamiliar data, is to see what it actually looks like and get it into a more usable form for further analysis. **Investigate the transmission file provided by opening the file and inserting each line of the file into a list for later use, then printing it.** > Hint: Here's one way to [open CSV files](https://docs.python.org/3/library/csv.html#:~:text=A%20short%20usage%20example) diff --git a/3. RESTful-API workshop/Message-API/.idea/.idea.MessageAPI.dir/.idea/.gitignore b/3. RESTful-API workshop/Message-API/.idea/.idea.MessageAPI.dir/.idea/.gitignore new file mode 100644 index 0000000..7ec1bf1 --- /dev/null +++ b/3. RESTful-API workshop/Message-API/.idea/.idea.MessageAPI.dir/.idea/.gitignore @@ -0,0 +1,13 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Rider ignored files +/projectSettingsUpdater.xml +/.idea.MessageAPI.iml +/modules.xml +/contentModel.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/3. RESTful-API workshop/Message-API/.idea/.idea.MessageAPI.dir/.idea/.name b/3. RESTful-API workshop/Message-API/.idea/.idea.MessageAPI.dir/.idea/.name new file mode 100644 index 0000000..e1a685e --- /dev/null +++ b/3. RESTful-API workshop/Message-API/.idea/.idea.MessageAPI.dir/.idea/.name @@ -0,0 +1 @@ +MessageAPI \ No newline at end of file diff --git a/3. RESTful-API workshop/Message-API/.idea/.idea.MessageAPI.dir/.idea/encodings.xml b/3. RESTful-API workshop/Message-API/.idea/.idea.MessageAPI.dir/.idea/encodings.xml new file mode 100644 index 0000000..df87cf9 --- /dev/null +++ b/3. RESTful-API workshop/Message-API/.idea/.idea.MessageAPI.dir/.idea/encodings.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/3. RESTful-API workshop/Message-API/.idea/.idea.MessageAPI.dir/.idea/indexLayout.xml b/3. RESTful-API workshop/Message-API/.idea/.idea.MessageAPI.dir/.idea/indexLayout.xml new file mode 100644 index 0000000..7b08163 --- /dev/null +++ b/3. RESTful-API workshop/Message-API/.idea/.idea.MessageAPI.dir/.idea/indexLayout.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/3. RESTful-API workshop/Message-API/.idea/.idea.MessageAPI.dir/.idea/vcs.xml b/3. RESTful-API workshop/Message-API/.idea/.idea.MessageAPI.dir/.idea/vcs.xml new file mode 100644 index 0000000..b2bdec2 --- /dev/null +++ b/3. RESTful-API workshop/Message-API/.idea/.idea.MessageAPI.dir/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/3. RESTful-API workshop/Message-API/Controllers/MessageItemController.cs b/3. RESTful-API workshop/Message-API/Controllers/MessageItemController.cs new file mode 100644 index 0000000..93beca4 --- /dev/null +++ b/3. RESTful-API workshop/Message-API/Controllers/MessageItemController.cs @@ -0,0 +1,120 @@ +#nullable disable +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using MessageAPI.Models; +using MessageAPI.Models.DTO; + +namespace MessageAPI.Controllers; + +[Route("api/message")] +[ApiController] +public class MessageItemController : ControllerBase +{ + private readonly MessageContext _context; + private readonly ILogger _logger; + + public MessageItemController(MessageContext context, ILogger logger) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + /// + /// Gets all messages + /// + /// A response with the list of messages + [HttpGet] + public async Task>> GetMessageItems() + { + var messageItems = await _context.MessageItems.ToListAsync(); + return messageItems.Select(messageItem => new MessageItemDTO + { Id = messageItem.Id, MainMessage = messageItem.MainMessage }).ToArray(); + } + + /// + /// Gets a single message + /// + /// The ID of the message to return + /// The message with that ID, or a 404 response if the message does not exist + [HttpGet("{id}")] + public async Task> GetMessageItem(int id) + { + var messageItem = await _context.MessageItems.FindAsync(id); + + if (messageItem == null) + { + return NotFound(); + } + + // Strip out the password + var messageItemDto = new MessageItemDTO { Id = messageItem.Id, MainMessage = messageItem.MainMessage }; + + return messageItemDto; + } + + /// + /// Updates the message if it exists + /// + /// The message to update + /// The request body + /// The password associated with the message + /// A 404 response if the message doesn't exist, or a 204 if it has been updated + [HttpPatch("{id}")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public async Task PatchMessageItem(int id, MessageUpdateDTO messageUpdateDto, + [FromHeader(Name = "password")] string password) + { + _logger.LogInformation("Password: {Password}", password); + + // If the password doesn't match the old message password, return bad request. + var oldMessageItem = await _context.MessageItems.FindAsync(id); + if (oldMessageItem is null) return BadRequest(); + + if (password != oldMessageItem.Password) + { + return Unauthorized(); + } + + oldMessageItem.MainMessage = messageUpdateDto.MainMessage; + await _context.SaveChangesAsync(); + + return NoContent(); + } + + /// + /// Creates a new message + /// + /// The new message item to create + /// a success code if the message has been created + [HttpPost] + [ProducesResponseType(StatusCodes.Status201Created)] + public async Task> PostMessageItem(MessageItem messageItem) + { + _context.MessageItems.Add(messageItem); + await _context.SaveChangesAsync(); + + return CreatedAtAction(nameof(GetMessageItem), new { id = messageItem.Id }, messageItem); + } + + /// + /// Deletes a message if it exists + /// + /// The ID of the message to delete + /// A 200 OK response + [HttpDelete("{id}")] + public async Task DeleteMessageItem(int id) + { + var messageItem = await _context.MessageItems.FindAsync(id); + if (messageItem is null) + { + // if we return not found, people who shouldn't know a message exists can find + // a message's existence from the response type + return Ok(); + } + + _context.MessageItems.Remove(messageItem); + await _context.SaveChangesAsync(); + + return Ok(); + } +} \ No newline at end of file diff --git a/3. RESTful-API workshop/Message-API/MessageAPI.csproj b/3. RESTful-API workshop/Message-API/MessageAPI.csproj new file mode 100644 index 0000000..5a146bb --- /dev/null +++ b/3. RESTful-API workshop/Message-API/MessageAPI.csproj @@ -0,0 +1,20 @@ + + + + net6.0 + enable + enable + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + diff --git a/3. RESTful-API workshop/Message-API/Models/DTO/MessageItemDTO.cs b/3. RESTful-API workshop/Message-API/Models/DTO/MessageItemDTO.cs new file mode 100644 index 0000000..a7d0a55 --- /dev/null +++ b/3. RESTful-API workshop/Message-API/Models/DTO/MessageItemDTO.cs @@ -0,0 +1,7 @@ +namespace MessageAPI.Models.DTO; + +public class MessageItemDTO +{ + public int Id { get; set; } + public string? MainMessage { get; set; } +} \ No newline at end of file diff --git a/3. RESTful-API workshop/Message-API/Models/DTO/MessageUpdateDTO.cs b/3. RESTful-API workshop/Message-API/Models/DTO/MessageUpdateDTO.cs new file mode 100644 index 0000000..925efb1 --- /dev/null +++ b/3. RESTful-API workshop/Message-API/Models/DTO/MessageUpdateDTO.cs @@ -0,0 +1,6 @@ +namespace MessageAPI.Models.DTO; + +public class MessageUpdateDTO +{ + public string? MainMessage { get; set; } +} \ No newline at end of file diff --git a/3. RESTful-API workshop/Message-API/Models/MessageContext.cs b/3. RESTful-API workshop/Message-API/Models/MessageContext.cs new file mode 100644 index 0000000..e23e1d3 --- /dev/null +++ b/3. RESTful-API workshop/Message-API/Models/MessageContext.cs @@ -0,0 +1,13 @@ +using Microsoft.EntityFrameworkCore; + +namespace MessageAPI.Models; + +public class MessageContext : DbContext +{ + public MessageContext(DbContextOptions options) + : base(options) + { + } + + public DbSet MessageItems { get; set; } = default!; +} \ No newline at end of file diff --git a/3. RESTful-API workshop/Message-API/Models/MessageItem.cs b/3. RESTful-API workshop/Message-API/Models/MessageItem.cs new file mode 100644 index 0000000..9569d70 --- /dev/null +++ b/3. RESTful-API workshop/Message-API/Models/MessageItem.cs @@ -0,0 +1,8 @@ +namespace MessageAPI.Models; + +public class MessageItem +{ + public int Id { get; set; } + public string? MainMessage { get; set; } + public string? Password { get; set; } +} \ No newline at end of file diff --git a/3. RESTful-API workshop/Message-API/Program.cs b/3. RESTful-API workshop/Message-API/Program.cs new file mode 100644 index 0000000..00bcee9 --- /dev/null +++ b/3. RESTful-API workshop/Message-API/Program.cs @@ -0,0 +1,34 @@ +using Microsoft.EntityFrameworkCore; +using MessageAPI.Models; + +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. + +builder.Services.AddControllers(); +builder.Services.AddDbContext(opt => + opt.UseInMemoryDatabase("Messages")); +builder.Services.AddSwaggerGen(c => +{ + c.SwaggerDoc("v1", new() { Title = "MessageAPI", Version = "v1" }); +}); +builder.Services.AddLogging(); + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +if (builder.Environment.IsDevelopment()) +{ + // app.UseDeveloperExceptionPage(); +} + +app.UseSwagger(); +app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MessageAPI v1")); +app.UseHttpsRedirection(); + +app.UseAuthorization(); +app.UseHttpLogging(); + +app.MapControllers(); + +app.Run(); \ No newline at end of file diff --git a/3. RESTful-API workshop/Message-API/Properties/launchSettings.json b/3. RESTful-API workshop/Message-API/Properties/launchSettings.json new file mode 100644 index 0000000..a040640 --- /dev/null +++ b/3. RESTful-API workshop/Message-API/Properties/launchSettings.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:39533", + "sslPort": 44361 + } + }, + "profiles": { + "MessageAPI": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7298;http://localhost:5250", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/3. RESTful-API workshop/Message-API/README.md b/3. RESTful-API workshop/Message-API/README.md new file mode 100644 index 0000000..ec99532 --- /dev/null +++ b/3. RESTful-API workshop/Message-API/README.md @@ -0,0 +1,4 @@ +# How to run +Ensure that you have [.Net 6.0 SDK](https://dotnet.microsoft.com/en-us/download/dotnet/6.0) installed on your computer, open a terminal in this folder and run `dotnet restore` then `dotnet run` + +> Understanding the API source code is not required for this module. However, this may help you with phase 2 and 3 :) \ No newline at end of file diff --git a/3. RESTful-API workshop/Message-API/appsettings.Development.json b/3. RESTful-API workshop/Message-API/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/3. RESTful-API workshop/Message-API/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/3. RESTful-API workshop/Message-API/appsettings.json b/3. RESTful-API workshop/Message-API/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/3. RESTful-API workshop/Message-API/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/3. RESTful-API workshop/README.md b/3. RESTful-API workshop/README.md index 467dbfd..d0440a5 100644 --- a/3. RESTful-API workshop/README.md +++ b/3. RESTful-API workshop/README.md @@ -1,38 +1,42 @@ -# MSA 2022 RESTful API workshop +# RESTful API Workshop -Welcome to the RESTful API Workshop. The goal for this workshop is for you to get familar with RESTful API concepts and have some hands on experience with interactive with an API. You will perform CRUD operations, that is, Create, Read, Update and Delete operations on an API that we have created. You may use any tools to interact with the API, such as JavaScript, Python and Postman. +Welcome to the RESTful API Workshop. The goal for this workshop is for you to get familiar with RESTful API concepts and have some hands on experience with interactive with an API. You will perform CRUD operations, that is, Create, Read, Update and Delete operations on an API that we have created. You may use any tools to interact with the API, such as JavaScript, Python and Postman. - Pre-requisite: https://docs.microsoft.com/en-us/learn/modules/build-web-api-minimal-api/ If you are not sure what tool to use to interact with the API, we recommend you to use [Postman](https://www.postman.com/), it is a GUI API platform for building and using APIs. -## Assignment +> Alternatively, you can also use the swagger UI built into the web API. -### Exercise 1: READ +> You can find the UI by visiting: [https://2022-nsmsa-phase-1-api.azurewebsites.net/swagger](https://2022-nsmsa-phase-1-api.azurewebsites.net/swagger). However, we recommend that you don't use this UI unless you are stuck. -Get a list of messages that other people have created in the API. The link to the API endpoint is: https://www.2022-nsmsa-phase-1-api.azurewebsites.net/api/message +## Assignment +### Exercise 1: READ -> Hint: For this exercise, you will need to use the HTTP GET Request. +Get a list of messages that other people have created in the API. The link to the API endpoint is: https://2022-nsmsa-phase-1-api.azurewebsites.net/api/message +> Hint: For this exercise, you will need to use the HTTP GET Request. ### Exercise 2: CREATE -Now that you have retrieved information from the API, let's try to do add something to the database via the API. Again, use the same endpoint, but a different HTTP method, post a message to the API: https://www.2022-nsmsa-phase-1-api.azurewebsites.net/api/message -The API takes in form-data with three key-value pair: Nickname, Message and Password. The nickname and message will be publicly displayed, whereas password will be used to authenticate you when you want to update or delete your message. Please do not put in the password that you have used somewhere else for this exercise. +Now that you have retrieved information from the API, let's try to do add something to the database via the API. Again, use the same endpoint, but a different HTTP method, post a message to the API: https://2022-nsmsa-phase-1-api.azurewebsites.net/api/message -> Hint: You will need to use an HTTP POST request. +The API takes in [json](https://json.org/example.html) formatted data with three key-value pair: "Nickname", "MainMessage" and "Password". The nickname and message will be publicly displayed, whereas password will be used to authenticate you when you want to update or delete your message. Please do not put in the password that you have used somewhere else for this exercise. +> Hint: You will need to use an HTTP POST request. +> Hint 2: You may also need to set your a HTTP header: "Content-Type" with the value of "application/json". -After you have received the success message, you may retrieve your information using a GET request, just like you did in exercise 1. +After you have received the success message, you may retrieve your information using a GET request, just like you did in exercise 1. ### Exercise 3: UPDATE +After you confirm that your entry is indeed living in the database. You next task is to update the message to say something else. The endpoint for this is: https://2022-nsmsa-phase-1-api.azurewebsites.net/api/message/MESSAGEID, where "MESSAGEID" is ID of the message you would like to update. In order to prevent unauthorized update by other people, you will need to input your password in the HTTP header. The API endpoint takes in json with one key-value pair: MainMessage (Which is the new message you want to update to). -After you confirm that your entry is indeed living in the database. You next task is to update the message to say something else. In order to prevent unauthorized update by other people, you will need to input your password in the HTTP header. The API endpoint takes in form-data with two key-value pair: ID (Which you can find by finding your message with the GET request) and message (Which is the new message you want to update to). - -> Hint: You will want to use PATCH request for this exercise. +> Hint: You will want to use PATCH request for this exercise. ### Exercise 4: DELETE +Your last task is to delete an entry from the database. Again, you will need to authenticate by providing your password in the HTTP header. The API endpoint is: https://2022-nsmsa-phase-1-api.azurewebsites.net/api/message/MESSAGEID, where "MESSAGEID" is ID of the message you would like to delete. -Your last task is to delete an entry from the database. Again, you will need to authenticate by providing your password in the HTTP header. This API endpoint takes in form-data with simply one key-value pair: ID. - -> Hint: You will want to use DELETE request for this exercise. +> Hint: You will want to use DELETE request for this exercise. Note that your message won't get deleted from the database, as we want other students to see your message! But if you have received a 200 status code as a response, considered the task completed! + +### Stuck somewhere? +Feel free to create a new discussion in our GitHub repository! \ No newline at end of file diff --git a/4. Relational DB workshop/README.md b/4. Relational DB workshop/README.md index b736c46..ac7c336 100644 --- a/4. Relational DB workshop/README.md +++ b/4. Relational DB workshop/README.md @@ -1,8 +1,8 @@ # MSA 2022 SQL Relational DB Workshop -Welcome to the SQL Relational DB Workshop. By now, you should be familiar with Basic Ralational Database and SQL queries. +Welcome to the SQL Relational DB Workshop. By now, you should be familiar with Basic Relational Database and SQL queries. -Here is an assignment to help you review those knowledge. +Here is an assignment to help you review your knowledge. > 1. Write an SQL statement that lists school names, student names, and their cities only if the school and the student are in the same city and the student is not from New York. diff --git a/5. C# workshop/README.md b/5. C# workshop/README.md index f247636..ed73b41 100644 --- a/5. C# workshop/README.md +++ b/5. C# workshop/README.md @@ -4,7 +4,7 @@ | --- | -Welcome to the C# Workshop. The goal for this assignment is for you to get familar with C# concepts and have some hands on experience with C# and dotnet. You will be completing the missing code in this CLI application and fix up the code to pass the existing unit tests. If you haven't already, please complete [Microsoft Learn Path](https://docs.microsoft.com/en-us/learn/paths/csharp-first-steps/) before attempting this workshop. +Welcome to the C# Workshop. The goal for this assignment is for you to get familiar with C# concepts and have some hands on experience with C# and dotnet. You will be completing the missing code in this CLI application and fix up the code to pass the existing unit tests. If you haven't already, please complete [Microsoft Learn Path](https://docs.microsoft.com/en-us/learn/paths/csharp-first-steps/) before attempting this workshop. Pre-requisites: * .NET 6 - [Download](https://dotnet.microsoft.com/en-us/download) diff --git a/README.md b/README.md index 3722f48..ba3622a 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Please refer to this README for guidance. If you are unsure of anything please r **To pass Phase 1, students are required to complete / obtain 34,000 XP on your Microsoft Learn Account.** -Sign up for Microsoft (MS) Learn [here](https://docs.microsoft.com/en-us/learn/) and start accumulating points by completeing the modules! Pick and choose modules which resonate with you or follow our recommended modules below! +Sign up for Microsoft (MS) Learn [here](https://docs.microsoft.com/en-us/learn/) and start accumulating points by completing the modules! Pick and choose modules which resonate with you or follow our recommended modules below! --- @@ -83,10 +83,10 @@ We have also created small modular workshops for each section of MS Learn. **The - [ ] [5. C# workshop](https://github.com/NZMSA/2022-Phase-1/tree/main/5.%20C%23%20workshop) - [ ] Week 7 (27 MAY - 2 JUN) - [ ] [HTML & CSS](https://docs.microsoft.com/en-us/learn/modules/build-simple-website/) - - [ ] [6. HTML & CSS workshop](https://github.com/NZMSA/2022-Phase-1/tree/main/6.%20HTML%2BCSS%20workshop/README.md) + - [ ] [6. HTML & CSS workshop](https://github.com/NZMSA/2022-Phase-1/tree/main/6.%20HTML%2BCSS%20workshop) - [ ] Week 8 (3 JUN - 9 JUN) - [ ] [JavaScript](https://docs.microsoft.com/en-us/learn/paths/web-development-101/) - - [ ] [7. JavaScript workshop](https://github.com/NZMSA/2022-Phase-1/tree/main/7.%JS%20workshop) + - [ ] [7. JavaScript workshop](https://github.com/NZMSA/2022-Phase-1/tree/main/7.%20JS%20workshop) - [ ] Week 9 (10 JUN - 16 JUN) - [ ] [TypeScript](https://docs.microsoft.com/en-us/learn/paths/build-javascript-applications-typescript/) - [ ] [8. TypeScript workshop](https://github.com/NZMSA/2022-Phase-1/tree/main/8.%20Typescript%20workshop)