Introduction
Kindly view my YouTube Video Link to learn about MY EASY KIDS LEARN using MVC.
What is EASY KIDS LEARN?
This is a Kids Easy Learn Game. Here we display 10 questions, and in each question, we will display one image and also we will display the hint for each question. Kids need to enter the correct spelling for each image displayed, For example, we display an image as 10 and kids need to enter the correct word spelling as "TEN." All the images, hint questions, and answer will be posted by the admin. The admin can add any number of images with hint questions and answers for the users (here users are kids) each time the 10 questions are randomly displayed. Using this application kids can easily learn the spelling of words.
This application has two modules:
Admin Module:
Admin can log into system using admin username and password. Admin can manage all question (Add/Edit/Delete and view). Admin can add new questions by uploading images with correct answers and hint questions. This correct answer will be compared with users' entered answers and if both are the same then we display the result for users.
User Module:
Users are not required to login to system. They can directly play the game from the home page. Here users are kids where this application's aim is for kids to easily learn the words. Users can enter the name and start the game. For users we will display 10 random questions, and for each question we will display one image. Users need to enter the correct spelling for each image. This will be very useful for kids to learn spelling for a word by seeing the image and with the hint question.
In this article we will see how to create and manage a question by admin and users to play game using ASP.NET MVC, WEB API and AngularJS.
Here we will see,
- Easy Kids Question Management (Only Admin user can View All / Create /Delete and Edit Questions).
- How users can play the game from home page by entering their name.
Prerequisites
Visual Studio 2015: You can download it from here.
Using the code
1. Create Database and Table
We will create a KidsLearnerMaster table under the Database ‘KidsLearnerDB. The following is the script to create a database, table and sample insert query. Run this script in your SQL Server. I have used SQL Server 2014.
USE MASTER;
IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'KidsLearnerDB' )
BEGIN
ALTER DATABASE KidsLearnerDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE
DROP DATABASE KidsLearnerDB ;
END
CREATE DATABASE KidsLearnerDB
GO
USE KidsLearnerDB
GO
IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'kidsLearnerMaster' )
DROP TABLE MenuMaster
GO
CREATE TABLE kidsLearnerMaster
(
KIDIDENTITY int identity(1,1),
IMAGENAME VARCHAR(200) NOT NULL,
ANSWER VARCHAR(100) NOT NULL ,
HINTQUESTION VARCHAR(200) NOT NULL ,
CONSTRAINT [PK_MenuMaster] PRIMARY KEY CLUSTERED
(
[kidIdentity] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
select * from kidsLearnerMaster
Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
values('one.png','ONE','Its a Number this is the First Number')
Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
values('TWO.png','TWO','Its a Number with 3 Character')
Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
values('THREE.png','THREE','Its a Number with 5 Character')
Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
values('FOUR.png','FOUR','Its a Number with 4 Character')
Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
values('FIVE.png','FIVE','Its a Number with 4 Character')
Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
values('SIX.png','SIX','Its a Number with 3 Character')
Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
values('SEVEN.png','SEVEN','Its a Number with 5 Character')
Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
values('EIGHT.png','EIGHT','Its a Number and this number plus 2 is 10')
Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
values('NINE.png','NINE','Its a Number and 10 minus 1 is this number')
Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
values('TEN.png','TEN','Its a Number with 3 Character')
All these 10 default images have been uploaded to my root folder /Images. You can add more questions and images directly using the application.
Stored Procedure : Run all this Procedure one by one in your SQL Server. SP to select all records to display for Admin.
USE KidsLearnerDB
GO
CREATE PROCEDURE [dbo].[USP_KIDSLEARN_SelectALL]
(
@IMAGENAME VARCHAR(100) = ''
)
AS
BEGIN
SELECT
KIDIDENTITY,IMAGENAME,ANSWER,HINTQUESTION
FROM kidsLearnerMaster
WHERE
IMAGENAME like @IMAGENAME +'%'
END
SP to select top 10 Random records to display for users to play the game.
CREATE PROCEDURE [dbo].[USP_KIDSLEARN_SelectALL]
(
@IMAGENAME VARCHAR(100) = ''
)
AS
BEGIN
SELECT
KIDIDENTITY,IMAGENAME,ANSWER,HINTQUESTION
FROM kidsLearnerMaster
WHERE
IMAGENAME like @IMAGENAME +'%'
END
GO
SP to Insert records by Admin
CREATE PROCEDURE [dbo].[USP_KIDSLEARN_Insert]
(
@IMAGENAME VARCHAR(100) = '',
@ANSWER VARCHAR(100) = '',
@HINTQUESTION VARCHAR(200) = ''
)
AS
BEGIN
IF NOT EXISTS (SELECT * FROM kidsLearnerMaster WHERE <a href="mailto:IMAGENAME=@IMAGENAME">IMAGENAME=@IMAGENAME</a>)
BEGIN
Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
values(@IMAGENAME,@ANSWER,@HINTQUESTION)
Select 'Inserted' as results
END
ELSE
BEGIN
Select 'Exists' as results
END
END
SP to Update records by Admin
ALTER PROCEDURE [dbo].[USP_KIDSLEARN_Update]
( @KIDIDENTITY VARCHAR(20) = '',
@IMAGENAME VARCHAR(100) = '',
@ANSWER VARCHAR(100) = '',
@HINTQUESTION VARCHAR(200) = ''
)
AS
BEGIN
IF EXISTS (SELECT * FROM kidsLearnerMaster WHERE <a href="mailto:KIDIDENTITY=@KIDIDENTITY">KIDIDENTITY=@KIDIDENTITY</a>)
BEGIN
UPDATE kidsLearnerMaster SET
<a href="mailto:IMAGENAME=@IMAGENAME">IMAGENAME=@IMAGENAME</a>,
<a href="mailto:ANSWER=@ANSWER">ANSWER=@ANSWER</a>,
<a href="mailto:HINTQUESTION=@HINTQUESTION">HINTQUESTION=@HINTQUESTION</a>
WHERE
<a href="mailto:KIDIDENTITY=@KIDIDENTITY">KIDIDENTITY=@KIDIDENTITY</a>
Select 'updated' as results
END
ELSE
BEGIN
Select 'Not Exists' as results
END
END
SP to Delete record by Admin
Create PROCEDURE [dbo].[USP_KIDSLEARN_Delete]
( @KIDIDENTITY VARCHAR(20) = '' )
AS
BEGIN
DELETE FROM kidsLearnerMaster WHERE <a href="mailto:KIDIDENTITY=@KIDIDENTITY">KIDIDENTITY=@KIDIDENTITY</a>
END
Create your MVC Web Application in Visual Studio 2015
After installing Visual Studio 2015 click Start, then Programs, and select Visual Studio 2015 - Click Visual Studio 2015. Click New, then Project, select Web and then select ASP.NET Web Application. Enter your project name and click OK.
Select MVC,WEB API and click OK.
Web.Config
In web.config file we can find the DefaultConnection Connection string. By default ASP.NET MVC will use this connection string to create all ASP.NET Identity related tables like AspNetUsers, etc. For our application we also need to use the database for other page activities instead of using two different databases, one for User details and one for our own functionality. Here I will be using one database where all ASP.NET Identity tables will be created and also we can create our own tables for other page uses.
Here in connection string change your SQL Server Name, UID and PWD to create and store all user details in one database.
<connectionStrings>
<add name="DefaultConnection" connectionString="data source=YOURSERVERNAME;initial catalog= KidsLearnerDB;user id=UID;password=PWD;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Create default Role for Admin User
Firstly, create default user role like “Admin” and also we will create a default admin user. We will be creating all default roles and user in “Startup.cs”
OWIN (OPEN WEB Interface for .NET) defines a standard interface between .NET and WEB Server and each OWIN application has a Startup Class where we can specify components.
Reference
In “Startup.cs” file we can find the Configuration method. From this method we will be calling our createRolesandUsers() method to create a default user role and user. We will check for Roles already created or not. If Roles, like Admin, is not created, then we will create a new Role as “Admin” and we will create a default user and set the user role as Admin. We will be using this user as super user where the user can Manage Question from our MVC application.
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
createRolesandUsers();
}
private void createRolesandUsers()
{
ApplicationDbContext context = new ApplicationDbContext();
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
if (!roleManager.RoleExists("Admin"))
{
var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
role.Name = "Admin";
roleManager.Create(role);
var user = new ApplicationUser();
user.UserName = "<a href="mailto:syedshanumcain@gmail.com">syedshanumcain@gmail.com</a>";
user.Email = "<a href="mailto:syedshanumcain@gmail.com">syedshanumcain@gmail.com</a>";
string userPWD = "<a href="mailto:A@Z200711">A@Z200711</a>";
var chkUser = UserManager.Create(user, userPWD);
if (chkUser.Succeeded)
{
var result1 = UserManager.AddToRole(user.Id, "Admin");
}
}
}
When we run our application we can see new default ASP.NET user related tables will be created in our KidsLearnerDB Database.
Add Database using ADO.NET Entity Data Model
Right click our project and click Add, then New Item. Select Data, then ADO.NET Entity Data Model and give the name for our EF and click,
Select "EF Designer from database" and click Next.
Connect to our database. Click Next to select our Tables and Stored Procedure for Menu management.
Here we can see newly created KidsLearnerMaster table with existing ASP.NET Identity tables and all newly created stored procedures has been selected for performing our KidsLearnerMaster CRUD operations.
Click finish.
Procedure to add our Web API Controller
Right-click the Controllers folder, click Add and then click Controller.
Select Web API 2 Controller – Empty, click add and give name for our WEB API controller.
Working with WEBAPI Controller for CRUD
Select Controller and add an Empty Web API 2 Controller. Provide your name to the Web API controller and click OK. Here for my Web API Controller I have given the name “KIDSLEARNAPIController." As we have created Web API controller, we can see our controller has been inherited with ApiController. As we all know Web API is a simple and easy way to build HTTP Services for Browsers and Mobiles.
Web API has the following four methods as Get/Post/Put and Delete where:
- Get is to request for thedata. (Select)
- Post is to create a data.(Insert)
- Put is to update the data.
- Delete is to delete data.
Get Method
In our example I have used only a Get method since I am using only a Stored Procedure. We need to create an object for our Entity and write our Get Method to do Select/Insert/Update and Delete operations.
Select Operation
We use a get method to get all the details of the KidslearnMasters table using an entity object and we return the result as IEnumerable. We use this method in our AngularJS and display the result in an MVC page from the AngularJS controller. Using Ng-Repeat we can bind the details.
Here we can see in the getKIDSLEARNSelect method I have passed the search parameter to the USP_KIDSLEARN_Select ALL Stored Procedure. In the Stored Procedure I used like "%" to return all the records if the search parameter is empty.
[HttpGet]
public IEnumerable<USP_KIDSLEARN_SelectALL_Result> getKIDSLEARNSelectALL(string IMAGENAME)
{
if (IMAGENAME == null)
IMAGENAME = "";
return objapi.USP_KIDSLEARN_SelectALL(IMAGENAME).AsEnumerable();
}
Next we have one more Select method .This Method will be used to display top 10 random questions to users.
[HttpGet]
public IEnumerable<USP_KIDSLEARN_Select_Result> getKIDSLEARNSelect(string IMAGENAME)
{
if (IMAGENAME == null)
IMAGENAME = "";
return objapi.USP_KIDSLEARN_Select(IMAGENAME).AsEnumerable();
}
Insert OperationThe same as select, we passed all the parameters to the insert procedure. This insert method will return the result from the database if a record is inserted or not. We will get the result and display it from the AngularJS Controller to MVC application.
[HttpGet]
public IEnumerable<string> insertKIDSLEARN(string IMAGENAME, string ANSWER, string HINTQUESTION)
{
return objapi.USP_KIDSLEARN_Insert(IMAGENAME, ANSWER, HINTQUESTION).AsEnumerable();
}
Update Operation
The same as insert, we have passed all the parameters to the Update procedure. This Update method will return the result from the database if a record is updated or not.
[HttpGet]
public IEnumerable<string> updateKIDSLEARN(string kidsIdentity, string IMAGENAME, string ANSWER, string HINTQUESTION)
{
return objapi.USP_KIDSLEARN_Update(kidsIdentity, IMAGENAME, ANSWER, HINTQUESTION).AsEnumerable();
}
Delete Operation
The same as insert, we have passed all the parameters to the Delete procedure. This Delete method will return the result from the database as a record is delete or not.
[HttpGet]
public string deleteKIDSLEARN(string kidsIdentity)
{
objapi.USP_KIDSLEARN_Delete(kidsIdentity);
objapi.SaveChanges();
return "deleted";
}
Admin Module:
In admin module, the Admin can be logged in and manage all Kids Question details.
Creating AngularJS Controller
Firstly, create a folder inside the Scripts folder and we have given the folder name “MyAngular.”
Now add your Angular Controller inside the folder.
Right click the MyAngular folder and click Add and New Item. Select Web and then AngularJS Controller and provide a name for the Controller. I have named my AngularJS Controller “Controller.js”.
Once the AngularJS Controller is created, we can see by default the controller will have the code with the default module definition and all.
If the AngularJS package is missing, then add the package to your project.Right click your MVC project and click Manage NuGet Packages. Search for AngularJS and click Install.
Procedure to Create AngularJS Script Files for Menu CRUD
Modules.js: Here we will add the reference to the AngularJS JavaScript and create an Angular Module named “AngularJs_Module”.
var app;
(function () {
app = angular.module("AngularJs_Module", ['ngAnimate']);
})();
Controllers: In AngularJS Controller I have done all the business logic and returned the data from Web API to our MVC HTML page.
Variable declarations: Firstly, we declared all the local variables which need to be used.
app.controller("AngularJs_Controller", function ($scope, $timeout, $rootScope, $window, $http, FileUploadService) {
$scope.date = new Date();
$scope.MyName = "shanu";
$scope.sImage = "";
$scope.showKidsAdd = true;
$scope.addEditKids = false;
$scope.KidsList = true;
$scope.showItem = true;
$scope.userRoleName = $("#txtuserRoleName").val();
$scope.UImage = "";
$scope.Answer = "";
$scope.Question = "";
Methods
Select Method In the select method I have used $http.get to get the details from Web API. In the get method I will provide our API Controller name and method to get the details.
The final result will be displayed to the MVC HTML page using data-ng-repeat.
selectKidsLearnDetails($scope.sImage);
function selectKidsLearnDetails(IMAGENAME) {
$http.get('/api/KidsLearnAPI/getKIDSLEARNSelectALL/', { params: { IMAGENAME: IMAGENAME } }).success(function (data) {
$scope.KidsLearnData = data;
$scope.showKidsAdd = true;
$scope.addEditKids = false;
$scope.KidsList = true;
$scope.showItem = true;
if ($scope.KidsLearnData.length > 0) {
}
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
});
}
$scope.searchKidsLearnDetails = function () {
selectKidsLearnDetails($scope.sImage);
}
Insert new Question
In the ADD/Edit Details button click we will make visible the Question. Add table details where the Admin user can enter the new Question information. For a new Menu we will make the Menu ID as 0. In the New Menu save button click we will call the save method.
$scope.showKidsAddDetails = function () {
cleardetails();
$scope.showKidsAdd = true;
$scope.addEditKids = true;
$scope.KidsList = true;
$scope.showItem = true;
}
In the Save method we will check for the kidsIdentity. If the kidsIdentitys is “0” then it will insert the new question Master. Here we will call the Insert Web API method and if the MenuIdentitys is > 0 then it means to update the Menu record then we will call the Update Web API method.
Image Upload: In Edit and Add new question admin can upload image to our root folder and image name will be saved to our database.
$scope.ChechFileValid
This method checks if the attached image file is valid or not. If the image file is not valid then display the error message.
$scope.SaveDetail = function ()
In this method pass the image file to the UploadFile method and once the image is uploaded successfully to our root folder the item details will be inserted into database.
fac.UploadFile = function (file) In this method using $http.post we pass our image file to the MVC Controller and our HTTP Post method as in the following:
$scope.Message = "";
$scope.FileInvalidMessage = "";
$scope.SelectedFileForUpload = null;
$scope.FileDescription_TR = "";
$scope.IsFormSubmitted = false;
$scope.IsFileValid = false;
$scope.IsFormValid = false;
$scope.$watch("f1.$valid", function (isValid) {
$scope.IsFormValid = isValid;
});
$scope.ChechFileValid = function (file) {
var isValid = false;
if ($scope.SelectedFileForUpload != null) {
if ((file.type == 'image/png' || file.type == 'image/jpeg' || file.type == 'image/gif') && file.size <= (800 * 800)) {
$scope.FileInvalidMessage = "";
isValid = true;
}
else {
$scope.FileInvalidMessage = "Only JPEG/PNG/Gif Image can be upload )";
}
}
else {
$scope.FileInvalidMessage = "Image required!";
}
$scope.IsFileValid = isValid;
};
$scope.selectFileforUpload = function (file) {
var files = file[0];
$scope.Imagename = files.name;
$scope.SelectedFileForUpload = file[0];
}
$scope.saveDetails = function () {
$scope.IsFormSubmitted = true;
$scope.Message = "";
$scope.ChechFileValid($scope.SelectedFileForUpload);
if ($scope.IsFormValid && $scope.IsFileValid) {
FileUploadService.UploadFile($scope.SelectedFileForUpload).then(function (d) {
if ($scope.kidsIdentitys == 0) {
$http.get('/api/KidsLearnAPI/insertKIDSLEARN/', { params: { IMAGENAME: $scope.Imagename, ANSWER: $scope.Answer, HINTQUESTION: $scope.Question } }).success(function (data) {
$scope.menuInserted = data;
alert($scope.menuInserted);
cleardetails();
selectKidsLearnDetails('');
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
});
}
else { $http.get('/api/KidsLearnAPI/updateKIDSLEARN/', { params: { kidsIdentity: $scope.kidsIdentitys, IMAGENAME: $scope.Imagename, ANSWER: $scope.Answer, HINTQUESTION: $scope.Question } }).success(function (data) {
$scope.menuUpdated = data;
alert($scope.menuUpdated);
cleardetails();
selectKidsLearnDetails('');
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
});
}
}, function (e) {
alert(e);
});
}
else {
$scope.Message = "All the fields are required.";
}
};
})
.factory('FileUploadService', function ($http, $q) {
var fac = {};
fac.UploadFile = function (file) {
var formData = new FormData();
formData.append("file", file);
var defer = $q.defer();
$http.post("/KidslearnAdmin/UploadFile", formData,
{
withCredentials: true,
headers: { 'Content-Type': undefined },
transformRequest: angular.identity
})
.success(function (d) {
defer.resolve(d);
})
.error(function () {
defer.reject("File Upload Failed!");
});
return defer.promise;
}
return fac;
Add MVC controller for Admin page:
We will create new MVC controller named as KidsLearnAdminContrller. In this controller first we check if the user role is admin and also an authorized user. If the user is not logged in and not a Admin user then we will redirect to login page. If the user is logged in then we display the Admin Question Management page.
public string RoleName { get; set; }
public Boolean isAdminUser()
{
if (User.Identity.IsAuthenticated)
{
var user = User.Identity;
ApplicationDbContext context = new ApplicationDbContext();
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var s = UserManager.GetRoles(user.GetUserId());
RoleName = s[0].ToString();
if (RoleName == "Admin")
{
return true;
}
else
{
return false;
}
}
return false;
}
public ActionResult Index()
{
if (User.Identity.IsAuthenticated)
{
var user = User.Identity;
ViewBag.Name = user.Name;
ViewBag.displayMenu = "No";
if (isAdminUser())
{
ViewBag.UserRole = RoleName;
ViewBag.displayMenu = "YES";
return View();
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
return RedirectToAction("Index", "Home");
ViewBag.Name = "Not Logged IN";
}
return RedirectToAction("Index", "Home");
}
In this controller we use the UploadFile method to upload the image to our root folder.
Note:$http.post(“”) we need to provide our MVC Controller name and our HTTPost method name, where we upload the image to our root folder. The following is the code to upload an image to our MVC Controller.
[HttpPost]
public JsonResult UploadFile()
{
string Message, fileName;
Message = fileName = string.Empty;
bool flag = false;
if (Request.Files != null)
{
var file = Request.Files[0];
fileName = file.FileName;
try
{
file.SaveAs(Path.Combine(Server.MapPath("~/Images"), fileName));
Message = "File uploaded";
flag = true;
}
catch (Exception)
{
Message = "File upload failed! Please try again";
}
}
return new JsonResult { Data = new { Message = Message, Status = flag } };
}
User Module:
Same as with admin we will add new AngularJS Controller and we give the AngularJS controller name as KidsController for user module and we declare all local variables to be used.
var app;
(function () {
app = angular.module("AngularJs_ImageModule", ['ngAnimate']);
})();
app.controller("AngularJs_ImageController", function ($scope, $timeout, $rootScope, $window, $http) {
$scope.date = new Date();
$scope.MyName = "Shanu";
$scope.usrName = "";
$scope.Images;
$scope.txtAnswer = "";
$scope.questionCount = 1;
$scope.answerCount = 1;
$scope.totalPoints = 0
$scope.wordCount = 0;
$scope.rowCount = 0;
$scope.Image1 = "";
$scope.ImageAnswer = "won.png";
$scope.Answers = "";
$scope.HintQuestion = "";
$scope.Resuts = "";
$scope.showGameStart = true;
$scope.showGame = false;
$scope.showresult = false;
$scope.mp3 = "~/Sounds/Key.wav"
Game Start Function
By default we will display how to play the game and the rules to play the game and the instructions to start the game. The user can enter their name to start the game. The user cannot start the game without entering their name.
In the Start game button click I call the AngularJS method startGame to check whether the user has entered their name. If the user has not entered their name I will ask to enter the name to start the game. If the user has entered their name then I will call the function to display the first question for the user.
$scope.startGame = function () {
$scope.playKeySound();
if ($scope.usrName == '') {
alert("Enter Your Name to start the game !");
$scope.showGameStart = true;
$scope.showGame = false;
$scope.showresult = false;
}
else {
$scope.questionCount = 1;
$scope.totalPoints = 0;
$scope.wordCount = 0;
$scope.rowCount = 0;
$scope.answerCount = 1;
selectGameDetails('');
$scope.showGameStart = false;
$scope.showGame = true;
$scope.showresult = false;
}
}
Play Sound:
Here I have used Windows default sound for each button click and for correct and wrong answers. In our MVC page we add HTML5 Audio Element tag for playing the sounds.
<tr ng-show="showSounds">
<td>
<audio id="audio1" >
<source src="@Url.Content("~/Sounds/Key.wav")"></source>
Your browser isn't invited for super fun audio time.
</audio>
<audio id="audioOK">
<source src="@Url.Content("~/Sounds/Alarm07Ok.wav")"></source>
Your browser isn't invited for super fun audio time.
</audio>
<audio id="audioNG">
<source src="@Url.Content("~/Sounds/Alarm06NOK.wav")"></source>
Your browser isn't invited for super fun audio time.
</audio>
</td>
</tr>
In our AngularJS Controller in each button click, correct answer and wrong Answer we call the each method to play the sounds.
$scope.playKeySound = function () {
var audio2 = document.getElementById("audio1");
audio2.volume = 1;
audio2.play();
}
$scope.playOKSound = function () {
var audio2 = document.getElementById("audioOK");
audio2.volume = 1;
audio2.play();
}
$scope.playNOKSound = function () {
var audio2 = document.getElementById("audioNG");
audio2.volume = 1;
audio2.play();
}
selectGameDetails() To display the Each question.
When the user clicks on the Start game button we display questions number 1, the total points as 0 and using the $http.get('/api/KidsLearnAPI/getKIDSLEARNSelect/', { params: { IMAGENAME: IMAGENAME } })
we will get 10 random questions from the database and will store the result data to $scope.Images. For the first question the rowcount will be 0, I will display the first question's information with a Hint Answer.
function selectGameDetails(IMAGENAME) {
$http.get('/api/KidsLearnAPI/getKIDSLEARNSelect/', { params: { IMAGENAME: IMAGENAME } }).success(function (data) {
$scope.Images = data;
if ($scope.Images.length > 0) {
$scope.Image1 = $scope.Images[$scope.rowCount].IMAGENAME;
$scope.Answers = $scope.Images[$scope.rowCount].ANSWER;
$scope.HintQuestion = $scope.Images[$scope.rowCount].HINTQUESTION;
$scope.wordCount = $scope.Answers.length;
}
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
});
}
Next Question button Click
In the next button we will check for each answer result entered by the user.
Correct Answer:
We will check the user entered answer with the database result answer. If both answers are correct then we will display the result to answer and award the user 20 total points.
Wrong Answer:
We will check the user-entered answer with the database result answer. If both answers are incorrect then we will display the result to answer and deduct the user total points by 10 (-10).
Final Result, the User Won/Lose the Game
When the user has answered all the 10 questions we will check for the result of Total Points for the user and if the points are less than 200 then we will display the message to the user that they have lost the game.
Here is the AngularJS code to check the user result and display the message.
$scope.findAnswer = function () {
if ($scope.txtAnswer == "") {
alert("Enter the Answer");
return;
}
if ($scope.txtAnswer.toLowerCase() == $scope.Answers.toLowerCase()) {
$scope.playOKSound();
alert("Wow :) You have enter the correct answer and you have got 20 Points for this Answer")
if ($scope.answerCount <= 9) {
$scope.answerCount = $scope.answerCount + 1;
}
$scope.totalPoints = $scope.totalPoints + 20;
}
else {
$scope.playNOKSound();
if ($scope.answerCount > 1)
{
$scope.answerCount = $scope.answerCount - 1;
}
alert("Sorry :( You have enter the wrong answer and you have got -10 points")
$scope.totalPoints = $scope.totalPoints - 10;
}
$scope.txtAnswer = "";
if ($scope.questionCount == 10) {
if ($scope.totalPoints >= 200) {
$scope.playOKSound();
$scope.Resuts = "Wow :) You have won the Game.Good Job " + $scope.usrName;
alert($scope.Resuts)
$scope.ImageAnswer = "won.png";
}
else {
$scope.Resuts = "Sorry " + $scope.usrName + " You lose the game :( .Your Total points are " + $scope.totalPoints + " out of 100 points"
alert($scope.Resuts);
$scope.ImageAnswer = "lose.png";
}
$scope.showGameStart = false;
$scope.showGame = false;
$scope.showresult = true;
return;
}
else {
$scope.questionCount = $scope.questionCount + 1;
$scope.wordCount = 0;
$scope.rowCount = $scope.rowCount + 1;
$scope.Image1 = $scope.Images[$scope.rowCount].image1;
$scope.Image1 = $scope.Images[$scope.rowCount].IMAGENAME;
$scope.Answers = $scope.Images[$scope.rowCount].ANSWER;
$scope.HintQuestion = $scope.Images[$scope.rowCount].HINTQUESTION;
$scope.wordCount = $scope.Answers.length;
}
}
Points of Interest
Firstly, create a sample KidsLearnerDB Database in your SQL Server. In the Web.Config file change the DefaultConnection connection string with your SQL Server Connections. In Startup.cs file I have created default Admin user with UserName "shanu" and password "A@Z200711." This UserName and password will be used to login as Admin user. You can change this user name and password as you like. For security reasons after logging in as Admin you can change the Admin user password as you like.
History
shanuEasyKidsLearnerMVCAngularJS.zip - 2016/03/02