Skip to content

Instantly share code, notes, and snippets.

@jipengxiang
Last active February 25, 2022 21:42
Show Gist options
  • Save jipengxiang/32dda180721ba5f624260ec35633668b to your computer and use it in GitHub Desktop.
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
@shuimeihe
Copy link

shuimeihe commented Jan 17, 2019

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;
    }
}`
  1. [https://s3-ap-southeast-1.amazonaws.com/csc-assignment]

stripepaymentseqdiagram

@junwei9955
Copy link

1626261

image

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>

@S0methingSimple
Copy link

1626018
Lau Wei Yang Jeffery

  1. 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);
}

`

  1. AWS S3 Path
    https://s3.amazonaws.com/jefferycscca1/image

  2. Sequence Diagram
    stripe_payment

Copy link

ghost commented Jan 18, 2019

1646335
Poh Yi Jie Nicholas

  1. `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;
    }
    

    }
    `

  2. AWS S3
    https://s3-us-west-2.amazonaws.com/ql-cf-templates-1546222745-dd8ab6d8efde128d-us-west-2/talent+search/

sequence

@Excelic
Copy link

Excelic commented Jan 18, 2019

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;
}
}

https://s3-us-west-2.amazonaws.com/ql-cf-templates-1545895724-691cc8dc9db95fe0-us-west-2/TalentSearch/

task6

Copy link

ghost commented Jan 18, 2019

1626373, Koh Ding Yuan

  1. 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
    

    }`

  2. AWS S3 Url
    https://s3-us-west-2.amazonaws.com/ql-cf-templates-1541035926-39999b7229d833b5-us-west-2/

  3. Sequence Diagram
    sequence_diagram

@DarrylTang
Copy link

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.

task6-sequencediagramstripe

Some Screenshots for API annotations [Task 3]

Trying to POST object that is not compliant with annotated fields.

task2-postman-pract3-1

Attempting to POST object with fields that are not within pre-definied model.

task2-postman-pract3-2

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

task5-error

Using Postman, there is no response when using http

task5-postmanerror

@ThePikachu
Copy link

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

image

Adding a Database Model

image
image
image
image

Reference

https://www.youtube.com/watch?v=UrHKfCCncHQ (Start from 2:03)

@S0methingSimple
Copy link

  1. 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); } });

  1. 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(); });

@WeeA5A3
Copy link

WeeA5A3 commented Jan 18, 2019

  1. Incorrect data type creating products:
    picture1

  2. Sequence Diagram Stripe:
    sequence_stripe

@Timelessly
Copy link

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;
    }
}
  1. https://s3-ap-southeast-1.amazonaws.com/cscassignment/talent

web payment stripe

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment