-
-
Save jipengxiang/32dda180721ba5f624260ec35633668b to your computer and use it in GitHub Desktop.
(1) PLease upload your client side code to call talents API | |
(2) AWS url for web API if you have PUBLISHED your web api to AWS | |
or url to S3 image | |
(3) Sequence diagram for calling Stripe API | |
or calling global weather web service |
1646380
Ong Yi Ren
-
Client Side
$('document').ready(function() {
Stripe.setPublishableKey('pk_test_rwlbSJgFthELe4J2pU94fdMi');
$('#btnCharge').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
Stripe.card.createToken({
number: $('#txtCardNumber').val(),
cvc: $('#txtCvc').val(),
exp_month: $('#txtExpiryMonth').val(),
exp_year: $('#txtExpiryYear').val()
}, stripeResponseHandler);
});
function stripeResponseHandler(status, response) {
var$form = $ ('#frmCharge');
if (response.error) {
// Show the errors on the form
alert(response.error.message);
} else {
// response contains id and card, which contains additional card details
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$('#hdnToken').val(token);
// and submit
$form.get(0).submit();
}
}
}); -
Server side
private async Task ProcessPayment(StripeChargeModel model)
{
return await Task.Run(() =>
{
var myCharge = new StripeChargeCreateOptions
{
// convert the amount of £12.50 to pennies i.e. 1250
Amount = (int)(model.Amount * 100),
Currency = "gbp",
Description = "Description for test charge",
Source = new StripeSourceOptions{
TokenId = model.Token
}
};
var chargeService = new StripeChargeService("sk_test_3wVUBnfmEWmyaY9nEA0Qpniu");
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var stripeCharge = chargeService.Create(myCharge);
return stripeCharge.Id;
});
}
1626216
He Shuimei
`public class TalentsController : ApiController
{
static readonly TalentRepository repository = new TalentRepository();
//[EnableCors(origins: "", headers: "", methods: "*")]
[Route("api/talents")]
public IEnumerable GetAllTalents()
{
return repository.GetAll();
}
[Route("api/talents/{id:int}")]
public Talent GetTalent(int id)
{
Talent item = repository.Get(id);
if (item == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return item;
}
}`
-
[https://s3-ap-southeast-1.amazonaws.com/csc-assignment]
1626261
script.js
$('#loader').hide();
$('#search').keyup(function () {
$('#loader').show();
$('#wholeDiv').hide();
//get data from Restful web Service in development environment
var urlForJson = "/api/talents";
//get data from Restful web Service in production environment
//var urlForJson= "http://csc123.azurewebsites.net/api/talents";
//Url for the Cloud image hosting
var urlForCloudImage = "https://res.cloudinary.com/doh5kivfn/image/upload/v1460006156/talents/";
var searchField = $('#search').val();
var myExp = new RegExp(searchField, "i");
$.ajax({
type: 'GET',
url: urlForJson
}).done(function (data) {
var output = '<ul class="searchresults">';
$.each(data, function (key, val) {
if ((val.Name.search(myExp) != -1) ||
(val.Bio.search(myExp) != -1)) {
output += '<li>';
output += '<h2>' + val.Name + '</h2>';
//get the absolute path for local image
//output += '<img src="images/'+ val.ShortName +'_tn.jpg" alt="'+ val.Name +'" />';
//get the image from cloud hosting
output += '<img src=' + urlForCloudImage + val.ShortName + "_tn.jpg alt=" + val.Name + '" />';
output += '<p>' + val.Bio + '</p>';
output += '</li>';
}
});
output += '</ul>';
$('#update').html(output);
$('#loader').hide();
$('#wholeDiv').show();
}).fail(function (data) {
$('#loader').hide();
$('#update').html("Error " + data.status + ": " + data.statusText);
$('#wholeDiv').show();
});
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Live Search</title>
<link rel="stylesheet" href="mystyle.css" />
<style>
.liClass:hover {
cursor: pointer;
}
@keyframes spinner {
to {
transform: rotate(360deg);
}
}
.spinner:before {
content: '';
box-sizing: border-box;
position: absolute;
top: 50%;
left: 50%;
width: 50px;
height: 50px;
margin-top: -10px;
margin-left: -10px;
border-radius: 50%;
border: 2px solid #f6f;
border-top-color: #0e0;
border-right-color: #0dd;
border-bottom-color: #f90;
animation: spinner .6s linear infinite;
}
</style>
</head>
<body>
<div id="searcharea">
<label for="search">live search</label>
<p>Enter the name or info about a speaker</p>
<input type="search" name="search" id="search" placeholder="name or info" />
</div>
<div class="spinner" id="loader"></div>
<div id="wholeDiv">
<div id="update"></div>
</div>
<script src="jquery.js"></script>
<script src="script.js"></script>
</body>
</html>
1626018
Lau Wei Yang Jeffery
- Talent API Controller
`
[ApiController, Route("api/talents"), RequireHttps]
public class TalentsController : ControllerBase
{
private ITalentRepository talentRepository;
public TalentsController(ITalentRepository talentRepository)
{
this.talentRepository = talentRepository;
}
[HttpGet]
public IEnumerable<Talent> GetAllTalents()
{
//System.Threading.Thread.Sleep(1500);
return talentRepository.GetAll();
}
[HttpGet, Route("{Id:int:min(1)}")]
public Talent GetTalent(int Id) => talentRepository.Get(Id);
}
`
-
AWS S3 Path
https://s3.amazonaws.com/jefferycscca1/image
1646335
Poh Yi Jie Nicholas
-
`public class TalentsController : ApiController
{
static readonly TalentRepository repository = new TalentRepository();
[EnableCors(origins: "", headers: "", methods: "*")][Route("api/talents")] public IEnumerable<Talent> GetAllTalents() { return repository.GetAll(); } [Route("api/talents/{id:int}")] public Talent GetTalent(int id) { Talent item = repository.Get(id); if (item == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return item; }
}
`
1646207
Ng Yu Xiang
[Route("api")]
[ApiController]
public class TalentsController : ControllerBase
{
static readonly TalentRepository repository = new TalentRepository();
[HttpGet,Route("talents")]
public IEnumerable GetAllTalents()
{
return repository.GetAll();
}
[HttpGet,Route("talents/{id:int}")]
public Talent GetTalent(int id)
{
Talent item = repository.Get(id);
if (item == null)
{
return null;
}
return item;
}
}
1626373, Koh Ding Yuan
-
Talents API Controller
` [ApiController, Route("api/talents"), RequireHttps]
public class TalentsController : ControllerBase
{
private ITalentRepository talentRepository = new TalentRepository();
#region TalentsController - Crud Methods
//Create Method
[HttpPost]
public Task PostTalent([BindRequired]TalentView inputTalent)
{
try
{
#region PostTalent - Model Validation
if (!ModelState.IsValid) {
return Task.FromResult(
BadRequest("Invalid object as parameter."));
}
#endregion
#region PostTalent - Conflict Validation
Talent tempTalent = talentRepository.Get(inputTalent.Id);
if (tempTalent != null) {
return Task.FromResult(
Conflict("Talent with the id of " + inputTalent.Id + " already exists."));
}
#endregion
#region PostTalent - Data Processing
talentRepository.Post(inputTalent);
return Task.FromResult(
Ok("Talent with the id of " + inputTalent.Id + " was successfully created."));
#endregion
}
catch (Exception) {
return Task.FromResult(
StatusCode(500));
}
}//Read Methods [HttpGet, Route("{inputId:int:min(1)}")] public Task<Talent> GetTalent(int inputId) => Task.FromResult<Talent>(talentRepository.Get(inputId)); [HttpGet] public Task<IEnumerable<Talent>> GetAllTalents() => Task.FromResult<IEnumerable<Talent>>(talentRepository.GetAll()); //Update Method [HttpPut, Route("{inputId:int:min(0)}")] public Task<IActionResult> PutTalent(int inputId, Talent inputTalent) { try { #region PutTalent - Model Validation if (!ModelState.IsValid) { return Task.FromResult<IActionResult>( BadRequest("Invalid object as parameter.")); } #endregion #region PutTalent - Content Validation Talent tempTalent = talentRepository.Get(inputId); if (tempTalent == null) { return Task.FromResult<IActionResult>( NotFound("Talent with the id of " + inputTalent.Id + " does not exist.")); } if (tempTalent.Id != inputTalent.Id) { tempTalent = talentRepository.Get(inputTalent.Id); if (tempTalent != null) { return Task.FromResult<IActionResult>( Conflict("Potential conflict of proposed Id detected.")); } } #endregion #region PutTalent - Data Processing talentRepository.Put(inputId, inputTalent); return Task.FromResult<IActionResult>( Ok("Talent with the id of " + inputTalent.Id + " was successfully updated.")); #endregion } catch (Exception) { return Task.FromResult<IActionResult>( StatusCode(500)); } } //Delete Method [HttpDelete, Route("{inputId:int:min(1)}")] public Task<IActionResult> DeleteTalent(int inputId) { try { #region DeleteTalent - Content Validation Talent tempTalent = talentRepository.Get(inputId); if (tempTalent == null) { return Task.FromResult<IActionResult>( NotFound("Talent with the id of " + inputId + " does not exist.")); } #endregion #region DeleteTalent - Data Processing talentRepository.Delete(inputId); return Task.FromResult<IActionResult>( Ok("Talent with the id of " + inputId + " was successfully deleted.")); #endregion } catch (Exception) { return Task.FromResult<IActionResult>( StatusCode(500)); } } #endregion
}`
-
AWS S3 Url
https://s3-us-west-2.amazonaws.com/ql-cf-templates-1541035926-39999b7229d833b5-us-west-2/
1503393 | Tang Guan You Darryl
1. TalentsController.cs
using ProductStore.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace ProductStore.Controllers
{
public class TalentsController : ApiController
{
static readonly TalentRepository repository = new TalentRepository();
[Route("api/talents")]
public IEnumerable<Talent> GetAllTalents()
{
return repository.GetAll();
}
[Route("api/talents/{id:int}")]
public Talent GetTalent(int id)
{
Talent item = repository.Get(id);
if (item == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return item;
}
}
}
3.
Some Screenshots for API annotations [Task 3]
Trying to POST object that is not compliant with annotated fields.
Attempting to POST object with fields that are not within pre-definied model.
Some screenshots regarding HTTPS authentication [Task 5]
When requesting with http://, it gets redirected to HTTPS. Below shows that an SSL protocol is needed to go through
Using Postman, there is no response when using http
Database Driven Approach
public class TalentController : ApiController
{
CSC_DatabaseEntitiesv1 db = new CSC_DatabaseEntitiesv1();
///
/// Get all talents objects from database
///
///
[RequireHttps]
[HttpGet]
[EnableCors(origins: "", headers: "", methods: "*")]
[Route("api/talents")]
public IEnumerable GetAllTalents()
{
List talents = db.Talents.ToList();
System.Threading.Thread.Sleep(1500);
return talents;
}
/// <summary>
/// Get one talent object from database by id
/// </summary>
/// <param name="id">The id of the talent object</param>
/// <returns></returns>
[Route("api/talents/{id:int}")]
public Talent GetTalent(int id)
{
Talent item = db.Talents.SingleOrDefault(x => x.Id == id);
if (item == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return item;
}
}
Model
Adding a Database Model
Reference
https://www.youtube.com/watch?v=UrHKfCCncHQ (Start from 2:03)
- AJAX Timeout Retry
$.ajax({ type: 'GET', url: url, async: false, contentType: "application/json", jsonpCallback: callback, dataType: 'jsonp', tryCount: 0, retryLimit: 3, success: function (json) { console.dir('success'); }, error: function (xhr, textStatus, errorThrown ) { if (textStatus == 'timeout') { this.tryCount++; if (this.tryCount <= this.retryLimit) { sleep(1000); $.ajax(this); return; } return; } console.log(e.message); } });
- Entity Framework (DotNet Core)
2.1 Startup - Specify services used
public void ConfigureServices(IServiceCollection services) { services.AddDbContext<TalentDbContext>( options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddScoped<ITalentRepository, SqlTalentRepository>(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
2.2 TalentDbContext - Create DB Context
`
public class TalentDbContext : DbContext
{
public TalentDbContext(DbContextOptions options) : base(options) {}
public DbSet<Talent> Talents { get; set; }
}
`
2.3 SqlTalentRepository - DB CRUD operations
`
public class SqlTalentRepository : ITalentRepository
{
private TalentDbContext _context;
public SqlTalentRepository(TalentDbContext context)
{
_context = context;
}
public void Post(Talent inputTalent)
{
_context.Add(inputTalent);
_context.SaveChanges();
}
public IEnumerable<Talent> GetAll() => _context.Talents;
public Talent Get(int inputId) => _context.Talents.FirstOrDefault(t => t.Id == inputId);
public void Put(int inputId, Talent inputTalent)
{
Talent talent = _context.Talents.FirstOrDefault(x => x.Id == inputId);
if (talent != null)
{
_context.Talents.Remove(talent);
_context.Talents.Add(inputTalent);
}
_context.SaveChanges();
}
public void Delete(int inputId)
{
Talent talent = _context.Talents.FirstOrDefault(x => x.Id == inputId);
_context.Talents.Remove(talent);
_context.SaveChanges();
}
}
`
3. AJAX Loading
$(document).ajaxStart(function () { $("#loading").show(); }).ajaxStop(function () { $("#loading").hide(); });
Lim Wen Hui 1646348
public class TalentsController : ApiController
{
static readonly TalentRepository repository = new TalentRepository();
[EnableCors(origins: "", headers: "", methods: "*")]
// download Microsoft.AspNet.Cors package library
[Route("api/talents")]
public IEnumerable GetAllTalents()
{
return repository.GetAll();
}
[Route("api/talents/{id:int}")]
public Talent GetTalent(int id)
{
Talent item = repository.Get(id);
if (item == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return item;
}
}
1625921
Tan Juin Chen
1.
public class TalentController : ApiController
{
static readonly TalentRepository repository = new TalentRepository();
https://s3-ap-southeast-1.amazonaws.com/talentsphoto