Click here to Skip to main content
15,879,326 members
Articles / Web Development / HTML

Group Messaging for Samsung Gear using MVC, Web API and AngularJS

Rate me:
Please Sign up or sign in to vote.
3.53/5 (7 votes)
14 Oct 2015CPOL14 min read 26.4K   296   14   4
Send Group Message from web server to Samsung Gear Smartwatches
In this article, we see how to send Group Message from a web server to Samsung Gear Smartwatches.

Image 1

Introduction

What is Gear Group Messaging (GGM) System for Samsung Gear Smartwatch?

In this article, we see how to send Group Message from web server to Samsung Gear Smartwatches. The main aim of this Group Message System for Samsung Gear Smartwatch is to send fast and important message to groups from the web server. We have Email, Smartphone messaging system, then why do we need the group messages to Smartwatch. The answer to this question is very simple. Now let’s consider the CEO of a company wants to meet all the Project Managers of a company in 10 minutes. The CEO can send an email to all the managers and also send Text message to Smartphones. It’s not sure all the Project Managers can see the mail and also all Project managers can see the smartphone messages as they might not be at their desk or in a meeting or at a cafeteria. In this case, there will be a possibility of not seeing the messages sent by the CEO. Now we consider that all the Project Managers are wearing Samsung Gear Smartwatch. The CEO can send message from web site as “4 Pm Meeting”. After the CEO posts the new message, the message will be displayed immediately on everyone’s Samsung gear Smartwatch. This group message System is not only for a company, but this Group Messaging system can be used for family, friends, etc.

The main advantage will be anyone can post the message within office Group. Only one message can be posted. Everytime the new message will be updated with an old image.

From the above GIF Image, we can see that from my MVC web application using AngularJS and Web API I will be updating the message to the database and the updated result will get back from the database using Web API get method. In my Samsung Gear app, I have used the AngularJS controller to get the result of WEB API and bind the result message in Samsung Gear. We will see in detail how to create an application.

Shanu Gear Group Messaging (GGM) Architecture

Image 2

Here, we can see my GGM Architecture in detail. The Group message can be viewed in both Samsung Gear as well as in GGM Website.

Image 3

Note: If you are new to Samsung Gear App development using TIZEN IDE, then kindly view my previous article which explains in detail about how to Install Tizen SDK and create your first hello world program using Tizen IDE.

In this article, we will see in detail how to:

  1. Create Group Message Web Server using MVC, AngularJS and Web API 2. This application will be used to post Messages to group from website.
  2. Create Simple Samsung Gear App to display Date and Current Time using Angular JS.
  3. Create Samsung Gear App with AngularJS to display the current message from WEB API.

1) Prerequisites Need to Install for Developing Samsung Gear App

To start developing our first App for Samsung Gear, we need the following software to be installed:

  1. Tizen SDK (http://developer.samsung.com/gear/)

    (Tizen consists of set of tools for Developing Tizen web and native applications. It contains IDE for developing our applications and Emulator to view our outputs.)

  2. SDK Image (http://developer.samsung.com/gear/)
  3. Visual Studio 2015 - you can download it from here.

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:

Using the Code

  1. Create Group Message Web Server using MVC, AngularJS and Web API
  2. This application will be used to post Messages to group from website.

1. Create Database and Table

We will create a MessageDetails table under the Database ‘MessageDB’.

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.

SQL
-- =============================================                                
-- Author      : Shanu                                
-- Create date : 2015-10-01                                   
-- Description : To Create Database,Table and Sample Insert Query                             
-- Latest                                
-- Modifier    : Shanu                                 
-- Modify date : 2015-10-01                            
-- ============================================= 
--Script to create DB,Table and sample Insert data 

USE MASTER 
GO 

-- 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] = 'MessageDB' ) 
DROP DATABASE MessageDB 
GO 

CREATE DATABASE MessageDB 
GO 

USE MessageDB 
GO   

-- 1) //////////// StudentMasters 

IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'MessageDetails' ) 
DROP TABLE MessageDetails 
GO 

CREATE TABLE [dbo].[MessageDetail]( 
       [msgID] INT IDENTITY PRIMARY KEY, 
       [grpMessage] [varchar](500) NOT NULL,
        [msgDate]  datetime
)

   Select * from MessageDetail
   -- 1) Stored procedure to Select Student Details

-- Author      : Shanu                                                               
-- Create date :  2015-10-01                                                           
-- Description : MessageDetail                                           
-- Tables used :  MessageDetail                                                              
-- Modifier    : Shanu                                                               
-- Modify date :  2015-10-01                                                              
-- =============================================  
-- exec USP_Message_Select
-- =============================================
Create PROCEDURE [dbo].[USP_Message_Select] 
AS                                                               
BEGIN      
         Select Top 1 grpMessage,msgDate
            FROM
                MessageDetail         
