Easy Kids Learn Game Using MVC and AngularJS

 

Kindly view my YouTube Video Link to learn about MY EASY KIDS LEARN using MVC.

Introduction

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:

  1. Admin Module
  2. User Module

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.

Before starting this article kindly go through my previous article ASP.NET MVC 5 Security and Creating User Role. It explains in detail about ASP.NET Identity and creating User Role.

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,

  1. Easy Kids Question Management (Only Admin user can View All / Create /Delete and Edit Questions).
  2. How users can play the game from home page by entering their name. 

Prerequisites

Visual Studio 2015: You can download it from here.

Code part

Create Database and Table

1. Create Database and Table

We will create a KidsLearnerMaster table under the Database ‘KidsLearnerDBThe 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. 

  1. -- =============================================                                  
  2. -- Author      : Shanu                                    
  3. -- Create date : 2016-02-28                                 
  4. -- Description : To Create Database                            
  5.                                
  6. -- =============================================    
  7. --Script to create DB,Table and sample Insert data    
  8. USE MASTER;    
  9. -- 1) Check for the Database Exists .If the database is exist then drop and create new DB    
  10. IF EXISTS (SELECT [nameFROM sys.databases WHERE [name] = 'KidsLearnerDB' )    
  11. BEGIN    
  12. ALTER DATABASE KidsLearnerDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE    
  13. DROP DATABASE KidsLearnerDB ;    
  14. END    
  15.     
  16.     
  17. CREATE DATABASE KidsLearnerDB    
  18. GO    
  19.     
  20. USE KidsLearnerDB    
  21. GO    
  22.   
  23. IF EXISTS ( SELECT [nameFROM sys.tables WHERE [name] = 'kidsLearnerMaster' )    
  24. DROP TABLE MenuMaster    
  25. GO    
  26.     
  27. CREATE TABLE kidsLearnerMaster    
  28. (    
  29.    KIDIDENTITY int identity(1,1),    
  30.    IMAGENAME VARCHAR(200)  NOT NULL,     
  31.    ANSWER VARCHAR(100)  NOT NULL ,  
  32.    HINTQUESTION VARCHAR(200)  NOT NULL ,  
  33. CONSTRAINT [PK_MenuMaster] PRIMARY KEY CLUSTERED          
  34. (         
  35.   [kidIdentity] ASC    
  36.    
  37. )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]         
  38. ON [PRIMARY]       
  39.   
  40. select * from kidsLearnerMaster  
  41.   
  42. Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)  
  43.  values('one.png','ONE','Its a Number this is the First Number')  
  44.   
  45.  Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)  
  46.  values('TWO.png','TWO','Its a Number with 3 Character')  
  47.   
  48.  Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)  
  49.  values('THREE.png','THREE','Its a Number with 5 Character')  
  50.   
  51.  Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)  
  52.  values('FOUR.png','FOUR','Its a Number with 4 Character')  
  53.   
  54.  Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)  
  55.  values('FIVE.png','FIVE','Its a Number with 4 Character')  
  56.   
  57.  Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)  
  58.  values('SIX.png','SIX','Its a Number with 3 Character')  
  59.   
  60.  Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)  
  61.  values('SEVEN.png','SEVEN','Its a Number with 5 Character')  
  62.   
  63.  Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)  
  64.  values('EIGHT.png','EIGHT','Its a Number and this number plus 2 is 10')  
  65.   
  66.  Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)  
  67.  values('NINE.png','NINE','Its a Number and 10 minus 1 is this number')  
  68.   
  69.  Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)  
  70.  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.

  1. USE KidsLearnerDB    
  2. GO    
  3. -- 2) select all kidsLearnerMaster records       
  4.   
  5. -- Author      : Shanu                                                                  
  6. -- Create date :  2016-02-28                                                                  
  7. -- Description :select top 10 random kidsLearnerMaster records                                              
  8. -- Tables used :  kidsLearnerMaster                                                              
  9. -- Modifier    : Shanu                                                                  
  10. -- Modify date : 2016-02-28                                                                  
  11. -- =============================================    
  12. -- To Select all user roles   
  13. -- EXEC USP_KIDSLEARN_SelectALL ''  
  14. -- =============================================    
  15. CREATE PROCEDURE [dbo].[USP_KIDSLEARN_SelectALL]     
  16. (    
  17.      @IMAGENAME            VARCHAR(100)     = ''      
  18.       )         
  19. AS                                                                  
  20. BEGIN         
  21.         SELECT   
  22.                 KIDIDENTITY,IMAGENAME,ANSWER,HINTQUESTION    
  23.         FROM kidsLearnerMaster  
  24.         WHERE  
  25.                 IMAGENAME like  @IMAGENAME +'%'  
  26.           
  27. END  

