default image
default image
in ,

How to create Yo Yo Test Application in Dotnet Core

The Multistage Fitness Bleep Test determines Aerobic Fitness Levels.

The Multistage Fitness Test (also known as the ‘bleep test’) is now established as the most reliable and easy to use aerobic fitness test. You don’t need to be a scientist to use it.

The bleep test comes with instructions and a table explaining the results. All you need is two markers placed 20 metres apart.

Performers run between markers while the bleep intervals become progressively shorter.

Yo Yo Test Application Walkthrough

Code Repo : https://github.com/pkworlz/YoYoTestDemo

Code

Javascript

// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.

// Write your JavaScript code.

// Vars..

var count;
var timerElement;
var timerIntervalObj;
var cdTimerIntervalObj;
var seconds;
var minutes;
var currentTime;

// CountDown Timer
var cdSeconds;
var cdMinutes;
var cdTimerElement;
var cdCurrentTime;
var countDown;

var siteBaseUrl = "";

var fitnessRatingData;
var allPlayersData;

var progressBarObj = {start: 0, end: 0, current: 0}

// Shuttel Vars

var currentShuttleLevelNumber;
var currentShuttleNumber;
var currentShuttleSpeed;
var currentTotalDistance;



// Init code..
$(function () {
    console.log("ready!");
    init();
});

function init() {
    count = 0;
    timerElement = $('#timer');
    cdTimerElement = $('#cdTimer');
    currentShuttleNumber = 0;
    currentTime = "00:00";

    //load json data..
    getFitnessRatingData();
    getPlayersData();

    //init UI..
    $("#controls").removeAttr("hidden");
    $("#pauseBtn").hide();
    $("#playBtn").show();

    $("#restartBtn").hide();


}

function fitnessRatingDataLoaded() {
    initProgressBarData();

}


// Events Entry..
function stop() {

    console.log("stop timer!");

    stopTimer();

    $("#pauseBtn").hide();
    $("#playBtn").show();
}

function start() {
    console.log("start timer!");
    startTimer();
    startCountDownTimer();

    processSuttle();

    $("#pauseBtn").show();
    $("#playBtn").hide();

    $(".btnPlayer").removeAttr("hidden");
    $("#finishTestBtn").removeAttr("hidden");

}

function restart() {
    location.reload();
}

// Timer Logic..
function timer() {
    count++;

    seconds = pad(count % 60);
    minutes = pad(parseInt(count / 60));

    currentTime = minutes + ":" + seconds

    timerElement.text(currentTime);
    processSuttle();

}


function countDownTimer() {
    countDown--;

    cdSeconds = pad(countDown % 60);
    cdMinutes = pad(parseInt(countDown / 60));

    cdCurrentTime = cdMinutes + ":" + cdSeconds


    
    cdTimerElement.text(cdCurrentTime);

    //console.log(countDown, currentTime);
    if (countDown <= 0) {
        clearInterval(cdTimerIntervalObj);
        countDown = 0;
    }
   
}

// Second Minute Helper
function pad(val) {
    let valString = val + "";
    if (valString.length < 2) {
        return "0" + valString;
    } else {
        return valString;
    }
}

function startTimer() {
    timerIntervalObj = setInterval(timer, 1000);
}

function startCountDownTimer() {
    //countDown = timeSpan;
    cdTimerIntervalObj = setInterval(countDownTimer, 1000);
}

function stopTimer() {
    clearInterval(timerIntervalObj);
    clearInterval(cdTimerIntervalObj);
}

function initShuttleData() {

}


