I am developing web application in .NET as two separate applications, back end using webapi c# and user interface using AngularJS. I just want to add Chat option in this project. I have installed SignalR and added ChatHub.cs class in webapi.
enter image description here
in WebAPI there is a class named Startup.cs
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local;
WebApiConfig.Register(config);
app.UseCors(CorsOptions.AllowAll);
ConfigureAuth(app);
app.UseWebApi(config);
app.MapSignalR();//added after installation of SignalR package
}
}
ChatHub class
public class ChatHub : Hub
{
public static string emailIDLoaded = "";
public void Connect(string userName, string email)
{
emailIDLoaded = email;
var id = Context.ConnectionId;
using (SmartCampEntities dc = new SmartCampEntities())
{
var userdetails = new ChatUserDetail
{
ConnectionId = id,
UserName = userName,
EmailID = email
};
dc.ChatUserDetails.Add(userdetails);
dc.SaveChanges();
}
}
}
Whatever request i send from user interface it will hit to its corresponding controller in webAPI. For example
$http({
method: 'GET',
url: $scope.appPath + "DashboardNew/staffSummary" //[RoutePrefix]/[Route]
}).success(function (result, status) {
data = result;
});
My user interface is a separate application. How can i connect signalR from UI.
I tried something but didn't get it work. Can anyone suggest me how to get it work
html code
<div>
<a class="btn btn-blue" ng-click="sendTask()">SendTask</a>
javascript
angular.module('WebUI').controller('DashboardCtrl', function ($scope, $window, $http, $modal, ngTableParams) {
$scope.header = "Chat";
$scope.sendTask = function () {
$http({
method: 'POST',
url: $scope.appPath + hubConnetion.server.sendTask("userName","email"),
})
}
});
Basics:
That you can connect to your signalr server you have to include the client code to your page. It's also important that you include jquery before.
At least you can also include the generate hubs file in the case you are working with hubs:
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script src="Scripts/jquery.signalR-2.1.0.min.js"></script>
<script src="signalr/hubs"></script>
Basic Sample:
Here you have a full sample (without and with generated hub proxy):
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div class="container">
<div class="row">
<!-- Title -->
<h1>SignalR Sample</h1>
</div>
<div class="row">
<!-- Input /Button-->
<input type="text" id="inputMsg" />
<button button="btn btn-default" id="btnSend">Send</button>
</div>
<div class="row">
<!-- Message list-->
<ul id="msgList"></ul>
</div>
</div>
<script src="Scripts/jquery-1.6.4.js"></script>
<script src="Scripts/jquery.signalR-2.2.0.js"></script>
<script src="http://[LOCATIONOF YOUR HUB]/signalr/hubs"></script>
<script>
// ------------------- Generated Proxy ----------------------------
$(function () {
$.connection.hub.url = "[LOCATION WHERE YOUR SERVICE IS RUNNING]/signalr";
var chat = $.connection.myChat;
chat.client.addMessage = function (name, message) {
$('#msgList').append('<li><strong>' + name
+ '</strong>: ' + message + '</li>');
};
$.connection.hub.start({}).done(function () {
$('#btnSend').click(function () {
chat.server.Send("Stephan", $('#inputMsg').val());
$('#inputMsg').val('').focus();
});
})
});
//// ------------------- Without Proxy ----------------------------
//$(function () {
// var connection = $.hubConnection("http://localhost:8080/signalr");
// var chatHubProxy = connection.createHubProxy('chatHub');
// chatHubProxy.on('AddMessage', function (name, message) {
// console.log(name + ' ' + message);
// $('#msgList').append('<li><strong>' + name
// + '</strong>: ' + message + '</li>');
// });
// connection.start().done(function () {
// $('#btnSend').click(function () {
// chatHubProxy.invoke('send', "Stephan", $('#inputMsg').val());
// $('#inputMsg').val('').focus();
// });
// });
//});
</script>
</body>
</html>
For more details see:
http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client
SignalR Angular Module:
There is also a "helper module" which you can use in angularjs for working with signalr:
https://github.com/JustMaier/angular-signalr-hub
I can able to connect webapi by adding below code into my Startup.Auth.cs
public void ConfigureAuth(IAppBuilder app)
{
app.UseOAuthBearerTokens(OAuthOptions);
//by adding below code
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR(new HubConfiguration { EnableJSONP = true });
}
Related
I am learning Angular JS. I am trying to create a mock portal that displays Daily Messages. I have stored my daily messages in a database table.
create table DailyMsg(Sno int primary key, msg varchar(max));
Then I created a service using factory in AngularJS.
public class DailyMsgsController : Controller
{
private amenEntities1 db = new amenEntities1();
// GET: DailyMsgs
public ActionResult Index()
{
return Json(db.DailyMsgs.ToList(),JsonRequestBehavior.AllowGet);
}
}
I tested the URL and it works fine, it returns the expected data in the JSON format
https://localhost:44329/DailyMsgs
Now, I wanted to display this data on my HomePage. But it doesn't work. On inspecting the page it shows me the error
Error: $http:badreq
Bad Request Configuration
Http request configuration url must be a string or a $sce trusted object. Received: undefined
My Controller
var myApp = angular.module('myApp', []);
//Daily Messages Service Function
myApp.factory('DailyMsgService', function ($http) {
DailyMsgObj = {};
DailyMsgObj.DisplayDailyMsg = function () {
var Msg;
Msg = $http({method: 'GET', URL: '/DailyMsgs/Index'}).
then(function (response){
return response.data;
});
return Msg;
}
return DailyMsgObj;
});
myApp.controller('HomePageController', function ($scope, DailyMsgService) {
DailyMsgService.DisplayDailyMsg().then(function (result) {
$scope.DailyMsg = result;
});
});
My HomePage
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div ng-controller="HomePageController">
{{DailyMsg}}
</div>
</body>
</html>
<script src="../Scripts/angular.min.js"></script>
<script src="../Scripts/bootstrap.min.js"></script>
<link href="../Content/bootstrap.min.css" rel="stylesheet" />
<script src="../AngularControllers/HomePageController.js"></script>
I'm working on a website where the client has asked for an option to allow signup/login using Google and Facebook accounts. How can I extract the email address from a user's Google profile for storing in database?
Here is my code. The problem is that I am not getting the user profile completely. Instead, I am receiving just user name.
try
{
WebClient client = new WebClient();
var urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token="
+ access_token;
string outputData = client.DownloadString(urlProfile);
GoogleUserOutputData serStatus =
JsonConvert.DeserializeObject<GoogleUserOutputData>(outputData);
if (serStatus != null)
{
return serStatus;
// You will get the user information here.
}
}
catch (Exception ex)
{
//catching the exception
}
return null;
Here is a way to receive data (email, etc.) in JavaScript. At the end it shows an alert with data. (You can store this data in a database.) It's a complete working example with a Google button.
<html>
<head>
<title>Demo: Getting an email address using the Google+ Sign-in button</title>
<!-- Include the API client and Google+ client. -->
<script src = "https://plus.google.com/js/client:platform.js" async defer></script>
</head>
<body>
<!-- Container with the Sign-In button. -->
<div id="gConnect" class="button">
<button class="g-signin"
data-scope="email"
data-clientid="Your_Client_ID"
data-callback="onSignInCallback"
data-theme="dark"
data-cookiepolicy="single_host_origin">
</button>
<!-- Textarea for outputting data -->
<div id="response" class="hide">
<textarea id="responseContainer" style="width:100%; height:150px"></textarea>
</div>
</div>
</body>
<script>
/**
* Handler for the signin callback triggered after the user selects an account.
*/
function onSignInCallback(resp) {
gapi.client.load('plus', 'v1', apiClientLoaded);
}
/**
* Sets up an API call after the Google API client loads.
*/
function apiClientLoaded() {
gapi.client.plus.people.get({userId: 'me'}).execute(handleEmailResponse);
}
/**
* Response callback for when the API client receives a response.
*
* #param resp The API response object with the user email and profile information.
*/
function handleEmailResponse(resp) {
var primaryEmail;
var name;
var gender;
for (var i=0; i < resp.emails.length; i++) {
if (resp.emails[i].type === 'account')
primaryEmail = resp.emails[i].value;
if (resp.displayName != null)
name = resp.displayName;
gender = resp.gender;
}
document.getElementById('responseContainer').value = 'Primary email: ' +
primaryEmail + '\n\nFull Response:\n' + JSON.stringify(resp);
ShowAlert("Email: "+primaryEmail +" "+"Name: "+ resp.displayName +" "+"Gender: "+gender);
}
</script>
</html>
For further information and detail you can (should) read this link:
Getting people and profile information
Documentation is the key; please check it completely.
https://developers.google.com/identity/sign-in/web/sign-in
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
<div class="g-signin2" data-onsuccess="onSignIn"></div>
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
}
Sign out
<script>
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
</script>
I am trying to create an API using a local server for testing. The ROUTES are working and I can add data to the OBJ using the URL from the browser. The issue is when I try to 'POST' the data through the HTML. I am getting back a 404 error. I developing using node.js and Express. What am I doing wrong?
JS on the server side
app.get('/add/:word/:score?', addWord);
//Function to request and send back the data
function addWord(request, response) {
var data = request.params;
var word = data.word;
var score = Number(data.score);
var reply;
if (!score) {
var reply = {
msg: 'Score is required'
}
response.send(reply);
} else {
words[word] = score;
// Transforms javascript object into raw data correctly idented with null, 2
var data = JSON.stringify(words, null, 2);
fs.writeFile('words.json', data, finished);
function finished(err) {
console.log('Writting');
var reply = {
word: word,
score: score,
status: 'Success'
}
response.send(reply);
}
}
}
POST method JS
$('#submit').on('click', function submitWord() {
var word = $('#fieldWord').val();
var score = $('#fieldScore').val();
$.ajax({
type: 'POST',
url: '/add/' + word + "/" + score,
success: function (newOrder) {
$list.append('<li>name: ' + newOrder.word + newOrder.score + '</li>');
},
error: function (err) {
console.log('Error saving order', err);
}
});
});
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tutorial API with node.js</title>
<script type="text/javascript" src ="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<p>
Word: <input type="text" id="fieldWord"><br/>
Score:<input type="text" id="fieldScore"><br/>
<button type="button" id ="submit">Submit</button>
<ul id="list">
</ul>
</p>
</body>
<script type="text/javascript" src="sketch.js"></script>
</html>
Thank you in advance.
I'm trying to call JavaScript in a JavaFx WebView from Java, but I get:
Exception in thread "JavaFX Application Thread" netscape.javascript.JSException: TypeError: undefined is not a function
at com.sun.webkit.dom.JSObject.fwkMakeException(JSObject.java:128)
at com.sun.webkit.WebPage.twkExecuteScript(Native Method)
at com.sun.webkit.WebPage.executeScript(WebPage.java:1439)
at javafx.scene.web.WebEngine.executeScript(WebEngine.java:982)
.java file
private WebView emailSubject() {
String pageURL = "D:myproject\\src\\resources\\WEB_INF\\forms\\readMail\\emailBody.html";
pageURL = pageURL.replace("\\", "/");
webView = new WebView();
webView.setMaxHeight(52);
webEngine = webView.getEngine();
emailSubject = getHTMLMailSubject();
webEngine.getLoadWorker().stateProperty().addListener((ov, oldState, newState) -> {
if (newState == State.SUCCEEDED) {
webEngine.executeScript("testCheckMate(\"" + emailSubject + "\");");
}
});
webEngine.load("file:" + pageURL);
return webView;
}
Exception which points to this line:
webEngine.executeScript("testCheckMate(\"" + emailSubject + "\");");
The HTML:
<!-- Latest compiled and minified JavaScript -->
<script src="../../baseJS/JQuery/jquery-1.11.3.js"></script>
<script src="../../baseJS/JQuery/jquery.min.js"></script>
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Home Alone</h3>
</div>
</div>
<script>
$(document).ready(function() {
window.testCheckMate = function (data) {
$(".panel-title" ).append(data);
};
});
</script>
What am I doing wrong? Thank you all in advance.
Please note that I've tried:
load(); already
$(".panel-title" ).load(data);
as well as with
testCheckMate outside $(document).ready(function(), but still nothing.
testCheckMate = function (data) {
$(".panel-title" ).load(data);
};
I'm trying to use websockets into my ASP.NET MVC web-app but I can't implement, so here I'm trying to display each database update on the end-user web-page without any need to refresh.
HTML:
<span id="nbAlertes"></span>
<ul id="listeAlertes"></ul>
Javascript / SignalR / jQuery
<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-2.0.2.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="signalr/hubs"></script>
<script>
$(function () {
// Declare a proxy to reference the hub.
var alertes = $.connection.AlerteHub;
// Create a function that the hub can call to broadcast messages.
alertes.client.broadcastMessage = function (nbAlertes, listeAlertes) {
// Html encode display name and message.
var nbA = $('<div />').text(nbAlertes).html();
var lstA = $('<div />').text(listeAlertes).html();
// Add the message to the page.
$('#nbAlertes').text(nbA);
lstA.forEach(function(item) {
$('#listeAlerte').append(item.nomPoste);
});
};
});
</script>
class AlerteHub:
public class AlerteHub : Hub
{
public void GetAll()
{
var nbAlertes = new CalculAlertesUtilitaire().compter();
var listeAlertes = new CalculAlertesUtilitaire().lister(5);
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(nbAlertes, listeAlertes);
}
MonitoringNDataContext _db = new MonitoringNDataContext();
public string compter()
{
var compte = _db.Alertes.ToList().Count();
return (compte == 0) ? "" : compte.ToString();
}
public ICollection<AlerteModel> lister(int nb)
{
return (ICollection<AlerteModel>)_db.Alertes.ToList().Take(nb).ToArray();
}
}
class Startup
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Any connection or hub wire up and configuration should go here
app.MapSignalR();
}
}
How do I to make it work, please ?
If you want to use SignalR, you need to establish the connection on the client. In JavaScript you do this by calling connection.start(). For example:
<!--Reference the SignalR library. -->
<script src="/Scripts/jquery.signalR-2.0.2.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>
<script>
$(function () {
// Declare a proxy to reference the hub.
var alertes = $.connection.alerteHub;
// Create a function that the hub can call to broadcast messages.
alertes.client.broadcastMessage = function (nbAlertes, listeAlertes) {
// Html encode display name and message.
var nbA = $('<div />').text(nbAlertes).html();
var lstA = $('<div />').text(listeAlertes).html();
// Add the message to the page.
$('#nbAlertes').text(nbA);
lstA.forEach(function(item) {
$('#listeAlerte').append(item.nomPoste);
});
};
$.connection.hub.start().done(function () {
// You should probably be calling GetAll from somewhere.
// I'm not sure if you should call it as soon as you connect,
// but you certainly can't call GetAll before connecting.
alertes.server.getAll();
}).fail(function (error) {
alert("Failed to connect!");
});
});
</script>
You can learn more about how to use the Signalr JS client here: http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-javascript-client