In this article, we will see in detail how to create an online Mind Reader quiz game using AngularJS and WCF Rest Service.
Introduction
You can also view my previous articles related to AngularJs using MVC and the WCF Rest Service:
Previous articles related to Angular JS, MVC and WEB API:
So What is Mind Reader Quiz Game?
A Mind Reader Quiz game is a quiz game where users can think of any one of his dream stars from the list of names. In an online quiz, there will be some limited questions with Yes or No options that the users will be asked related to his dream star. Depending on the user's answer, the system will finally find the person in the user's mind and produce the result.
In my online quiz application (Shanu-Who's In Your Mind Reader), users can think of a famous person from the list from the Main Page. I will determine who's in your mind. You can select any popular person from the list. He or she might be an Actor, Actress, cricketer or any other celebrity from the list. I will ask a few questions about who's in your mind. You can answer Yes or No. Finally I will tell your the star's personality of whom you are thinking of.
This article will explain in detail how to create an Online Mind Reader quiz game using Angular JS and a WCF Rest Service. This article will explain:
- how to create a WCF Rest service and retrieve data from a database.
- how to install the Angular JS Package into an MVC application.
- how to create our Angular JS application to create our own Master Detail Grid.
- how to use a WCS service in Angular JS to create our own online Quiz Game for Mind Reader.
Note: The prerequisites are Visual Studio 2013 (if you don't have Visual Studio 2013, you can download it from the Microsoft website here).
Here, we can see some basics and reference links for Windows Communication Foundation (WCF). WCF is a framework for building service-oriented applications.
Service-Oriented Application
Using a protocol, the service can be shared and used over a network.
For example, let's consider now we are working on a project and we need to create a common database function and those functions need to be used in multiple projects and the projects are in a different place and connected by the internet.
In this case, we can create a WCF service and we can write all our common database functions in our WCF service class. We can deploy our WCF in IIS and use the URL in our application to do DB functions. In the code part, let's see how to create a WCF REST service and use it in our Angular JS application.
If you are interested in reading more about WCF, then kindly go through this link.
Angular JS
We might be familiar with what the Model, View, View Model (MVVM) and what Model, View and Controller (MVC) are. Angular JS is a JavaScript framework that is purely based on HTML, CSS and JavaScript.
The Angular JS Model View Whatever (MVW) pattern is similar to the MVC and MVVM patterns. In our example, I have used Model, View and Service. In the code part, let's see how to install and create Angular JS in our MVC application.
If you are interested in reading more about Angular JS, then kindly go through this link.
Using the Code
1. Create Database and Table
We will create a Professional_Type
, Character_Type
, Character_Name
and Questions
table under the database MindReader
.
Below is the script to create a database, table and sample insert query.
Run this script in your SQL Server. I have used SQL Server 2012.
USE MASTER
GO
IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'MindReader' )
DROP DATABASE MindReader
GO
CREATE DATABASE MindReader
GO
USE MindReader
GO
IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'Professional_Type' )
DROP TABLE Professional_Type
GO
CREATE TABLE Professional_Type
(
Profes_ID VARCHAR(10) NOT NULL,
Profes_Type VARCHAR(50)
CONSTRAINT [PK_Professional_Type] PRIMARY KEY CLUSTERED
(
[Profes_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, _
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Insert into Professional_Type(Profes_ID,Profes_Type) values('1','Sports')
Insert into Professional_Type(Profes_ID,Profes_Type) values('2','Bollywood Movie Star')
Insert into Professional_Type(Profes_ID,Profes_Type) values('3','kollywood Movie Star')
IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'Character_Type' )
DROP TABLE Character_Type
GO
CREATE TABLE Character_Type
(
Char_ID VARCHAR(10) NOT NULL,
Profes_ID VARCHAR(10) NOT NULL CONSTRAINT _
fk_Professional_Type FOREIGN KEY REFERENCES Professional_Type,
Char_Type VARCHAR(50)
CONSTRAINT [PK_Character_Type] PRIMARY KEY CLUSTERED
(
[Char_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, _
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Insert into Character_Type(Char_ID,Profes_ID,Char_Type) values('1','1','Cricket')
Insert into Character_Type(Char_ID,Profes_ID,Char_Type) values('2','2','Bollywood Actor')
Insert into Character_Type(Char_ID,Profes_ID,Char_Type) values('4','3','kollywood Actor')
IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'Character_Name' )
DROP TABLE Character_Name
GO
CREATE TABLE Character_Name
(
Char_Name_ID VARCHAR(10) NOT NULL,
Char_ID VARCHAR(10) NOT NULL CONSTRAINT _
fk_Character_Type FOREIGN KEY REFERENCES Character_Type,
Char_Name VARCHAR(50),
Char_Status VARCHAR(20)
CONSTRAINT [PK_Char_Name] PRIMARY KEY CLUSTERED
(
[Char_Name_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, _
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Insert into Character_Name(Char_Name_ID,Char_ID,Char_Name,Char_Status) _
values('1','1','Sachin Tendulkar','Past')
Insert into Character_Name(Char_Name_ID,Char_ID,Char_Name,Char_Status) _
values('2','1','Sunil Gavaskar' ,'Past')
Insert into Character_Name(Char_Name_ID,Char_ID,Char_Name,Char_Status) _
values('3','1','Mohammed Azharuddin','Past')
Insert into Character_Name(Char_Name_ID,Char_ID,Char_Name,Char_Status) _
values('4','1','Mahender Singh Dhoni','Present')
Insert into Character_Name(Char_Name_ID,Char_ID,Char_Name,Char_Status) _
values('5','1','Shikhar Dhawan','Present')
Insert into Character_Name(Char_Name_ID,Char_ID,Char_Name,Char_Status) _
values('6','2','Amitabh Bachchan','Present')
Insert into Character_Name(Char_Name_ID,Char_ID,Char_Name,Char_Status) _
values('7','2','Shah Rukh Khan' ,'Present')
Insert into Character_Name(Char_Name_ID,Char_ID,Char_Name,Char_Status) _
values('8','2','Aamir Khan','Present')
Insert into Character_Name(Char_Name_ID,Char_ID,Char_Name,Char_Status) _
values('9','2','Salman Khan','Present')
Insert into Character_Name(Char_Name_ID,Char_ID,Char_Name,Char_Status) _
values('10','4','Rajini Kanth','Present')
Insert into Character_Name(Char_Name_ID,Char_ID,Char_Name,Char_Status) _
values('11','4','Ajith Kumar' ,'Present')
Insert into Character_Name(Char_Name_ID,Char_ID,Char_Name,Char_Status) _
values('12','4','Kamala Hasan','Present')
Insert into Character_Name(Char_Name_ID,Char_ID,Char_Name,Char_Status) _
values('13','4','Vijay','Present')
IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'Questions' )
DROP TABLE Questions
GO
CREATE TABLE Questions
(
Question_ID VARCHAR(10) NOT NULL,
Char_Name_ID VARCHAR(10) NOT NULL CONSTRAINT _
fk_Character_Name FOREIGN KEY REFERENCES Character_Name,
Question VARCHAR(300),
Answer VARCHAR(100)
CONSTRAINT [PK_Questions] PRIMARY KEY CLUSTERED
(
[Question_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, _
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('1','1','Is he Present Player?','No')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('2','1','Is he born in Mumbai, Maharastra?' ,'Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('3','1','Is he also called as nick name Little Master?','Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('4','2','Is he Present Player?','No')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('5','2','Is he born in Mumbai, Maharastra?' ,'Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('6','2','Is he also called as nickname Sunny?','Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('7','3','Is he Present Player?','No')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('8','3','Is he born in Hyderabad, Andhra Pradesh?' ,'Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('9','3','Is he also called as nickname Ajju?','Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('10','4','Is he Present Player?','Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('11','4','Is he born in Ranchi, Jharkhand?' ,'Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('12','4','Is he also called as nickname Mahi?','Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('13','5','Is he Present Player?','Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('14','5','Is he born in Delhi?' ,'Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('15','5','Is he also called as nickname Gabbar?','Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('16','6','Is Your Actor Born in Allahabad, Uttar Pradesh?','Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('17','6','Is Your Actor Father Was a Hindi Poet?' ,'Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('18','6','Is your Actor married to a Actress named Jaya Bhaduri?','Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('19','7','Is your Actor born in New Delhi?','Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('20','7','Is one of his Famous film _
runs in a Theatre for nearly 20 Years?' ,'Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('21','7','Is your Actor is called as King Khan?','Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('22','8','Is your Actor born in Mumbai?','Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('23','8','Is his father was a producer?' ,'Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('24','8','Is he acted in a movie which has _
Cricket Matches and that movie got so many awards?','Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('25','9','Is your Actor born in Indore?','Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('26','9','Is his father was a screenwriter?' ,'Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('27','9',') Is your Actor brothers name is Arbaaz khan?','Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('28','10','Is your Actor born in Karnataka?','Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('29','10','Is your Actor is called as Super Star?' ,'Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('30','10','Is your Actor is called as Thalapathy?','Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('31','11','Is Your Actor Born in Hyderabad?','Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('32','11','Is Your Actor Motor Bike racer?' ,'Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('33','11','Is your Actor nick name is Thala?','Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('34','12','Is your Actor born in Paramakudi?','Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('35','12','Is your Actor received padma shri award during 1990?' ,'Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('36','12','Is your Actor acted in a file with 10 Characters Roles?','Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('37','13','Is your Actor born in Chennai?','Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('38','13','Is his father producer/Director?' ,'Yes')
Insert into Questions(Question_ID,Char_Name_ID,Question,Answer) _
values('39','13','Is your Actor Called as Ilaya Thalapathy?','Yes')
select * from Professional_Type
select * from Character_Type
select * from Character_Name
select * from Questions order by Question_ID,Char_Name_ID
select A.Question_ID,
A.Char_Name_ID,
B.Char_ID,
A.Question,
A.Answer,
B.Char_Name,
B.Char_Status
FROM
Questions A
Inner JOIN Character_Name B
ON A.Char_Name_ID=B.Char_Name_ID
WHERE
B.Char_ID='1'
order by cast(A.Question_ID as INT)
2. Create WCF REST Service
Open Visual Studio 2013 -> Select File- New- Project – Select WCF Service Application -> Select your Project path and Name your WCF service and click OK.
Once we created our WCF Service, we can see “IService.CS” and “Service1.svc” in Solution Explorer as below:
IService.CS - > In “IService.CS”, we can see three Contracts by default:
[ServiceContract]
- > describes the methods or any operations available for service. Service Contract is an Interface and methods can be declared inside the Service Interface using Operation Contract attribute. [OperationContract]
-> is similar to web service [WEBMETHOD]
[DataContract]
-> describes the data exchange between the client and the service.
[ServiceContract]
The below code will be automatically created for all the IService.CS file. We can change and write our own code here:
public interface IService1
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
}
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
Data Contract
In our example, we need to get both Character Type, Character Name and from database, so I have created three Data Contract “CharacterTypeDataContract
”, “CharacterNameDataContract
” and “questionAnswersDataContract
”.
Here, we can see we have decelerated our entire Table column name as Data Member.
public class whosInYourMinDataContract
{
[DataContract]
public class CharacterTypeDataContract
{
[DataMember]
public string Char_ID { get; set; }
[DataMember]
public string Character_Type { get; set; }
}
[DataContract]
public class CharacterNameDataContract
{
[DataMember]
public string Char_Name_ID { get; set; }
[DataMember]
public string Char_ID { get; set; }
[DataMember]
public string Char_Name { get; set; }
[DataMember]
public string Char_Status { get; set; }
}
[DataContract]
public class questionAnswersDataContract
{
[DataMember]
public string Question_ID { get; set; }
[DataMember]
public string Char_Name_ID { get; set; }
[DataMember]
public string Char_ID { get; set; }
[DataMember]
public string Question { get; set; }
[DataMember]
public string Answer { get; set; }
[DataMember]
public string Char_Name { get; set; }
[DataMember]
public string Char_Status { get; set; }
}
}
Service Contract
In Operation Contract, we can see “WebInvoke
” and “WebGet
” which is to retrieve the data from the database in REST Service.
RequestFormat = WebMessageFormat.Json
ResponseFormat = WebMessageFormat.Json
Here, we can see both the request and response format here I have used the Json format.
- JSON ->JavaScript Object Notation is a lightweight data interchange format
UriTemplate
- > is our Method Name and here our method return type is List
Here, I have declared three methods as “GetCharacterType
”, “getCharacterNames
” and “questionAnswers
”. “GetOrderMaster
” method is used to get the Celebrity Profession (he or she might be cricketer, movie Actor, etc.) in “getCharacterNames
”. To get all the Celebrity Names from the database and “questionAnswers
” is to get all the questions from the database.
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/GetCharacterType/")]
List<whosInYourMinDataContract.CharacterTypeDataContract> GetCharacterType();
[OperationContract]
[WebGet(RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getCharacterNames/")]
List<whosInYourMinDataContract.CharacterNameDataContract> getCharacterNames();
[OperationContract]
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/questionAnswers/{Char_ID}")]
List<whosInYourMinDataContract.questionAnswersDataContract>
questionAnswers(string Char_ID);
}
Iservice.Cs -> Complete Source Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace Shanu_QuizWcfService
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/GetCharacterType/")]
List<whosInYourMinDataContract.CharacterTypeDataContract> GetCharacterType();
[OperationContract]
[WebGet(RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/getCharacterNames/")]
List<whosInYourMinDataContract.CharacterNameDataContract> getCharacterNames();
[OperationContract]
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/questionAnswers/{Char_ID}")]
List<whosInYourMinDataContract.questionAnswersDataContract>
questionAnswers(string Char_ID);
}
public class whosInYourMinDataContract
{
[DataContract]
public class CharacterTypeDataContract
{
[DataMember]
public string Char_ID { get; set; }
[DataMember]
public string Character_Type { get; set; }
}
[DataContract]
public class CharacterNameDataContract
{
[DataMember]
public string Char_Name_ID { get; set; }
[DataMember]
public string Char_ID { get; set; }
[DataMember]
public string Char_Name { get; set; }
[DataMember]
public string Char_Status { get; set; }
}
[DataContract]
public class questionAnswersDataContract
{
[DataMember]
public string Question_ID { get; set; }
[DataMember]
public string Char_Name_ID { get; set; }
[DataMember]
public string Char_ID { get; set; }
[DataMember]
public string Question { get; set; }
[DataMember]
public string Answer { get; set; }
[DataMember]
public string Char_Name { get; set; }
[DataMember]
public string Char_Status { get; set; }
}
}
}
Add Database using ADO.NET Entity Data Model
Right click your WCF project and select Add New Item ->Select ADO.NET Entity Data Model and click Add.
Select EF Designer from Database and click Next.
Click New Connection.
Here, we can select our Database Server Name and enter your DB server SQL Server Authentication User ID and Password. We have already created our database as “OrderManagement
”, so we can select the database and click OK.
Click Next and select our tables need to be used and click Finish.
Here, we can see now we have created our shanuQuizModel
.
Service1.SVC
“Service.SVC.CS” implements IService
Interface and override and define all the methods of Operation Contract.
For example, here we can see that I have implemented the IService1
in Service1
class. Created the Object for our Entity model and in questionAnswers
using LINQ Query, I have used the Linq Join
query to join 2 tables and get the result from the database filtering by the Char_Id
and result was been added to the list.
public class Service1 : IService1
{
shanuQuizEntities OME;
public Service1()
{
OME = new shanuQuizEntities();
}
public List<whosInYourMinDataContract.questionAnswersDataContract>
questionAnswers(string Char_ID)
{
var query = (from A in OME.Questions
join B in OME.Character_Name on A.Char_Name_ID equals B.Char_Name_ID
where B.Char_ID.Equals(Char_ID)
select new
{
A.Question_ID,
A.Char_Name_ID,
B.Char_ID,
A.Question,
A.Answer,
B.Char_Name,
B.Char_Status
}).ToList().OrderBy(q => Int32.Parse(q.Question_ID));
List<whosInYourMinDataContract.questionAnswersDataContract>
questionAnswersList = new List<whosInYourMinDataContract.questionAnswersDataContract>();
query.ToList().ForEach(rec =>
{
questionAnswersList.Add
(new whosInYourMinDataContract.questionAnswersDataContract
{
Question_ID =rec.Question_ID,
Char_Name_ID = rec.Char_Name_ID,
Char_ID = rec.Char_ID,
Question = rec.Question,
Answer = rec.Answer,
Char_Name = rec.Char_Name,
Char_Status = rec.Char_Status
});
});
return questionAnswersList;
}
}
“Service.SVC.CS” - Complete Source Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using Shanu_QuizWcfService.Model;
namespace Shanu_QuizWcfService
{
public class Service1 : IService1
{
shanuQuizEntities OME;
public Service1()
{
OME = new shanuQuizEntities();
}
public List<whosInYourMinDataContract.CharacterTypeDataContract> GetCharacterType()
{
var query = (from a in OME.Character_Type
select a).Distinct();
List<whosInYourMinDataContract.CharacterTypeDataContract>
CharacterTypeList =
new List<whosInYourMinDataContract.CharacterTypeDataContract>();
query.ToList().ForEach(rec =>
{
CharacterTypeList.Add
(new whosInYourMinDataContract.CharacterTypeDataContract
{
Char_ID = rec.Char_ID,
Character_Type = rec.Char_Type
});
});
return CharacterTypeList;
}
public List<whosInYourMinDataContract.CharacterNameDataContract> getCharacterNames()
{
List<whosInYourMinDataContract.CharacterNameDataContract>
CharacterNameList =
new List<whosInYourMinDataContract.CharacterNameDataContract>();
try
{
var query = (from a in OME.Character_Name
select a).ToList().OrderBy(q => Int32.Parse(q.Char_Name_ID));
query.ToList().ForEach(rec =>
{
CharacterNameList.Add
(new whosInYourMinDataContract.CharacterNameDataContract
{
Char_Name_ID = rec.Char_Name_ID,
Char_ID = rec.Char_ID,
Char_Name = rec.Char_Name,
Char_Status = rec.Char_Status
});
});
return CharacterNameList;
}
catch (Exception ex)
{
throw new FaultException<string>
(ex.Message);
}
}
public List<whosInYourMinDataContract.questionAnswersDataContract>
questionAnswers(string Char_ID)
{
var query = (from A in OME.Questions
join B in OME.Character_Name on A.Char_Name_ID equals B.Char_Name_ID
where B.Char_ID.Equals(Char_ID)
select new
{
A.Question_ID,
A.Char_Name_ID,
B.Char_ID,
A.Question,
A.Answer,
B.Char_Name,
B.Char_Status
}).ToList().OrderBy(q => Int32.Parse(q.Question_ID));
List<whosInYourMinDataContract.questionAnswersDataContract> questionAnswersList =
new List<whosInYourMinDataContract.questionAnswersDataContract>();
query.ToList().ForEach(rec =>
{
questionAnswersList.Add
(new whosInYourMinDataContract.questionAnswersDataContract
{
Question_ID =rec.Question_ID,
Char_Name_ID = rec.Char_Name_ID,
Char_ID = rec.Char_ID,
Question = rec.Question,
Answer = rec.Answer,
Char_Name = rec.Char_Name,
Char_Status = rec.Char_Status
});
});
return questionAnswersList;
}
}
}
Web.Config
In WCF project, “Web.Config”:
- Change
<add binding="basicHttpsBinding" scheme="https" />
to <add binding="webHttpBinding" scheme="http" />
- Replace the
</behaviors>
to:
<endpointBehaviors>
<behavior>
<webHttp helpEnabled="True"/>
</behavior>
</endpointBehaviors>
</behaviors>
Run WCF Service: Now, we have created our WCF Rest service, let’s run and test our service. In our service URL, we can add our method name and we can see the JSON result data from database.
Create MVC Web Application
So now we have completed our WCF and now it’s time to create our MVC Angular JS application.
We can add new project to our existing project and create new MVC web Application as below.
Right click your Solution and click Add New Project -> Enter your project Name and click OK.
Select MVC and click OK.
Now we have created our MVC application and it’s time to add our WCF Service and install the Angular JS package to our solution.
Add WCF Service
Right click MVC Solution and click Add -> click Service Reference.
Enter your WCF URL and click GO. Here, my WCF URL is http://localhost:4194/Service1.svc.
Add your name and click OK.
Now we have successfully added our WCF Service to our MVC Application.
Steps to Install Angular JS package
Right click your MVC project and click -> Manage NuGet Packages.
<p<img src="/KB/Articles/893821/14.jpg">
Select Online and Search for Angular JS. Select the AngularJs and click Install.
Now we have Installed AngularJS package to our MVC Project. Now let’s create our Angular Js:
- Modules.js
- Controllers.js
- Services.js
Steps to Create Angular Js Script Files
Right click Script folder and create your own folder to create our Angular Js Model/Controller and Service JavaScript. In your script folder, add three JavaScript files and name as Modules.js, Controllers.js and Services.js as below:
Modules.js: Here, we add the reference to the Angular.js JavaScript and create a Angular Module named “RESTClientModule
”.
var app;
(function () {
app = angular.module("RESTClientModule", []);
})();
Services.js: Here, we add the reference to the Angular.js JavaScript and our Module.js.
Here, we give name to our service and we use this name in controllers.js. Here, for Angular service, I have given the name as "AngularJs_WCFService
". You can give your own name but careful about changing the name in Controllers.js. Here, we can see in method as I have passed the URL of our WCF Service URL.
app.service("AngularJs_WCFService", function ($http) {
this.GetCharacterType = function () {
return $http.get("http://localhost:4194/Service1.svc/GetCharacterType");
};
this.getCharacterNames = function () {
return $http.get("http://localhost:4194/Service1.svc/getCharacterNames/");
}
this.getquestionAnswers = function (Char_ID) {
return $http.get("http://localhost:4194/Service1.svc/questionAnswers/" + Char_ID);
}
});
Controllers.js: Here, we add the reference to the Angular.js JavaScript and our Module.js and Services.js. Same like Services for the controller, I have given the name as "AngularJs_WCFController
".
In Controller, I have performed all the business logic and return the data from WCF JSON data to our MVC HTML page.
1) Variable Declarations
First, I declared all the local Variables which need to be used and current date and store the date using $scope.date
.
Note: $scope.finalresultCount = 3;
This is a very important variable. Here, I have set the default value to 3. In my Quiz program, I have Insert 3 questions per Celebrity. If we increase the number of questions, then we need to give the same count here.
2) Methods
Hidetables()
This method is used to hide and show the display of Table TR
to show the Celebrity Profession selection and to answer the Question and to display the final result in same page.
getCharacterNames()
In this method, I will get all the Celebrity Names from the JSON and bind the result to the Main page. From there, user can think anyone celebrity in their mind and start the quiz game to play.
GetCharacterType()
In this method, I will get all the Celebrity Profession type from the JSON and bind the final result to the radio Button.
findYourAnswer()
In this method, get the question from database one by one and bind the question for users to answer.
$scope.findAnswers = function()
This method will be called when user click on the Submit button. In this method, I will do all the business logic as to display next questions and check for the final result and display the appropriate celebrity Name as Final result.
Controller.js Full Source Code
app.controller("AngularJs_WCFController",
function ($scope, $rootScope, $window, AngularJs_WCFService) {
$scope.date = new Date();
$scope.CharacterID = 4;
$scope.CharacterType = 'kollywood Actor';
var firstbool = true;
var secondbool = false;
var thirdbool = false;
$scope.Question_ID;
$scope.Char_Name_ID;
$scope.Char_ID;
$scope.Question;
$scope.Answer;
$scope.Char_Name;
$scope.Char_Status;
$scope.User_Selected_Result = 'Yes';
$scope.loopCount = 0;
$scope.resultCount = 0;
$scope.finalresultCount = 3;
$scope.NextStar = 0;
$scope.totalQuestionCount = 0;
$scope.QuestionIncrement = 0;
$scope.YourDreamStarName = "";
Hidetables()
function Hidetables() {
if ($scope.firstbool == false) {
$scope.firstbool = true;
$scope.secondbool = false;
$scope.thirdbool = true
}
else
{
$scope.firstbool = false;
$scope.secondbool = true;
$scope.thirdbool = true;
}
}
hideresult()
function hideresult() {
if ($scope.thirdbool == false) {
$scope.thirdbool = true;
}
}
GetCharacterType();
getCharacterNames();
function GetCharacterType() {
var promiseGet = AngularJs_WCFService.GetCharacterType();
promiseGet.then(function (pl) {
$scope.getCharacterTypeDisp = pl.data
},
function (errorPl) {
});
}
function getCharacterNames() {
var promiseGet = AngularJs_WCFService.getCharacterNames();
promiseGet.then(function (pl) {
$scope.getCharacterNamesDisp = pl.data;
},
function (errorPl) {
});
}
$scope.radioCheckValue = function (CharID, CharType) {
$scope.CharacterID = CharID;
$scope.CharacterType = CharType;
};
$scope.get = function () {
$scope.firstbool = true;
$scope.secondbool = false;
$scope.NextStar = 0;
$scope.loopCount = 0;
findYourAnswer();
}
function findYourAnswer()
{
var promiseGet = AngularJs_WCFService.getquestionAnswers($scope.CharacterID);
promiseGet.then(function (pl) {
$scope.questionAnswersDisp = pl.data
$scope.totalQuestionCount = $scope.questionAnswersDisp.length;
for (x in $scope.questionAnswersDisp) {
if (x == $scope.loopCount) {
$scope.Question_ID = $scope.questionAnswersDisp[x].Question_ID;
$scope.Char_Name_ID = $scope.questionAnswersDisp[x].Char_Name_ID;
$scope.Char_ID = $scope.questionAnswersDisp[x].Char_ID;
$scope.Question = $scope.questionAnswersDisp[x].Question;
$scope.Answer = $scope.questionAnswersDisp[x].Answer;
$scope.Char_Name = $scope.questionAnswersDisp[x].Char_Name;
$scope.Char_Status = $scope.questionAnswersDisp[x].Char_Status;
$scope.QuestionIncrement = $scope.QuestionIncrement + 1;
}
}
},
function (errorPl) {
});
}
$scope.rdoAnschk = function (chkResult) {
$scope.User_Selected_Result = chkResult;
};
$scope.findAnswers = function () {
if ($scope.User_Selected_Result == 'Yes')
{
$scope.resultCount = $scope.resultCount + 1;
}
else
{
if ($scope.Answer == 'No') {
$scope.resultCount = $scope.resultCount + 1;
if ($scope.NextStar > 0) {
$scope.NextStar = $scope.NextStar - 1;
}
}
else {
if ($scope.resultCount > 0) {
$scope.resultCount = $scope.resultCount - 1;
}
$scope.NextStar = $scope.NextStar + 1;
}
}
if ($scope.NextStar == $scope.finalresultCount)
{
alert('Hope my guess was Wrong! lets start for other Star ');
$scope.NextStar = 0;
}
if ($scope.resultCount == $scope.finalresultCount) {
$scope.secondbool = true;
$scope.thirdbool = false;
$scope.YourDreamStarName = $scope.Char_Name;
alert('Your Dream Star in your mind is ' + $scope.YourDreamStarName);
return;
}
$scope.loopCount = $scope.loopCount + 1;
findYourAnswer();
if($scope.QuestionIncrement>= $scope.totalQuestionCount)
{
$scope.secondbool = true;
$scope.thirdbool = false;
$scope.YourDreamStarName = "Sorry My Dear Friend.
All the Questions are Completed. I cont find your answer. Shall we try again";
alert($scope.YourDreamStarName);
return;
}
}
});
So now, we have created our AngularJs Module /Controller and Service. So what is next?
Create MVC Control and View to Display Our Result
Add Controller
Right click Controllers -> Add Controller -> select MVC 5 Controller – Empty ->click Add.
Change the Controller name and here, I have given the name as “WhosinYourMindController
” and click OK.
Add View: Right Click on Controller Index and Click Add View
1) Index View: Name the View as “Index”
In View Design your page and reference of angular.js, Modules.js, Services.js and Controllers.js.
In Angular JS, we use {{ }}
to bind or display the data.
Here, we can see first I create one table and for that table.
First in table, I have used the data-ng-controller="AngularJs_WCFController"
and here, we can see data-ng-controller
will be used to bound the data of controller to our HTML table.
Using <tbody data-ng-repeat=" detail in getCharacterNamesDisp">
, we can get all the records and using the <td><span>{{ detail.Char_Name}}</span></td>
, bind all the data inside the table.
<html data-ng-app="RESTClientModule">
@{
ViewBag.Title = "Who is in Your Mind Reader";
}
<body>
<img src="~/Images/blank.gif" alt=""
width="1" height="10" />
<table width="99%" style="
border-bottom:3px solid #3273d5;">
<tr>
<td width=" 250">
<table width="99%">
<tr>
<td>
Welcome Mr. {{'SHANU'}} .
</td>
</tr>
</table>
</td>
<td class="style1" align="center">
<h3>Who is in Your Mind Reader Quiz :)</h3>
</td>
<td align="right">
<div ng-controller="AngularJs_WCFController">
Today Date is :
{{date | date:'yyyy-MM-dd'}}
</div>
</td>
</tr>
</table>
<img src="~/Images/blank.gif" alt=""
width="1" height="10" />
<table id="tblContainer"
data-ng-controller="AngularJs_WCFController"
style='width: 99%;table-layout:fixed;'>
<tr>
<td>
<table style=" background-color:#ECF3F4; border: solid 2px #6D7B8D;
padding: 5px;width: 99%;table-layout:fixed;">
<tr>
<th style=" background-color:#98AFC7;
border-bottom: solid 4px #FFFFFF; padding: 5px;
width: 99%;table-layout:fixed;">
<h3>Think Any one of your Dream Star
in your mind from the list Below.</h3>
</th>
</tr>
<tbody data-ng-repeat="detail in getCharacterNamesDisp">
<tr>
<td style=" border: dashed 2px #6D7B8D;
padding: 5px;width: 99%;table-layout:fixed;">
<b> <span style="color:#9F000F">
{{detail.Char_Name}}</span></b>
</td>
</tr>
</table>
</td>
</tr>
</tr>
</table>
<img src="~/Images/blank.gif" alt=""
width="1" height="10" />
<table id="tblContainers"
style='width: 20%;table-layout:fixed;' align="center">
<tr>
<td align="center">
<table style=" background-color:#F0F8FF;color:#566D7E;
border: dashed 2px #6D7B8D; padding: 5px;width: 99%;table-layout:fixed;">
<tr>
<td align="center" style="color:#9F000F;">
<h3>@Html.ActionLink("Get Ready to Play!",
"CharacterTypeView", "WhosinYourMind")</h3>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/shanuAngularScript/Modules.js"></script>
<script src="~/Scripts/shanuAngularScript/Services.js"></script>
<script src="~/Scripts/shanuAngularScript/Controllers.js"></script>
2) CharacterTypeView View
Add another view name as “CharacterTypeView
”.
This is our main View. Here, I will display the Celebrity Profession type and user can select any one Celebrity profession which they have think in mind from the index page list. User can start to play the game. Answer all the questions and find the result finally.
<html data-ng-app="RESTClientModule">
@{
ViewBag.Title = "Select Your Character Profession";
}
<body>
<img src="~/Images/blank.gif" alt=""
width="1" height="10" />
<table width="99%"
style=" border-bottom:3px solid #3273d5;">
<tr>
<td width=" 250">
<table width="99%">
<tr>
<td>
Welcome Mr. {{'SHANU'}} .
</td>
</tr>
</table>
</td>
<td class="style1" align="center">
<h3>Who is in Your Mind Reader Quiz :)</h3>
</td>
<td align="right">
<div ng-controller="AngularJs_WCFController">
Today Date is :
{{date | date:'yyyy-MM-dd'}}
</div>
</td>
</tr>
</table>
<img src="~/Images/blank.gif" alt=""
width="1" height="10" />
<table width="100%"
data-ng-controller="AngularJs_WCFController">
<tr ng-hide="firstbool" ng-init="Hidetables()">
<td>
<table id="tblContainer"
style='width: 99%;table-layout:fixed;'>
<tr>
<td>
<table style=" background-color:#ECF3F4;
border: solid 2px #6D7B8D; padding: 5px;
width: 99%;table-layout:fixed;">
<tr>
<th style=" background-color:#98AFC7;
border-bottom: solid 4px #FFFFFF; padding: 5px;
width: 99%;table-layout:fixed;">
<h3>Select Your Character Profession
which you have think in your mind.</h3>
</th>
</tr>
<tbody data-ng-repeat="detail in getCharacterTypeDisp">
<tr>
<td style=" border: dashed 2px #6D7B8D; padding: 5px;
width: 99%;table-layout:fixed;">
<b>
<input type="radio"
name="rdoCharType"
ng-model="detail.Character_Type"
value="detail.Character_Type"
ng-value="detail.Character_Type"
ng-click="radioCheckValue
(detail.Char_ID,detail.Character_Type)" />
<span style="color:#9F000F">
{{detail.Character_Type}}</span>
</b>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<img src="~/Images/blank.gif" alt=""
width="1" height="10" />
<table id="tblContainers"
style='width: 60%;table-layout:fixed;' align="center">
<tr>
<td align="center">
<table style=" background-color:#F0F8FF;color:#566D7E;
border: dashed 2px #6D7B8D; padding: 5px;
width: 99%;table-layout:fixed;">
<tr>
<td align="center"
style="color:#566d7e;">
You have selected <div>
<h3 style="color:#9F000F">
{{CharacterType}}
</h3></div> as you have think in mind.
Now its time to read your mind
lets start now.<br />
<h4> Time to Begin :)"</h4>
<input type="button" id="Detail"
value="lets Start" data-ng-click="get()"
style="background-color:#2B547E;
color:#FFFFFF;width:100px;height:30px">
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
<tr ng-hide="secondbool" ng-init="Hidetables()">
<td>
<table>
<tr>
<td>
<table id="tblContainer"
style='width: 100%;table-layout:fixed;'>
<tr>
<td align="right">
<table id="tblContainers"
style='width: 20%;table-layout:fixed;'
align="right">
<tr>
<td align="center">
<table style="
background-color:#F0F8FF;color:#566D7E;
border: dashed 2px #6D7B8D; padding: 5px;
width: 99%;table-layout:fixed;">
<tr>
<td align="center"
style="color:#566d7e;">
<div>You have selected
<h4 style="color:#9F000F">
{{CharacterType}}
</h4></div>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table style=" background-color:#ECF3F4;
border: solid 2px #6D7B8D;
padding: 5px;width: 100%;table-layout:fixed;">
<tr>
<th style=" background-color:#98AFC7;
border-bottom: solid 4px #FFFFFF;
padding: 5px;width: 99%;
table-layout:fixed;">
<h3>Answer Yes or No
to the below Questions,
this will help me to read your
mind Star !.</h3>
</th>
</tr>
<tr>
<td style=" border: dashed 2px #6D7B8D;
padding: 5px;width: 99%;table-layout:fixed;">
<b>
{{Question}}
</b>
<br />
<input type="radio" name="rdoAns"
value="Yes"
ng-click="rdoAnschk('Yes')"
checked='checked' />YES
<input type="radio" name="rdoAns"
value="No"
ng-click="rdoAnschk('No')" />No
</td>
</tr>
</table>
</td>
</tr>
</table>
<tr>
<td>
<img src="~/Images/blank.gif" alt=""
width="1" height="10" />
</td>
</tr>
<tr>
<td align="center">
<table style=" background-color:#F0F8FF;color:#566D7E;
border: dashed 2px #6D7B8D;
padding: 5px;width: 14%;table-layout:fixed;">
<tr>
<td align="center"
style="color:#566d7e;">
<input type="button" id="Detail"
value="Submit"
data-ng-click="findAnswers()"
style="background-color:#2B547E;
color:#FFFFFF;width:100px;height:30px">
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
<tr ng-hide="thirdbool" ng-init="hideresult()">
<td>
<table>
<tr>
<td align="center">
<table style=" background-color:#F0F8FF;color:#566D7E;
border: dashed 2px #6D7B8D; padding: 5px;
width: 99%;table-layout:fixed;">
<tr>
<td align="center" style="color:#566d7e;">
<div> I hope so this is your Star
<h3 style="color:#9F000F">
{{YourDreamStarName}}
</h3> whom you think in your Mind. </div>
<h3 style="color:#566D7E;">@Html.ActionLink
("Shall we play again :)", "Index",
"WhosinYourMind")</h3>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/shanuAngularScript/Modules.js"></script>
<script src="~/Scripts/shanuAngularScript/Services.js"></script>
<script src="~/Scripts/shanuAngularScript/Controllers.js"></script>
Run Your Program
Here, we can see that when I run the program, first, I display the celebrity.
After clicking the Get ready to play link, it will be redirected to next page.
Here, user can select any one Character profession as they have thought in their mind and clicks on Let's Start.
Here, user can answer to the question as Yes or No and click submits to check the next question.
Note: Here in my application, I have set maximum 3 questions for a Celebrity. User can increase the number of questions as per your requirement in database and in Controller.js, give the question count as same as in database in “$scope.finalresultCount = 3;
”
The final result will be displayed like this:
Points of Interest
Note: Here all the Celebrity Name, Celebrity Profession, Questions and Answers all have been displayed from the database. There is no static data in my application. So user can add your own celebrity Name, Profession and Question to the Db and have fun.
Supported Browsers: Chrome and Firefox
History
- 6th April, 2015: Initial version