// Shuttle Processing..
function processSuttle() {
    if (fitnessRatingData) {
        $.each(fitnessRatingData, function (index, item) {
            
            if (item.startTime === currentTime) {
                console.log(item, index);

                currentShuttleLevelNumber = item.speedLevel;
                currentShuttleNumber = item.shuttleNo;
                currentShuttleSpeed = item.speed;
                if (index > 0) currentTotalDistance = item.accumulatedShuttleDistance;

                if (index < fitnessRatingData.length) {
                    if (index !== fitnessRatingData.length - 1) {
                        let countDownSeconds = calculateCountDownTime(fitnessRatingData[index], fitnessRatingData[index + 1]);
                        countDown = countDownSeconds;
                    }

                    //resetting timer
                    if (cdTimerIntervalObj) {
                        clearInterval(cdTimerIntervalObj);
                    }
                    
                    startCountDownTimer();

                    // Progress change..
                    progressBarObj.current = item.accumulatedShuttleDistance;
                    //console.log("Progress Bar : ", progressBarObj);
                    calculateProgressBarData();
                }

                if (index === fitnessRatingData.length - 1) {
                    // finished..
                    finishTest();
                }
                

                updateProcessedUi();
                //return false;
            }
        });
    }
}

function updateProcessedUi() {
    $("#currentShuttleLevelNumber").text(currentShuttleLevelNumber);
    $("#currentShuttleNumber").text(currentShuttleNumber);
    $("#currentShuttleSpeed").text(currentShuttleSpeed);
    $("#currentTotalDistance").text(currentTotalDistance);
}

function initProgressBarData() {
    // Setting progress bar..
    if (fitnessRatingData) {
        progressBarObj.start = fitnessRatingData[0].accumulatedShuttleDistance;
        progressBarObj.end = fitnessRatingData[fitnessRatingData.length - 1].accumulatedShuttleDistance;
        progressBarObj.current = fitnessRatingData[0].accumulatedShuttleDistance;
    }
    $("#speed-level-progress-bar").css('width', 0 + '%');
}

// Getting FitnessRating Data..

function getFitnessRatingData() {
    $.ajax({
        url: siteBaseUrl + "/api/test/FitnessRating", success: function (result) {
            fitnessRatingData = result;
            fitnessRatingDataLoaded();
            //console.log(result);
            //processSuttle();
        }
    });
}

function getPlayersData() {
    $.ajax({
        url: siteBaseUrl + "/api/test/GetPlayers", success: function (result) {
            allPlayersData = result;
        }
    });
}

// Utilities..
function calculateCountDownTime(currentRating, nextRating) {

    let currentTime = currentRating.startTime.split(":");
    let nextTime = nextRating.startTime.split(":");

    let countDownTime = (parseInt(nextTime[0]) * 60 + parseInt(nextTime[1])) - (parseInt(currentTime[0]) * 60 + parseInt(currentTime[1]));
    console.log(currentTime, nextTime, countDownTime);

    return countDownTime;
}

function calculateProgressBarData() {
    let progressPercent = percentage(parseInt(progressBarObj.current), parseInt(progressBarObj.end));
    //console.log(progressPercent);
    $("#speed-level-progress-bar").css('width', progressPercent + '%');
}

function percentage(partialValue, totalValue) {
    return parseInt((100 * partialValue) / totalValue);
} 


// Player Events..
function warnPlayer(playerIdUiRef,playerId) {
    let btnName = '#warnBtn' + playerIdUiRef;
    let stopBtnName = '#stopBtn' + playerIdUiRef;
    console.log(btnName, playerIdUiRef);

    $(btnName).attr("disabled", true);
    $(btnName).removeClass("btn-outline-warning");
    $(btnName).addClass("btn-outline-dark");

    $(stopBtnName).attr("disabled", false);



    $.ajax({
        url: siteBaseUrl + "/api/test/WarnPlayer/" + playerId,
        success: function (result) {
            console.log(result);
        }
    });
}

function stopPlayer(playerIdUiRef, playerId) {

    let finishedPlayer = '.finished' + playerIdUiRef;
    let finishedPlayerDd = '#finished' + playerIdUiRef;
    let btnPlayer = '.btn' + playerIdUiRef;

    $(btnPlayer).hide();

    $(finishedPlayer).removeAttr("hidden");
    //$(finishedPlayer).text(currentShuttleLevelNumber + "-" + currentShuttleNumber);
    populateDropDown(finishedPlayerDd, currentShuttleLevelNumber, currentShuttleNumber);

    console.log(playerId);
    let playerResult = currentShuttleLevelNumber + "-" + currentShuttleNumber;

    setPlayerResult(playerId, playerResult);
}