END

 -- 2) Stored procedure to insert/Update MessageDetail

-- Author      : Shanu                                                               
-- Create date :  2015-10-02                                                           
-- Description : MessageDetail                                           
-- Tables used :  MessageDetail
-- Modifier    : Shanu
-- Modify date :  2015-10-02
-- =============================================  
-- exec USP_Message_Insert 'se'
-- =============================================
CREATE PROCEDURE [dbo].[USP_Message_Insert]
   (                      
     @grpMessage           VARCHAR(100)     = ''  
      )                                                     
AS                                                               
BEGIN       
IF NOT EXISTS (SELECT * FROM MessageDetail )
            BEGIN
                   INSERT INTO MessageDetail
                    ([grpMessage],msgDate)
                    VALUES (@grpMessage,GETDATE())
            
                    Select 'Inserted' as results
            END
         ELSE
             BEGIN
                     UPDATE MessageDetail
                             SET grpMessage  = @grpMessage     ,
                                 msgDate     = GETDATE()         
                     Select 'Updated' as results
              END     
END

In this script, I have created two stored procedures, one is to select the current message from database and another procedure to Insert the New Message for the first time and update the new message if the record is found.

2. Create Our MVC Web Application in Visual Studio 2015

After installing our Visual Studio 2015, click Start -> Programs-> select Visual Studio 2015 - Click Visual Studio 2015.

Click New -> Project - > Select Web -> ASP.NET Web Application. Select your project location and enter your web application Name.

Image 4

Select MVC and in Add Folders and Core reference. Select the Web API and click OK.

Image 5

Add Database using ADO.NET Entity Data Model

Right click our project and click Add -> New Item.

Image 6

Select Data ->Select ADO.NET Entity Data Model > Give the name for our EF and click Add.

Image 7

Select EF Designer from database and click Next.

Image 8

Here, click New Connection and provide your SQL-Server Server Name and connect to your database.

Image 9

Select the database as MessageDB as we have created the database using my SQL Script.

Image 10

Click Next and select our tables that need to be used and click Finish.

Image 11

Click Next and select our tables and Stored Proicedure that are needed and click Finish.

Image 12

Here, we can see now we have created our MessageModel.

Image 13

Once Entity has been created, in the next step, we add WEB API to our controller and write function to select/Insert/Update and Delete.

Steps to Add Our WEB API Controller

Right click Controllers folder-> click Add-> click Controller.

Image 14

As we are going to create our WEB API Controller. Select Controller and Add Empty WEB API 2 Controller. Give your Name to Web API controller and click OK. Here for my Web API Controller, I have given name as “MessagesController”.

Image 15

As we have created Web API controller, we can see our controller has been inherited ApiController.

As we all know, Web API is a simple and easy to build HTTP Services for Browsers and Mobiles.

Web API has 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.

In our example, we will use Get method, since we need to get all the Puzzle Question details from database.

Get Method

In our example, I have used only Get method as I am using to select data from database to display the Word Puzzle game. We need to create object for our Entity and write our Get Method to perform Select operations.

Select Operation

We use get method to get all the details of MessageDetail from stored procedure USP_Message_Select_Result using entity object and we return the result as IEnumerable.

Here, we can see in get method, I have used the USP_Message_Select to get the result.

We use this method in our AngularJS and display the result in MVC HTML page.

C#
public class MessagesController : ApiController
    {
               MessageDBEntities objAPI = new MessageDBEntities();
               // to get message from database
               [HttpGet]
               public IEnumerable<USP_Message_Select_Result> Get()
               {             
                      return objAPI.USP_Message_Select().AsEnumerable();
               }
}

Insert/Update Operation

To Insert and Update, I will pass the user posted message as parameter to the procedure and display back the result to MVC page from AngularJS controller.

C#
//to Update Student Details
               [HttpGet]
               public IEnumerable<string> messageinsert(string grpMessage)
               {
                      if (grpMessage == null)
                              grpMessage = "";
                      return objAPI.USP_Message_Insert(grpMessage).AsEnumerable();
               }

Creating AngularJs Controller

First, create a folder inside the Script folder and I give the folder name as “MyAngular”.

Image 16

Now add your Angular Controller inside the folder.

Right click the MyAngular folder and click Add -> New Item -> select Web -> select AngularJs Controller and give name to Controller. I have given my AngularJs Controller as “Controller.js”.