SP to select top 10 Random records to display for users to play the game.  

  1. USE KidsLearnerDB    
  2. GO    
  3.   
  4. -- 1) select top 10 random kidsLearnerMaster records       
  5.   
  6. -- Author      : Shanu                                                                  
  7. -- Create date :  2016-02-28                                                                  
  8. -- Description :select top 10 random kidsLearnerMaster records                                              
  9. -- Tables used :  kidsLearnerMaster                                                              
  10. -- Modifier    : Shanu                                                                  
  11. -- Modify date : 2016-02-28                                                                  
  12. -- =============================================    
  13. -- To Select all user roles   
  14. -- EXEC USP_KIDSLEARN_Select ''  
  15. -- =============================================    
  16. CREATE PROCEDURE [dbo].[USP_KIDSLEARN_Select]     
  17. (    
  18.      @IMAGENAME            VARCHAR(100)     = ''      
  19.       )         
  20. AS                                                                  
  21. BEGIN         
  22.         SELECT TOP 10   
  23.                 KIDIDENTITY,IMAGENAME,ANSWER,HINTQUESTION    
  24.         FROM kidsLearnerMaster  
  25.         WHERE  
  26.                 IMAGENAME like  @IMAGENAME +'%'  
  27.         ORDER BY NEWID()  
  28. END  
SP to Insert records by Admin 
  1. USE KidsLearnerDB    
  2. GO    
  3.    
  4. -- 3) Insert records       
  5.   
  6. -- Author      : Shanu                                                                  
  7. -- Create date :  2016-02-28                                                                  
  8. -- Description :Insert kidsLearnerMaster records                                              
  9. -- Tables used :  kidsLearnerMaster                                                              
  10. -- Modifier    : Shanu                                                                  
  11. -- Modify date : 2016-02-28                                                                  
  12. -- =============================================    
  13. -- To Select all user roles   
  14. -- EXEC USP_KIDSLEARN_Insert ''  
  15. -- =============================================                               
  16. CREATE PROCEDURE [dbo].[USP_KIDSLEARN_Insert]                                                
  17.    (                         
  18.      @IMAGENAME         VARCHAR(100)     = '',  
  19.      @ANSWER            VARCHAR(100)     = '',  
  20.      @HINTQUESTION      VARCHAR(200)     = ''  
  21.       
  22.       )                                                          
  23. AS                                                                  
  24. BEGIN         
  25.         IF NOT EXISTS (SELECT * FROM kidsLearnerMaster WHERE IMAGENAME=@IMAGENAME)  
  26.             BEGIN  
  27.   
  28.                  Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)  
  29.                 values(@IMAGENAME,@ANSWER,@HINTQUESTION)  
  30.                                  
  31.                     Select 'Inserted' as results  
  32.                           
  33.             END  
  34.          ELSE  
  35.              BEGIN  
  36.                      Select 'Exists' as results  
  37.               END  
  38.   
  39. END  