function populateDropDown(playerIdentifier,currentShuttleLevelNumber, currentShuttleNumber) {
    $(function () {
        //Reference the DropDownList.
        let ddPlayerResult = $(playerIdentifier);

        let option1 = $("<option />");
        option1.html("Choose");
        option1.val("");
        ddPlayerResult.append(option1);

        //Loop and add the Year values to DropDownList.
        $.each(fitnessRatingData, function (index, item) {
            let option = $("<option />");
            option.html(item.speedLevel + "-" + item.shuttleNo);
            option.val(item.speedLevel + "-" + item.shuttleNo);
            if (item.speedLevel === currentShuttleLevelNumber && item.shuttleNo === currentShuttleNumber) {
                option.attr("selected",true);
            }
            ddPlayerResult.append(option);
            //console.log(item);
        });
        
    });
}

function playerResultChanged(playerId, playerElementRefId) {
    let playerRef = "#" + playerElementRefId;
    console.log(playerId, playerElementRefId, $(playerRef).val());
    let playerResult = $(playerRef).val();
    setPlayerResult(playerId, playerResult);

}

function setPlayerResult(playerId, playerResult) {
    $.ajax({
        url: siteBaseUrl + "/api/test/ResultPlayer/" + playerId,
        type: "POST",
        data: {
            id: playerId,
            result: playerResult
        },
        success: function (result) {
            console.log(result);
        }
    });
}

function finishTest() {
    $.each(allPlayersData, function (index, item) {
        let runningPlayer = ".finishedPlayer-" + item.id;

        if ($(runningPlayer).attr("hidden")) {
            let nonfinishedPlayer = "Player-" + item.id;

            stopPlayer(nonfinishedPlayer, item.id);

            console.log(item.id);

        } 

    })


    // finished..
    stop();

    $("#finishTestBtnEle").text("Finished");

    $("#pauseBtn").hide();
    $("#playBtn").hide();

    $("#restartBtn").show();
}


Razor

@{
    ViewData["Title"] = "Home Page";

}
@model YoYoTestDemo.ViewModel.HomeViewModel