Once the AngularJs Controller is created, we can see by default the controller will have the code with 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.

Image 17

Steps to Create AngularJs Script Files

Modules.js: Here, we add the reference to the Angular.js JavaScript and create an Angular Module named “RESTClientModule”.

JavaScript
/// <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("RESTClientModule", ['ngAnimate']);
})();

Controllers: In Angular JS Controller, I have performed all the business logic and return the data from WEB API to our MVC HTML page.

1) Variable Declarations

First, I declared all the local Variable which needs to be used. For each variable, I have added the comments.

JavaScript
 app.controller("AngularJs_ImageController",
                 function ($scope, $timeout, $rootScope, $window, $http) {
//Global Variables
$scope.date = new Date();
   $scope.MyName = "shanu";
   $scope.grpMessage = "";
   $scope.grpMessageAdd = "";

2) Select Group Message Function

To display the latest message from database using $http.get, I will get the result and bind to the MVC page using $scope.grpMessage variable.

JavaScript
selectMessageDetails();
    function selectMessageDetails() {
        $http.get('/api/Messages/').success(function (data) {
            $scope.Message = data;
            if ($scope.Message.length > 0) {
                $scope.grpMessage = $scope.Message[0].grpMessage
            }
        })
   .error(function () {
       $scope.error = "An Error has occurred while loading posts!";
   });
    }

Here we can see in New Group Message, “4 PM Meeting” is the final message which was updated to the database.

Image 18

3) Insert/Update Group Message Function

In this method, I will be posting the user entered Message to API and insert/update to the database using Stored procedure.

JavaScript
//Save Message

    $scope.saveDetails = function () {
        $scope.messageDetails = $scope.grpMessageAdd;
        if ($scope.grpMessageAdd = "")
        {
            alert("Enter Message");
            return;
        }
        $http.get('/api/Messages/messageinsert/', 
                 { params: { grpMessage: $scope.messageDetails } }).success(function (data) {
            $scope.StudentsInserted = data;
            alert($scope.StudentsInserted);
            selectMessageDetails();
        })
      .error(function () {
          $scope.error = "An Error has occurred while loading posts!";
      });
    }

We can see the GIF image. Here, we update the text and after the data is updated to database, the result will be updated in New Group Message.

1034901/G4.gif

2. Create Simple Samsung Gear App to display Date and Current Time using Angular JS.

Image 20

Note: If you are new to Samsung Gear App development using TIZEN IDE, then kindly view my previous article which explains in detail about how to Install Tizen SDK and create your first hello world program using Tizen IDE.

Click -> Start programs -> click Tizen IDE.

For the first time, it will ask to select your Workspace. You can browse and select folder to create all your project under the folder. Click OK to start your new project.

Image 21

Once you are done, click on File -> New -> Tizen Web project.

Image 22

Creating our First Wearable UI Template: We can see a window like below. First, we start with Wearable UI Template. Select the Template and Wearable UI and click on Basic. Give name for your project and click Finish.

Image 23

Once you have created, you can see your Project on the left side of Project Explorer. Create new Folder inside your newly created project for adding all the AngularJS reference files. I have created the folder name as “MyAngular”. I have copied all AngularJS and JQuery related reference files to this folder and also created new JavaScript file as “controller.js” for AngularJS controller creation.

Image 24

In the Controller.JS JavaScript file, we will create for AngularJS Model and Controller like below.

In this JS file, first I create AngularJS Module and then Controller.

In controller, I have declared all the variables that need to be used as date to display the current date and time, Myname to display my name from controller to html page.

I have used the timer to run every second and call the function “CounterFunction” for every second. In this function, I update the current time and display the current time in HTML page.

JavaScript
/// <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("RESTClientModule", ['ngAnimate']);
})();

app.controller("AngularJs_Controller", 
function ($scope, $timeout, $rootScope, $window, $http) {

    //Global Variables
    $scope.date = new Date();
    $scope.MyName = "Shanu";
    $scope.counterval = 0;
   
    $scope.CounterFunction = function(){
        $timeout(function() {
          $scope.getTime();
          $scope.CounterFunction();
        }, 1000)
      };
      $scope.getTime = function(){
          $scope.counterval= $scope.counterval+1;
          $scope.date = new Date();
      }

      // Kick off the interval
      $scope.CounterFunction();
});

Now we have created AngularJS controller next part as we all know that. In Tizen Samsung Gear project, we have created a web project and we can find the index.html in project explorer. Now in this HTML page, we bind the result of controller variable to display the result.

We add all the AngularJS reference at the bottom of HTML page. In HTML tag, we add the data-ng-app and in body tag, we add the data-ng-controller. Next, we bind the name from AngularJS to our page using {{ MyName }}. Same like this, we bind the Current Date and time.