SP to Update records by Admin  
  1. USE KidsLearnerDB    
  2. GO    
  3. -- 4) Update kidsLearnerMaster records       
  4.   
  5. -- Author      : Shanu                                                                  
  6. -- Create date :  2016-02-28                                                                  
  7. -- Description :Update kidsLearnerMaster records                                               
  8. -- Tables used :  kidsLearnerMaster                                                              
  9. -- Modifier    : Shanu                                                                  
  10. -- Modify date : 2016-02-28                                                                  
  11. -- =============================================    
  12. -- To Select all user roles   
  13. -- EXEC USP_KIDSLEARN_Update ''  
  14. -- =============================================                                  
  15. ALTER PROCEDURE [dbo].[USP_KIDSLEARN_Update]                                                
  16.    ( @KIDIDENTITY       VARCHAR(20)     = '',    
  17.     @IMAGENAME          VARCHAR(100)     = '',  
  18.      @ANSWER            VARCHAR(100)     = '',  
  19.      @HINTQUESTION      VARCHAR(200)     = ''  
  20.       )                                                          
  21. AS                                                                  
  22. BEGIN         
  23.         IF  EXISTS (SELECT * FROM kidsLearnerMaster WHERE KIDIDENTITY=@KIDIDENTITY)  
  24.             BEGIN  
  25.                     UPDATE kidsLearnerMaster SET  
  26.                             IMAGENAME=@IMAGENAME,  
  27.                             ANSWER=@ANSWER,  
  28.                             HINTQUESTION=@HINTQUESTION  
  29.                     WHERE  
  30.                     KIDIDENTITY=@KIDIDENTITY  
  31.                                  
  32.                     Select 'updated' as results                       
  33.             END  
  34.          ELSE  
  35.              BEGIN  
  36.                      Select 'Not Exists' as results  
  37.               END  
  38. END  
SP to Delete record by Admin
  1. USE KidsLearnerDB    
  2. GO  
  3. -- 5) Stored procedure To Delete  KIDSLEARN   
  4.   
  5. -- Author      : Shanu                                                                  
  6. -- Create date : 2016-02-28                                                                 
  7. -- Description :To Delete KIDSLEARN detail                                            
  8. -- Tables used :  kidsLearnerMaster                                                              
  9. -- Modifier    : Shanu                                                                  
  10. -- Modify date : 2016-02-28                                                                  
  11. -- =============================================    
  12. -- To delete KIDSLEARN record  
  13. -- =============================================                                                            
  14. Create PROCEDURE [dbo].[USP_KIDSLEARN_Delete]                                                
  15.    ( @KIDIDENTITY       VARCHAR(20)     = '' )                                                          
  16. AS                                                                  
  17. BEGIN         
  18.         DELETE FROM kidsLearnerMaster WHERE KIDIDENTITY=@KIDIDENTITY                  
  19.               
  20. 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.
 
  1. <connectionStrings>   
  2.  <add name="DefaultConnection" connectionString="data source=YOURSERVERNAME;initial catalog= KidsLearnerDB;user id=UID;password=PWD;Integrated Security=True" providerName="System.Data.SqlClient"  />     
  3. </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.  

  1. public void Configuration(IAppBuilder app)  
  2.         {  
  3.             ConfigureAuth(app);  
  4.             createRolesandUsers();  
  5.         }  
  6.   
  7.   
  8.         // In this method we will create default User roles and Admin user for login  
  9.         private void createRolesandUsers()  
  10.         {  
  11.             ApplicationDbContext context = new ApplicationDbContext();  
  12.   
  13.             var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));  
  14.             var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));  
  15.   
  16.             // In Startup iam creating first Admin Role and creating a default Admin User   
  17.             if (!roleManager.RoleExists("Admin"))  
  18.             {  
  19.                 // first we create Admin rool  
  20.                 var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();  
  21.                 role.Name = "Admin";  
  22.                 roleManager.Create(role);  
  23.                 //Here we create a Admin super user who will maintain the website             
  24.   
  25.                 var user = new ApplicationUser();  
  26.                 user.UserName = "[email protected]";  
  27.                 user.Email = "[email protected]";  
  28.                 string userPWD = "A@Z200711";  
  29.                 var chkUser = UserManager.Create(user, userPWD);  
  30.                 //Add default User to Role Admin  
  31.                 if (chkUser.Succeeded)  
  32.                 {  
  33.                     var result1 = UserManager.AddToRole(user.Id, "Admin");  
  34.   
  35.                 }  
  36.             }  
  37.           
  38.         }  

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. 

  1. // to Search all Kids learn Details  
  2.         [HttpGet]  
  3.         public IEnumerable<USP_KIDSLEARN_SelectALL_Result> getKIDSLEARNSelectALL(string IMAGENAME)  
  4.         {  
  5.             if (IMAGENAME == null)  
  6.                 IMAGENAME = "";  
  7.   
  8.             return objapi.USP_KIDSLEARN_SelectALL(IMAGENAME).AsEnumerable();  
  9.         }  