<div class="container">
    <div class="row">
        <div class="col">
            <div class="text-center">
                <h1 class="display-4">WELCOME TO <br /> YO-YO-TEST</h1>
            </div>
        </div>
    </div>
    <br />
    <div class="row justify-content-center">
        <div class="card" style="width: 30rem;">
            <div class="card-body">
                <div class="row">
                    <div class="col">
                        <div id="controls" class="text-center" hidden>
                            <button id="playBtn" onclick="start();" type="button" class="btn btn-primary btn-lg rounded-pill mainBtn"><i class="fa fa-play" aria-hidden="true"></i></button>
                            <button id="pauseBtn" onclick="stop();" type="button" class="btn btn-primary btn-lg rounded-pill mainBtn"><i class="fa fa-pause" aria-hidden="true"></i></button>
                            <button id="restartBtn" onclick="restart();" type="button" class="btn btn-primary btn-lg rounded-pill mainBtn"><i class="fa fa-refresh" aria-hidden="true"></i></button>
                        </div>
                    </div>
                    <div class="col text-center">
                        <p>Level <span id="currentShuttleLevelNumber"> 0</span> </p>
                        <p>Shuttle <span id="currentShuttleNumber"> 0</span> </p>
                        <p><span id="currentShuttleSpeed">0</span> km/hr</p>

                    </div>

                </div>
                <p>
                    <div class="progress" style="height: 10px;">
                        <div id="speed-level-progress-bar" class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                </p>
            </div>
        </div>
    </div>

    <br />
    <div id="finishTestBtn" class="text-center" hidden><button onclick='finishTest();' id="finishTestBtnEle" type="button" class="btn btn-outline-success btn-sm rounded-pill">Finish Test</button></div>
    <br />
    <div class="row justify-content-center text-center">
        <div class="card" style="width: 30rem;">
            <div class="card-body">
                <div class="row ">

                    <div class="col">
                        <p>Next <br /> Shuttle</p>
                        <p id="cdTimer">__:__</p>

                    </div>
                    <div class="col">
                        <p>Total <br /> Time</p>
                        <p id="timer" class="">__:__</p>

                    </div>
                    <div class="col">
                        <p>Total <br /> Distance</p>
                        <p><span id="currentTotalDistance">__</span> m</p>

                    </div>
                </div>
            </div>
        </div>
    </div>

    @*</div>*@

    <br />
    <div class="row justify-content-center">
        <div class="card" style="width: 30rem;">
            <div class="card-header">
                Participants
            </div>
            <div class="card-body">
                @{
                    int sNo = 0;
                }
                @foreach (var item in Model.players)
                {
                    sNo++;

                    <div class="row" id="player-@item.id">
                        <div class="col-8">
                            @sNo.   @item.name
                        </div>
                        <div class="col-2 btnPlayer-@item.id btnPlayer" hidden>
                            <button id="warnBtnPlayer-@item.id" onclick='warnPlayer("Player-@item.id", @item.id);' type="button" class="btn btn-outline-warning btn-sm rounded-pill">Warn</button>
                        </div>
                        <div class="col-2 btnPlayer-@item.id btnPlayer" hidden>
                            <button id="stopBtnPlayer-@item.id" disabled="disabled" onclick='stopPlayer("Player-@item.id", @item.id);' type="button" class="btn btn-outline-danger btn-sm rounded-pill">Stop</button>
                        </div>
                        <div class="col-4 finishedPlayer-@item.id" hidden> <select id="finishedPlayer-@item.id" onchange='playerResultChanged(@item.id, "finishedPlayer-"+@item.id)'></select></div>
                    </div>
                    <br />

                }
            </div>
        </div>
    </div>

    @*<div class="row">
        <div class="col">
            <p>Participants </p>
            <hr />
        </div>
    </div>*@



</div>

C# Code

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using YoYoTestDemo.Models;
using YoYoTestDemo.Services;
using YoYoTestDemo.ViewModel;