HTML
<!DOCTYPE html>
<html data-ng-app="RESTClientModule">
<head>
       <meta name="viewport" 
       content="width=device-width,user-scalable=no">
       <title>Gear & AngulrJS</title>
       <link rel="stylesheet" 
       href="lib/tau/wearable/theme/default/tau.min.css">
       <link rel="stylesheet" 
       media="all and (-tizen-geometric-shape: circle)" 
        href="lib/tau/wearable/theme/default/tau.circle.min.css">
       <!-- load theme file for your application -->
       <link rel="stylesheet" href="css/style.css">
</head>
<body data-ng-controller="AngularJs_Controller">
       <div class="ui-page ui-page-active" id="main">
             <header class="ui-header">
                    <h2 class="ui-title">Gear & AngulrJS</h2>
             </header>
             <div class="ui-content content-padding">
                    <ul class="ui-listview">
                           <p>{{ MyName }} </p>
                            <p>  {{date | date:'yyyy-MM-dd'}}</p>  
                              <p>  {{date | date:'hh:mm:ss a'}}</p> 
                    </ul>
             </div>
       </div>
       <script type="text/javascript" 
       src="lib/tau/wearable/js/tau.min.js"></script>
       <script type="text/javascript" 
       src="js/circle-helper.js"></script>
       <script src="app.js"></script>
       <script src="lowBatteryCheck.js"></script>     
<script src="MyAngular/angular.js"></script>
<script src="MyAngular/angular-animate.js"></script>
<script src="MyAngular/controller.js"></script>
</body>
</html>

When we run this project in simulator, we can see the result as:

Image 25

Output with Emulator:

Image 26

3. Create Samsung Gear App with AngularJS to Display the Current Message from WEB API

This is our main Samsung Gear App which is to display the newly updated message to be displayed in Samsung Gear. I will be using Timer and every 1 second, I call the method to display the updated Group Message from WEB API using AngularJS controller.

Click -> Start programs -> Click Tizen IDE.

For the first time, it will ask to select your Workspace. You can browse and select folder to create all your project under the folder. Click OK to start your new project.

Image 27

Once you have done click on File-> New -> Tizen Web project.

Image 28

Creating our First Wearable UI Template: We can see a window like below. First, we start with Wearable UI Template. Select the Template and Wearable UI and click on Basic. Give name for your project and click Finish.

Image 29

Once you have created, you can see your Project on the left side of Project Explorer. Create new folder inside your newly created project for adding all the AngularJS reference files. I have created the folder name as “MyAngular”. I have copied all AngularJS and JQuery related reference files to this folder and also created new JavaScript file as “controller.js” for AngularJS controller creation.

Image 30

In the Controller.JS JavaScript file, we will create for AngularJS Model and Controller like below.

In this JS file, first I create AngularJS Module and then Controller.

In controller, I have declared all the variables that need to be used as date to display the current date and time, Myname to display my name from controller to HTML page AND Messages TO DISPLAY THE MESSAGE FROM API RESULT.

I have used the timer to run every second and call the function “getMessages” for every second. In this function, I will update the MESSAGE which I receive from MVC Web API.

JavaScript
/// <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("RESTClientModule", ['ngAnimate']);
})();

app.controller("AngularJs_Controller", 
    function ($scope, $timeout, $rootScope, $window, $http) {
    //Global Variables
    $scope.date = new Date();
    $scope.MyName = "Shanu";
    $scope.Messages = "";
  
    $scope.CounterFunction = function(){
        $timeout(function() {
          $scope.getMessages();
          $scope.CounterFunction();
        }, 1000)
      };
      $scope.getMessages = function(){        

          $http.get('http://localhost/shanuMVCTEST/api/Messages/').success(function (data) {
                             $scope.AllMessages = data;
              if ($scope.AllMessages.length > 0) { 
                  $scope.Messages=$scope.AllMessages[0].grpMessage;
              }
          })
          .error(function () {
              $scope.error = "An Error has occurred while loading posts!";
          });
      }    

      $scope.CounterFunction();
});

Now we have created AngularJS controller next part as we all know that. In Tizen Samsung Gear project, we have created a web project and we can find the index.html in project explorer. Now in this HTML page, we bind the result of controller variable to display the result.

We add all the AngularJS reference at the bottom of the HTML page.

In HTML tag, we add the data-ng-app and in body tag, we add the data-ng-controller.

Next, we bind the message from AngularJS to our page using {{ Messages }}.

Same like this, we bind the Current Date and time.

