MVC and AngularJS: Easy Kids Learn
You can download the Source Code from this link Download Source Code
Introduction
Kindly view my YouTube Video Link to learn about
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 Image as 10 and kids need to enter the correct word spelling as "TEN". All the Images, Hint Question and Answer will be posted by Admin. Admin can add any number of Images with Hint Question and Answers. For the Users (here users are kids) each time the 10 question’s randomly displayed. Using this application kids can easily learn spelling of words.
This application has two module one
1. Admin Module
2. User Module
Admin Module:
** **Admin can logged into system using admin username and password.Admin can manage all question (Add/Edit/Delete and view) .Admin can add new question by uploading image with correct answer and hint question. This correct answer will be compared with users entered answer and if both are same then we display the result for users.
User Module:
Users not required for login to system. They can directly play the game from Home page. Here users are kids where this applications aim is for kids easily learn the words. Users can enter the name and start the game. For users we will display 10 random question, for each questions 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 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 how to,
- Easy Kids Question Management (Only Admin user can View All / Create /Delete and Edit Questions).
- 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 ‘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.
-- =============================================
-- Author : Shanu
-- Create date : 2016-02-28
-- Description : To Create Database
-- =============================================
--Script to create DB,Table and sample Insert data
USE MASTER;
-- 1) Check for the Database Exists .If the database is exist then drop and create new DB
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 this 10 default images has been uploaded to my root folder /Images. You can add more question and images directly using the application.
Stored Procedure : Run all this Procedure one by one in your SQL Server
1) SP to select all records to display for Admin
USE KidsLearnerDB
GO
-- 2) select all kidsLearnerMaster records
-- Author : Shanu
-- Create date : 2016-02-28
-- Description :select top 10 random kidsLearnerMaster records
-- Tables used : kidsLearnerMaster
-- Modifier : Shanu
-- Modify date : 2016-02-28
-- =============================================
-- To Select all user roles
-- EXEC USP_KIDSLEARN_SelectALL ''
-- =============================================
CREATE PROCEDURE [dbo].[USP_KIDSLEARN_SelectALL]
(
@IMAGENAME VARCHAR(100) = ''
)
AS
BEGIN
SELECT
KIDIDENTITY,IMAGENAME,ANSWER,HINTQUESTION
FROM kidsLearnerMaster
WHERE
IMAGENAME like @IMAGENAME +'%'
END
2) SP to select top 10 Random records to display for users to play the game.
USE KidsLearnerDB
GO
-- 1) select top 10 random kidsLearnerMaster records
-- Author : Shanu
-- Create date : 2016-02-28
-- Description :select top 10 random kidsLearnerMaster records
-- Tables used : kidsLearnerMaster
-- Modifier : Shanu
-- Modify date : 2016-02-28
-- =============================================
-- To Select all user roles
-- EXEC USP_KIDSLEARN_Select ''
-- =============================================
CREATE PROCEDURE [dbo].[USP_KIDSLEARN_Select]
(
@IMAGENAME VARCHAR(100) = ''
)
AS
BEGIN
SELECT TOP 10
KIDIDENTITY,IMAGENAME,ANSWER,HINTQUESTION
FROM kidsLearnerMaster
WHERE
IMAGENAME like @IMAGENAME +'%'
ORDER BY NEWID()
END
3) SP to Insert records by Admin
USE KidsLearnerDB
GO
-- 3) Insert records
-- Author : Shanu
-- Create date : 2016-02-28
-- Description :Insert kidsLearnerMaster records
-- Tables used : kidsLearnerMaster
-- Modifier : Shanu
-- Modify date : 2016-02-28
-- =============================================
-- To Select all user roles
-- EXEC USP_KIDSLEARN_Insert ''
-- =============================================
CREATE PROCEDURE [dbo].[USP_KIDSLEARN_Insert]
(
@IMAGENAME VARCHAR(100) = '',
@ANSWER VARCHAR(100) = '',
@HINTQUESTION VARCHAR(200) = ''
)
AS
BEGIN
IF NOT EXISTS (SELECT * FROM kidsLearnerMaster WHERE IMAGENAME=@IMAGENAME)
BEGIN
Insert into kidsLearnerMaster(IMAGENAME,ANSWER,HINTQUESTION)
values(@IMAGENAME,@ANSWER,@HINTQUESTION)
Select 'Inserted' as results
END
ELSE
BEGIN
Select 'Exists' as results
END
END
4) SP to Update records by Admin
USE KidsLearnerDB
GO
-- 4) Update kidsLearnerMaster records
-- Author : Shanu
-- Create date : 2016-02-28
-- Description :Update kidsLearnerMaster records
-- Tables used : kidsLearnerMaster
-- Modifier : Shanu
-- Modify date : 2016-02-28
-- =============================================
-- To Select all user roles
-- EXEC USP_KIDSLEARN_Update ''
-- =============================================
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 KIDIDENTITY=@KIDIDENTITY)
BEGIN
UPDATE kidsLearnerMaster SET
IMAGENAME=@IMAGENAME,
ANSWER=@ANSWER,
HINTQUESTION=@HINTQUESTION
WHERE
KIDIDENTITY=@KIDIDENTITY
Select 'updated' as results
END
ELSE
BEGIN
Select 'Not Exists' as results
END
END
5) SP to Delete record by Admin
USE KidsLearnerDB
GO
-- 5) Stored procedure To Delete KIDSLEARN
-- Author : Shanu
-- Create date : 2016-02-28
-- Description :To Delete KIDSLEARN detail
-- Tables used : kidsLearnerMaster
-- Modifier : Shanu
-- Modify date : 2016-02-28
-- =============================================
-- To delete KIDSLEARN record
-- =============================================
Create PROCEDURE [dbo].[USP_KIDSLEARN_Delete]
( @KIDIDENTITY VARCHAR(20) = '' )
AS
BEGIN
DELETE FROM kidsLearnerMaster WHERE KIDIDENTITY=@KIDIDENTITY
END
2. Create your MVC Web Application in Visual Studio 2015 ** **
After installing our 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.
https://code.msdn.microsoft.com/site/view/file/149105/1/1.png
Select MVC,WEB API and click OK.
https://code.msdn.microsoft.com/site/view/file/149106/1/2.png
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 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=;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”
https://code.msdn.microsoft.com/site/view/file/149107/1/3.png
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 ourcreateRolesandUsers() 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();
}
// In this method we will create default User roles and Admin user for login
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));
// In Startup iam creating first Admin Role and creating a default Admin User
if (!roleManager.RoleExists("Admin"))
{
// first we create Admin role
var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
role.Name = "Admin";
roleManager.Create(role);
//Here we create a Admin super user who will maintain the website
var user = new ApplicationUser();
user.UserName = "syedshanumcain@gmail.com";
user.Email = "syedshanumcain@gmail.com";
string userPWD = "A@Z200711";
var chkUser = UserManager.Create(user, userPWD);
//Add default User to Role Admin
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.
https://code.msdn.microsoft.com/site/view/file/149108/1/A1.gif
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,
https://code.msdn.microsoft.com/site/view/file/149109/1/4.png
Select "EF Designer from database" and click Next.
https://code.msdn.microsoft.com/site/view/file/149110/1/5.png
Connect to our database. Click Next to select our Tables and Stored Procedure for Menu management.
https://code.msdn.microsoft.com/site/view/file/149111/1/6.png
Here we can see newly create KidsLearnerMaster table with existing ASP.NET Identity tables and all newly created stored procedures has been selected for performing our KidsLearnerMaster CRUD operations.
https://code.msdn.microsoft.com/site/view/file/149112/1/7.png
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 the data. (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.
Next we have one more Select method .This Method will be used to display top 10 random questions to users.
// To select top 10 random results
[HttpGet]
public IEnumerable<USP_KIDSLEARN_Select_Result> getKIDSLEARNSelect(string IMAGENAME)
{
if (IMAGENAME == null)
IMAGENAME = "";
return objapi.USP_KIDSLEARN_Select(IMAGENAME).AsEnumerable();
}
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 as a record is inserted or not. We will get the result and display it from the AngularJS Controller to MVC application.
// To insertKIDSLEARN
[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 as a record is updated or not.
//to Update updateKIDSLEARN
[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.
//to delete KIDSLEARN
[HttpGet]
public string deleteKIDSLEARN(string kidsIdentity)
{
objapi.USP_KIDSLEARN_Delete(kidsIdentity);
objapi.SaveChanges();
return "deleted";
}
Admin Module:
In admin module .Admin can be logged in and manage all Kids Question details
https://code.msdn.microsoft.com/site/view/file/149113/1/A2.gif
Creating AngularJS Controller
Firstly, create a folder inside the **Scripts **folder and we have given the folder name “MyAngular”.
https://code.msdn.microsoft.com/site/view/file/149114/1/8.png
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”.
https://code.msdn.microsoft.com/site/view/file/149115/1/9.png
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.
https://code.msdn.microsoft.com/site/view/file/149118/1/10.png
**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”.
// <reference path="../angular.js" />
/// <reference path="../angular.min.js" />
/// <reference path="../angular-animate.js" />
/// <reference path="../angular-animate.min.js" />
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.
**1. Variable declarations **
Firstly, we declared all the local variables 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();
//This variable will be used for Insert/Edit/Delete Kids Learn Question details. $scope.kidsIdentitys = 0;
$scope.UImage = "";
$scope.Answer = "";
$scope.Question = "";
2. 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.
// This method is to get all the kids Learn Details to display for CRUD.
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 occurred while loading posts!";
});
}
//Search
$scope.searchKidsLearnDetails = function () {
selectKidsLearnDetails($scope.sImage);
}
https://code.msdn.microsoft.com/site/view/file/149119/1/A3.gif
Insert new Question
In the ADD/Edit Details button click we will make visible the QuestionAdd 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.
// New Kids Details Add Details
$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 roopt folder and image name will be saved to our database.
$scope.ChechFileValid
**
**This method checks 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 HTTPost method as in the following:
//Declarationa and Function for Image Upload and Save Data
//--------------------------------------------
// Variables
$scope.Message = "";
$scope.FileInvalidMessage = "";
$scope.SelectedFileForUpload = null;
$scope.FileDescription_TR = "";
$scope.IsFormSubmitted = false;
$scope.IsFileValid = false;
$scope.IsFormValid = false;
//Form Validation
$scope.$watch("f1.$valid", function (isValid) {
$scope.IsFormValid = isValid;
});
// THIS IS REQUIRED AS File Control is not supported 2 way binding features of Angular
// ------------------------------------------------------------------------------------
//File Validation
$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;
};
//File Select event
$scope.selectFileforUpload = function (file) {
var files = file[0];
$scope.Imagename = files.name;
// alert($scope.Imagename);
$scope.SelectedFileForUpload = file[0];
}
//----------------------------------------------------------------------------------------
//Save File
$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 the MenuIdentity ID=0 means its new Menu insert here i will call the Web api insert method
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 { // to update to the Menu details
$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 occurred 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;
//---------------------------------------------
//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 for the user role is admin and also 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.
// GET: KidslearnAdmin
public string RoleName { get; set; }
// GET: Users
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;
}
// GET: Menu
public ActionResult Index()
{
if (User.Identity.IsAuthenticated)
{
var user = User.Identity;
ViewBag.Name = user.Name;
// ApplicationDbContext context = new ApplicationDbContext();
// var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
//var s= UserManager.GetRoles(user.GetUserId());
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 } };
``}
https://code.msdn.microsoft.com/site/view/file/149121/1/A4.gif
User Module:
Same like admin we will add new AngularJS Controller and we give the AngularJS controller name as KidsContrller for user module and we declare all local variables to be used.
https://code.msdn.microsoft.com/site/view/file/149122/1/A5.gif
/// <reference path="../angular.js" />
/// <reference path="../angular.min.js" />
/// <reference path="../angular-animate.js" />
/// <reference path="../angular-animate.min.js" />
var app;
(function () {
app = angular.module("AngularJs_ImageModule", ['ngAnimate']);
})();
app.controller("AngularJs_ImageController", function ($scope, $timeout, $rootScope, $window, $http) {
//Global Variables
$scope.date = new Date();
$scope.MyName = "Shanu";
$scope.usrName = "";
$scope.Images;
$scope.txtAnswer = "";
//Game variable declared
//This variable has been declared to display the Question Number,User Total Points on each questions,
//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.
//rowCount is used to display the Question one by one.
$scope.questionCount = 1;
$scope.answerCount = 1;
$scope.totalPoints = 0
$scope.wordCount = 0;
$scope.rowCount = 0;
//Game Detail Display Variables
$scope.Image1 = "";
$scope.ImageAnswer = "won.png";
$scope.Answers = "";
$scope.HintQuestion = "";
$scope.Resuts = "";
// --
//Game Hidden Table row display
$scope.showGameStart = true;
$scope.showGame = false;
$scope.showresult = false;
//Sound file for play sounds
$scope.mp3 = "~/Sounds/Key.wav"
Game Start Function
https://code.msdn.microsoft.com/site/view/file/149125/1/11.png
**
**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.
https://code.msdn.microsoft.com/site/view/file/149126/1/12.png
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.
//get all image Details
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 increment the user total points with 20.
https://code.msdn.microsoft.com/site/view/file/149127/1/A6.gif
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 decrement the user total points with 10 (-10).
https://code.msdn.microsoft.com/site/view/file/149128/1/A7.gif
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.
// to find the Answer
$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;
}
}
More Information
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.
You can download the Source Code from this link Download Source Code