namespace YoYoTestDemo.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private IPlayerService _playerService;

        public HomeController(ILogger<HomeController> logger, IPlayerService playerService)
        {
            _logger = logger;
            _playerService = playerService;
        }

        public IActionResult Index()
        {
            var homeViewModel = new HomeViewModel();

            var allPlayers = _playerService.GetPlayers();

            homeViewModel.players = allPlayers;
            return View(homeViewModel);
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using YoYoTestDemo.Models;
using YoYoTestDemo.Services;
using YoYoTestDemo.ViewModel;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace YoYoTestDemo.Controllers
{

    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {

        private IPlayerService _playerService;

        public TestController(IPlayerService playerService)
        {
            _playerService = playerService;
        }

        
        [HttpGet("GetPlayers")]
        public ActionResult GetPlayers()
        {
            return Ok(_playerService.GetPlayers());
        }

        [HttpGet("FitnessRating")]
        public ActionResult GetFitnessRating()
        {
            var fitnessRatingData = new List<FitnessRating>();
            var folderDetails = Path.Combine(Directory.GetCurrentDirectory(), $"wwwroot\\{"json\\fitnessrating_beeptest.json"}");
            var jsonText = System.IO.File.ReadAllText(folderDetails);

            JArray jsonArray = JArray.Parse(jsonText);
            foreach (var item in jsonArray)
            {
                var jsonObj = JsonConvert.DeserializeObject<FitnessRating>(item.ToString());
                fitnessRatingData.Add(jsonObj);
            }

            return Ok(fitnessRatingData);
        }


        [HttpGet("WarnPlayer/{id}")]
        public ActionResult WarnPlayer(int id)
        {
            var allPlayers = _playerService.GetPlayers();
            try
            {
                int editIndex = allPlayers.FindIndex(o => o.id == id);
                allPlayers[editIndex].warn = true;
                return Ok(allPlayers[editIndex]);
            }
            catch (Exception)
            {
                return NotFound();
            }
           
        }

        [HttpPost("ResultPlayer/{id}")]
        public ActionResult ResultPlayer([FromForm]PlayerResultViewModel playerResultRecieved)
        {
            var playerResult = _playerService.resultPlayer(playerResultRecieved.id, playerResultRecieved.result);
            Console.WriteLine(playerResultRecieved.id + " : " + playerResultRecieved.result);

            return Ok(playerResult);
        }

        
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace YoYoTestDemo.Models
{
    public class Player
    {
        public int id { get; set; }
        public string name { get; set; }
        public bool warn { get; set; }
        public bool stop { get; set; }
        public int levelNumber { get; set; }
        public int shuttleNumber { get; set; }
    }

}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace YoYoTestDemo.Models
{
    public class FitnessRating
    {
        public string AccumulatedShuttleDistance { get; set; }
        public string SpeedLevel { get; set; }
        public string ShuttleNo { get; set; }
        public string Speed { get; set; }
        public string LevelTime { get; set; }
        public string CommulativeTime { get; set; }
        public string StartTime { get; set; }
        public string ApproxVo2Max { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YoYoTestDemo.Models;

namespace YoYoTestDemo.ViewModel
{
    public class HomeViewModel
    {
        public IEnumerable<Player> players { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YoYoTestDemo.Models;

namespace YoYoTestDemo.ViewModel
{
    public class PlayerResultViewModel
    {
        public int id { get; set; }
        public string result { get; set; }
    }
   
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YoYoTestDemo.Models;
using YoYoTestDemo.ViewModel;

namespace YoYoTestDemo.Services
{
    public interface IPlayerService
    {
        List<Player> GetPlayers();
        Player warnPlayer(int playerId);
        PlayerResultViewModel resultPlayer(int playerId, string result);
    }

    public class PlayerService : IPlayerService
    {

        public List<Player> GetPlayers()
        {
            List<Player> players = new List<Player>();

            var player1 = new Player
            {
                id = 1,
                name = "Prem Kumar",
                warn = false,
                stop = false,
                levelNumber = 0,
                shuttleNumber = 0
            };

            var player2 = new Player
            {
                id = 2,
                name = "Jhon Cina",
                warn = false,
                stop = false,
                levelNumber = 0,
                shuttleNumber = 0
            };

            var player3 = new Player
            {
                id = 3,
                name = "Roney Colmen",
                warn = false,
                stop = false,
                levelNumber = 0,
                shuttleNumber = 0
            };

            var player4 = new Player
            {
                id = 4,
                name = "Arnold schwarzenegger",
                warn = false,
                stop = false,
                levelNumber = 0,
                shuttleNumber = 0
            };

            var player5 = new Player
            {
                id = 5,
                name = "Jay Cutler",
                warn = false,
                stop = false,
                levelNumber = 0,
                shuttleNumber = 0
            };

            players.Add(player1);
            players.Add(player2);
            players.Add(player3);
            players.Add(player4);
            players.Add(player5);

            return players;
        }

        public PlayerResultViewModel resultPlayer(int playerId, string result)
        {
            var playerResult = new PlayerResultViewModel();
            var playersList = GetPlayers();
            int editIndex = playersList.FindIndex(o => o.id == playerId);
            playerResult.id = playersList[editIndex].id;
            playerResult.result = result;
            //save data someware..

            return playerResult;
        }

        public Player warnPlayer(int playerId)
        {
            var playersList = GetPlayers();
            int editIndex = playersList.FindIndex(o => o.id == playerId);
            playersList[editIndex].warn = true;
            //save data someware..


            return playersList[editIndex];
        }
    }

}

Author Profile

PREM KUMAR
PREM KUMAR
Hey Its..! Tech Lover , Ionic, Angular, Typescript, Dotnet Core, Node, Like Opencv, AI, ML, Robotics, Iot, Love Music, Cooking, Girls, Innovation

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

What do you think?

400 Points
Upvote Downvote
How to save or export your whatsapp chat history

How to chat on whatsapp without saving number?

4 New features added in Android 11