HTML
<!DOCTYPE html>
<html data-ng-app="RESTClientModule">
<head>
       <meta name="viewport" content="width=device-width,user-scalable=no">
       <title>Circular UI</title>
       <link rel="stylesheet" href="lib/tau/wearable/theme/default/tau.min.css">
       <link rel="stylesheet" media="all and (-tizen-geometric-shape: circle)" 
        href="lib/tau/wearable/theme/default/tau.circle.min.css">
       <!-- load theme file for your application -->
       <link rel="stylesheet" href="css/style.css">
</head>
<body data-ng-controller="AngularJs_Controller">
       <div class="ui-page ui-page-active" id="main">
             <header class="ui-header">
                    <h2 class="ui-title">
                    <span style="color:#fffff;font-size:x-large">
                     Shanu Message Service</span></h2>
             </header>
             <div class="ui-content content-padding">
                    <ul class="ui-listview">
             <img src="shanu.jpg" /> 
             <span style="color:#af2609;font-size:large">Message:</span>
                             <br> <span style="color:#FFFFFF;font-size:x-large">
                               {{ Messages }}
                               </span>
                    </ul>
             </div>
       </div>
       <script type="text/javascript" src="lib/tau/wearable/js/tau.min.js"></script>
       <script type="text/javascript" src="js/circle-helper.js"></script>
       <script src="app.js"></script>
       <script src="lowBatteryCheck.js"></script>
       <script src="MyAngular/angular.js"></script>
<script src="MyAngular/angular-animate.js"></script>
<script src="MyAngular/controller.js"></script>
</body>
</html>

When we run this project in simulator, we can see the result as displaying the current message as “4 PM Meeting”.

Image 31

Note to run this in Emulator, we need to perform the following settings in config.xml file to allow the internet in your emulator from your Tizen Project.

Config.XML – Double click the Config.xml file and open to do the following changes:

Image 32

Add this below setting in:

Features & privileges for the App:

Features Tab

In Features tab, click Add and then select the http://tizen.org/feature/network.internet.

Image 33

Privileges Tab

In Privileges tab, click Add and then select the http://tizen.org/privilege/internet.

Image 34

Policy Tab

In Policy Tab, click Add and then add * for any website and Allow Subdomain to true. Same like this, you can add to localhost as well.

Image 35

I try to run the application but it was not displaying the localhost web API result in emulator. All the settings are looking fine but still it’s not displaying the result in emulator and working fine for Simulator and in Preview.

For testing with live internet web API result, I check with this API http://api.geonames.org/cities?north=44.1&south=-9.9&east=-22.4&west=55.2&username=demo/.

This internet API result works fine in my emulator, here is my sample controller to get the result from this sample live API and bind the length in message box:

JavaScript
function GetOrderMasters() {   
        alert("1");        
          $http.get('http://api.geonames.org/cities?north=44.1&
          south=-9.9&east=-22.4&west=55.2&username=demo/').success(function (data) {
                alert("2");  
               $scope.jsonResult = data;
              alert("API result Count " + $scope.jsonResult.length);
 if ($scope.jsonResult.length > 0) {    
              }           
          })
          .error(function () {
              $scope.error = "An Error has occurred while loading posts!";
          });
    }

Here, we can see in Samsung gear Emulator, we can see the API result total count.

Image 36

Points of Interest

Hope you like this and now you might be having a clearer idea to start working with Samsung gear App development for Smartwatch and have fun. This article is for the Contest. You can extend this project as per your requirement as for now I have used only one message to be updated and displayed. You can extend to more messages and also group Type for sending messages to individual groups.

In zip file, you can find:

  1. shanuAngularJSwebAPIMessageWebServer.sln for MVC web application. (In web config, change as per your DB Server setting.)
  2. shanuGearAngularJs folder which contains source code for Samsung Gear App with AngularJS sample to display Date and Time.
  3. samsungGearAngularMessageSystem folder which contains source code for Samsung gear app to display the message from WEB API using AngularJS.

History

  • 1st October, 2015: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

Comments and Discussions

 
GeneralMy vote of 5 Pin
Santhakumar M30-Sep-15 23:19
professionalSanthakumar M30-Sep-15 23:19 
GeneralRe: My vote of 5 Pin
syed shanu30-Sep-15 23:22
mvasyed shanu30-Sep-15 23:22 
GeneralNice Article Pin
aarif moh shaikh30-Sep-15 22:30
professionalaarif moh shaikh30-Sep-15 22:30 
GeneralRe: Nice Article Pin
syed shanu30-Sep-15 23:22
mvasyed shanu30-Sep-15 23:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.