Next we have one more select method. This Method will be used to display top 10 random questions to users.

  1. // To select top 10 random results  
  2.         [HttpGet]  
  3.         public IEnumerable<USP_KIDSLEARN_Select_Result> getKIDSLEARNSelect(string IMAGENAME)  
  4.         {  
  5.             if (IMAGENAME == null)  
  6.                 IMAGENAME = "";  
  7.             return objapi.USP_KIDSLEARN_Select(IMAGENAME).AsEnumerable();  
  8.         }  

Insert Operation

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

  1. // To insertKIDSLEARN  
  2.         [HttpGet]  
  3.         public IEnumerable<string> insertKIDSLEARN(string IMAGENAME, string ANSWER, string HINTQUESTION)  
  4.         {  
  5.             return objapi.USP_KIDSLEARN_Insert(IMAGENAME, ANSWER, HINTQUESTION).AsEnumerable();  
  6.         }  

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.  

  1. //to Update updateKIDSLEARN  
  2.         [HttpGet]  
  3.         public IEnumerable<string> updateKIDSLEARN(string kidsIdentity, string IMAGENAME, string ANSWER, string HINTQUESTION)  
  4.         {  
  5.             return objapi.USP_KIDSLEARN_Update(kidsIdentity, IMAGENAME, ANSWER, HINTQUESTION).AsEnumerable();  
  6.         }  

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.  

  1. //to Update deleteKIDSLEARN  
  2.         [HttpGet]  
  3.         public string deleteKIDSLEARN(string kidsIdentity)  
  4.         {  
  5.             objapi.USP_KIDSLEARN_Delete(kidsIdentity);  
  6.             objapi.SaveChanges();  
  7.             return "deleted";  
  8.         }  

 

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

  1. // <reference path="../angular.js" />    
  2. /// <reference path="../angular.min.js" />     
  3. /// <reference path="../angular-animate.js" />     
  4. /// <reference path="../angular-animate.min.js" />     
  5. var app;  
  6. (function () {  
  7.     app = angular.module("AngularJs_Module", ['ngAnimate']);  
  8. })();  

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. 

  1. app.controller("AngularJs_Controller"function ($scope, $timeout, $rootScope, $window, $http, FileUploadService) {  
  2.     $scope.date = new Date();  
  3.     $scope.MyName = "shanu";  
  4.     $scope.sImage = "";  
  5.      
  6.   
  7.     $scope.showKidsAdd = true;  
  8.     $scope.addEditKids = false;  
  9.     $scope.KidsList = true;  
  10.     $scope.showItem = true;  
  11.     $scope.userRoleName = $("#txtuserRoleName").val();  
  12.      //This variable will be used for Insert/Edit/Delete Kids Learn Question details. $scope.kidsIdentitys = 0;  
  13.     $scope.UImage = "";  
  14.     $scope.Answer = "";  
  15.     $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.  

  1. // This method is to get all the kids Learn Details to display for CRUD.   
  2.     select KidsLearnDetails($scope.sImage);     
  3.       
  4.   
  5.     function selectKidsLearnDetails(IMAGENAME) {  
  6.         $http.get('/api/KidsLearnAPI/getKIDSLEARNSelectALL/', { params: { IMAGENAME: IMAGENAME } }).success(function (data) {  
  7.             $scope.KidsLearnData = data;  
  8.             $scope.showKidsAdd = true;  
  9.             $scope.addEditKids = false;  
  10.             $scope.KidsList = true;  
  11.             $scope.showItem = true;  
  12.   
  13.             if ($scope.KidsLearnData.length > 0) {  
  14.             }  
  15.         })  
  16.    .error(function () {  
  17.        $scope.error = "An Error has occured while loading posts!";  
  18.    });  
  19.     }  
  20.   
  21.     //Search  
  22.     $scope.searchKidsLearnDetails = function () {  
  23.         selectKidsLearnDetails($scope.sImage);  
  24.     }  

Search Button Click 

  1. <table style="color:#9F000F;font-size:large" cellpadding="4" cellspacing="6">  
  2.   
  3.                                             <tr>  
  4.                                                 <td>  
  5.                                                     <b>Image Name</b>  
  6.                                                 </td>  
  7.   
  8.                                                 <td>  
  9.                                                     : <input type="text" name="txtMenuID" ng-model="sImage" value="" />  
  10.                                                     <br />  
  11.                                                 </td>  
  12.                                                  
  13.                                                 <td>  
  14.                                                     <input type="submit" value="Search" style="background-color:#336699;color:#FFFFFF" ng-click="searchKidsLearnDetails()" />  
  15.   
  16.                                                 </td>  
  17.                                             </tr>  
  18.   
  19.   
  20.                                         </table>  
 

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. 

  1. // New Kids Details Add Details  
  2.     $scope.showKidsAddDetails = function () {  
  3.         cleardetails();  
  4.         $scope.showKidsAdd = true;  
  5.         $scope.addEditKids = true;  
  6.         $scope.KidsList = true;  
  7.         $scope.showItem = true;  
  8.     }  

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: 

  1. //Declarationa and Function for Image Upload and Save Data  
  2.     //--------------------------------------------  
  3.     // Variables  
  4.     $scope.Message = "";  
  5.     $scope.FileInvalidMessage = "";  
  6.     $scope.SelectedFileForUpload = null;  
  7.     $scope.FileDescription_TR = "";  
  8.     $scope.IsFormSubmitted = false;  
  9.     $scope.IsFileValid = false;  
  10.     $scope.IsFormValid = false;  
  11.   
  12.     //Form Validation  
  13.     $scope.$watch("f1.$valid"function (isValid) {  
  14.         $scope.IsFormValid = isValid;  
  15.     });  
  16.   
  17.   
  18.     // THIS IS REQUIRED AS File Control is not supported 2 way binding features of Angular  
  19.     // ------------------------------------------------------------------------------------  
  20.     //File Validation  
  21.     $scope.ChechFileValid = function (file) {  
  22.         var isValid = false;  
  23.         if ($scope.SelectedFileForUpload != null) {  
  24.             if ((file.type == 'image/png' || file.type == 'image/jpeg' || file.type == 'image/gif') && file.size <= (800 * 800)) {  
  25.                 $scope.FileInvalidMessage = "";  
  26.                 isValid = true;  
  27.             }  
  28.             else {  
  29.                 $scope.FileInvalidMessage = "Only JPEG/PNG/Gif Image can be upload )";  
  30.             }  
  31.         }  
  32.         else {  
  33.             $scope.FileInvalidMessage = "Image required!";  
  34.         }  
  35.         $scope.IsFileValid = isValid;  
  36.     };  
  37.   
  38.     //File Select event   
  39.     $scope.selectFileforUpload = function (file) {  
  40.   
  41.         var files = file[0];  
  42.         $scope.Imagename = files.name;  
  43.     //    alert($scope.Imagename);  
  44.         $scope.SelectedFileForUpload = file[0];  
  45.   
  46.     }  
  47.     //----------------------------------------------------------------------------------------  
  48.   
  49.     //Save File  
  50.     $scope.saveDetails = function () {  
  51.        
  52.         $scope.IsFormSubmitted = true;  
  53.        
  54.         $scope.Message = "";  
  55.         $scope.ChechFileValid($scope.SelectedFileForUpload);  
  56.        
  57.         if ($scope.IsFormValid && $scope.IsFileValid) {  
  58.             FileUploadService.UploadFile($scope.SelectedFileForUpload).then(function (d) {  
  59.   
  60.                 //if the MenuIdentity ID=0 means its new Menu insert here i will call the Web api insert method  
  61.                 if ($scope.kidsIdentitys == 0) {  
  62.   
  63.                     $http.get('/api/KidsLearnAPI/insertKIDSLEARN/', { params: { IMAGENAME: $scope.Imagename, ANSWER: $scope.Answer, HINTQUESTION: $scope.Question } }).success(function (data) {  
  64.   
  65.                         $scope.menuInserted = data;  
  66.                         alert($scope.menuInserted);  
  67.   
  68.   
  69.                         cleardetails();  
  70.                         selectKidsLearnDetails('');  
  71.                     })  
  72.              .error(function () {  
  73.                  $scope.error = "An Error has occured while loading posts!";  
  74.              });  
  75.                 }  
  76.   
  77.   
  78.                 else {  // to update to the Menu details  
  79.                     $http.get('/api/KidsLearnAPI/updateKIDSLEARN/', { params: { kidsIdentity: $scope.kidsIdentitys, IMAGENAME: $scope.Imagename, ANSWER: $scope.Answer, HINTQUESTION: $scope.Question } }).success(function (data) {  
  80.                         $scope.menuUpdated = data;  
  81.                         alert($scope.menuUpdated);  
  82.   
  83.                         cleardetails();  
  84.                         selectKidsLearnDetails('');  
  85.                     })  
  86.             .error(function () {  
  87.                 $scope.error = "An Error has occured while loading posts!";  
  88.             });  
  89.                 }  
  90.   
  91.             }, function (e) {  
  92.                 alert(e);  
  93.             });  
  94.         }  
  95.         else {  
  96.             $scope.Message = "All the fields are required.";  
  97.         }  
  98.   
  99.     };  
  100.   
  101. })  
  102.   
  103. .factory('FileUploadService'function ($http, $q) {  
  104.     
  105.     var fac = {};  
  106.     fac.UploadFile = function (file) {  
  107.         var formData = new FormData();  
  108.         formData.append("file", file);  
  109.   
  110.         var defer = $q.defer();  
  111.         $http.post("/KidslearnAdmin/UploadFile", formData,  
  112.             {  
  113.                 withCredentials: true,  
  114.                 headers: { 'Content-Type': #ff0000 },  
  115.                 transformRequest: angular.identity  
  116.             })  
  117.         .success(function (d) {  
  118.             defer.resolve(d);  
  119.         })  
  120.         .error(function () {  
  121.             defer.reject("File Upload Failed!");  
  122.         });  
  123.   
  124.         return defer.promise;  
  125.   
  126.     }  
  127.     return fac;  
  128.   
  129.     //---------------------------------------------  
  130.     //End of Image Upload and Insert record  

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. 

  1. // GET: KidslearnAdmin  
  2.         public string RoleName { getset; }  
  3.         // GET: Users  
  4.         public Boolean isAdminUser()  
  5.         {  
  6.             if (User.Identity.IsAuthenticated)  
  7.             {  
  8.                 var user = User.Identity;  
  9.                 ApplicationDbContext context = new ApplicationDbContext();  
  10.                 var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));  
  11.                 var s = UserManager.GetRoles(user.GetUserId());  
  12.                 RoleName = s[0].ToString();  
  13.                 if (RoleName == "Admin")  
  14.                 {  
  15.                     return true;  
  16.                 }  
  17.                 else  
  18.                 {  
  19.                     return false;  
  20.                 }  
  21.             }  
  22.             return false;  
  23.         }  
  24.         // GET: Menu  
  25.         public ActionResult Index()  
  26.         {  
  27.   
  28.             if (User.Identity.IsAuthenticated)  
  29.             {  
  30.                 var user = User.Identity;  
  31.                 ViewBag.Name = user.Name;  
  32.                 //  ApplicationDbContext context = new ApplicationDbContext();  
  33.                 //  var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));  
  34.                 //var s=    UserManager.GetRoles(user.GetUserId());  
  35.                 ViewBag.displayMenu = "No";  
  36.   
  37.                 if (isAdminUser())  
  38.                 {  
  39.                     ViewBag.UserRole = RoleName;  
  40.                     ViewBag.displayMenu = "YES";  
  41.                     return View();  
  42.                 }  
  43.                 else  
  44.                 {  
  45.                     return RedirectToAction("Index""Home");  
  46.                 }  
  47.   
  48.             }  
  49.             else  
  50.             {  
  51.                 return RedirectToAction("Index""Home");  
  52.   
  53.                 ViewBag.Name = "Not Logged IN";  
  54.             }  
  55.             return RedirectToAction("Index""Home");  
  56.   
  57.         }  

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. 

  1. [HttpPost]  
  2.         public JsonResult UploadFile()  
  3.         {  
  4.             string Message, fileName;  
  5.             Message = fileName = string.Empty;  
  6.             bool flag = false;  
  7.             if (Request.Files != null)  
  8.             {  
  9.                 var file = Request.Files[0];  
  10.                 fileName = file.FileName;  
  11.                 try  
  12.                 {  
  13.                     file.SaveAs(Path.Combine(Server.MapPath("~/Images"), fileName));  
  14.                     Message = "File uploaded";  
  15.                     flag = true;  
  16.                 }  
  17.                 catch (Exception)  
  18.                 {  
  19.                     Message = "File upload failed! Please try again";  
  20.                 }  
  21.   
  22.             }  
  23.             return new JsonResult { Data = new { Message = Message, Status = flag } };  
  24.         }  

 
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.

 
  1. /// <reference path="../angular.js" />    
  2. /// <reference path="../angular.min.js" />     
  3. /// <reference path="../angular-animate.js" />     
  4. /// <reference path="../angular-animate.min.js" />     
  5. var app;  
  6.   
  7. (function () {  
  8.     app = angular.module("AngularJs_ImageModule", ['ngAnimate']);  
  9. })();  
  10.   
  11.   
  12. app.controller("AngularJs_ImageController"function ($scope, $timeout, $rootScope, $window, $http) {  
  13.   
  14.     //Global Variables  
  15.     $scope.date = new Date();  
  16.     $scope.MyName = "Shanu";  
  17.     $scope.usrName = "";  
  18.     $scope.Images;  
  19.     $scope.txtAnswer = "";  
  20.   
  21.     //Game variable declared  
  22.     //This variable has been declared to display the Question Number,User Total Points on each questions,  
  23.     //Each question Answer Correct Word total character Count for example from the Images display the correct answer is Fire then i will display 4 as total Word Count.  
  24.     //rowCount is used to display the Question one by one.  
  25.     $scope.questionCount = 1;  
  26.     $scope.answerCount = 1;  
  27.     $scope.totalPoints = 0  
  28.     $scope.wordCount = 0;  
  29.     $scope.rowCount = 0;  
  30.   
  31.     //Game Detail Display Variables  
  32.     $scope.Image1 = "";     
  33.     $scope.ImageAnswer = "won.png";  
  34.     $scope.Answers = "";  
  35.     $scope.HintQuestion = "";  
  36.     $scope.Resuts = "";  
  37.     //  --  
  38.   
  39.     //Game Hidden Table row display   
  40.     $scope.showGameStart = true;  
  41.     $scope.showGame = false;  
  42.     $scope.showresult = false;  
  43.     //Sound file for play sounds  
  44.     $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. 

  1. $scope.startGame = function () {  
  2.         $scope.playKeySound();  
  3.         if ($scope.usrName == '') {  
  4.             alert("Enter Your Name to start the game !");  
  5.             $scope.showGameStart = true;  
  6.             $scope.showGame = false;  
  7.             $scope.showresult = false;  
  8.         }  
  9.         else {  
  10.             $scope.questionCount = 1;  
  11.             $scope.totalPoints = 0;  
  12.             $scope.wordCount = 0;  
  13.             $scope.rowCount = 0;  
  14.             $scope.answerCount = 1;  
  15.             selectGameDetails('');  
  16.             $scope.showGameStart = false;  
  17.             $scope.showGame = true;  
  18.             $scope.showresult = false;  
  19.         }  
  20.     }  

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. 

  1. <tr ng-show="showSounds">  
  2.             <td>  
  3.                 <audio id="audio1" >  
  4.                     <source src="@Url.Content("~/Sounds/Key.wav")"></source>  
  5.                     Your browser isn't invited for super fun audio time.  
  6.                 </audio>  
  7.                 <audio id="audioOK">  
  8.                     <source src="@Url.Content("~/Sounds/Alarm07Ok.wav")"></source>  
  9.                     Your browser isn't invited for super fun audio time.  
  10.                 </audio>  
  11.                 <audio id="audioNG">  
  12.                     <source src="@Url.Content("~/Sounds/Alarm06NOK.wav")"></source>  
  13.                     Your browser isn't invited for super fun audio time.  
  14.                 </audio>  
  15.   
  16.             </td>  
  17.         </tr>  
In our AngularJS Controller in each button click, correct answer and wrong Answer we call the each method to play the sounds.  
  1. $scope.playKeySound = function () {  
  2.         var audio2 = document.getElementById("audio1");  
  3.         audio2.volume = 1;  
  4.         audio2.play();  
  5.     }  
  6.   
  7.     $scope.playOKSound = function () {         
  8.         var audio2 = document.getElementById("audioOK");  
  9.         audio2.volume = 1;  
  10.         audio2.play();  
  11.     }  
  12.   
  13.     $scope.playNOKSound = function () {  
  14.         var audio2 = document.getElementById("audioNG");  
  15.         audio2.volume = 1;  
  16.         audio2.play();  
  17.     }  
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. 

  1. //get all image Details  
  2.     function selectGameDetails(IMAGENAME) {  
  3.         $http.get('/api/KidsLearnAPI/getKIDSLEARNSelect/', { params: { IMAGENAME: IMAGENAME } }).success(function (data) {  
  4.             $scope.Images = data;  
  5.             if ($scope.Images.length > 0) {  
  6.                 $scope.Image1 = $scope.Images[$scope.rowCount].IMAGENAME;  
  7.                 $scope.Answers = $scope.Images[$scope.rowCount].ANSWER;  
  8.                 $scope.HintQuestion = $scope.Images[$scope.rowCount].HINTQUESTION;   
  9.                 $scope.wordCount = $scope.Answers.length;  
  10.             }  
  11.         })  
  12.         .error(function () {  
  13.             $scope.error = "An Error has occured while loading posts!";  
  14.   
  15.         });  
  16.     }  

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.

  1. // to find the Answer  
  2.     $scope.findAnswer = function () {  
  3.         if ($scope.txtAnswer == "") {  
  4.             alert("Enter the Answer");  
  5.             return;  
  6.         }        
  7.         if ($scope.txtAnswer.toLowerCase() == $scope.Answers.toLowerCase()) {            
  8.             $scope.playOKSound();  
  9.             alert("Wow :) You have enter the correct answer and you have got 20 Points for this Answer")  
  10.             if ($scope.answerCount <= 9) {  
  11.                 $scope.answerCount = $scope.answerCount + 1;  
  12.             }  
  13.             $scope.totalPoints = $scope.totalPoints + 20;  
  14.         }  
  15.   
  16.         else {  
  17.             $scope.playNOKSound();  
  18.             if ($scope.answerCount > 1)  
  19.                 {  
  20.                 $scope.answerCount = $scope.answerCount - 1;  
  21.             }  
  22.             alert("Sorry :( You have enter the wrong answer and you have got -10 points")  
  23.             $scope.totalPoints = $scope.totalPoints - 10;  
  24.         }  
  25.   
  26.         $scope.txtAnswer = "";  
  27.         if ($scope.questionCount == 10) {  
  28.             if ($scope.totalPoints >= 200) {  
  29.                 $scope.playOKSound();  
  30.                 $scope.Resuts = "Wow :) You have won the Game.Good Job " + $scope.usrName;  
  31.                 alert($scope.Resuts)  
  32.                 $scope.ImageAnswer = "won.png";  
  33.             }  
  34.             else {  
  35.                 $scope.Resuts = "Sorry " + $scope.usrName + " You lose the game :( .Your Total points are " + $scope.totalPoints + " out of 100 points"  
  36.                 alert($scope.Resuts);  
  37.                 $scope.ImageAnswer = "lose.png";  
  38.             }  
  39.   
  40.             $scope.showGameStart = false;  
  41.             $scope.showGame = false;  
  42.             $scope.showresult = true;  
  43.             return;  
  44.         }  
  45.         else {  
  46.   
  47.             $scope.questionCount = $scope.questionCount + 1;  
  48.   
  49.             $scope.wordCount = 0;  
  50.             $scope.rowCount = $scope.rowCount + 1;  
  51.   
  52.             $scope.Image1 = $scope.Images[$scope.rowCount].image1;  
  53.             $scope.Image1 = $scope.Images[$scope.rowCount].IMAGENAME;  
  54.             $scope.Answers = $scope.Images[$scope.rowCount].ANSWER;  
  55.             $scope.HintQuestion = $scope.Images[$scope.rowCount].HINTQUESTION;  
  56.   
  57.             $scope.wordCount = $scope.Answers.length;  
  58.         }  
  59.   
  60.     }  

Conclusion

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. You can find default connection string and one more as Entity connection string change both as per your SQL connection.

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.
Read more articles on AngularJS:

Up Next
    Ebook Download
    View all
    Learn
    View all