Implementing WebSockets using SignalR - javascript

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

Related

Pusher: How to get private channel subscription count in pusher?

What I want: How can i get subscription count after subscription of a private channel in pusher.Actually i want private chat between only 2 users.
What I Know and Doing: . I know that i private channel can be subscribed by multiple clients(users).So whenever server trigger the data to private channel then all subscribed user get that response.
Channel subscription code in java script (Client-1):
<!DOCTYPE html>
<head>
<title>Pusher Test</title>
<script src="https://js.pusher.com/3.2/pusher.min.js"></script>
<script>
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;
var pusher = new Pusher('PUSHER_KEY', {
authEndpoint: 'http://localhost:8080/medecube/rest/initial/pusher/auth',
auth: {
headers: {
'X-CSRF-Token': "12345"
}
}
});
var channel = pusher.subscribe('private-channel');
channel.bind('pusher:subscription_succeeded', function() {
var triggered = channel.trigger('client-myEvent', { "message": "i am pusher client1" });
});
</script>
</head>
Same channel subscribed by client 2
Channel subscription code in java script (Client-2):
<!DOCTYPE html>
<head>
<title>Pusher Test</title>
<script src="https://js.pusher.com/3.2/pusher.min.js"></script>
<script>
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;
var pusher = new Pusher('PUSHER_KEY', {
authEndpoint: 'http://localhost:8080/medecube/rest/initial/pusher/auth',
auth: {
headers: {
'X-CSRF-Token': "12345"
}
}
});
var channel = pusher.subscribe('private-channel');
channel.bind('pusher:subscription_succeeded', function() {
var triggered = channel.trigger('client-myEvent', { "message": "i am pusher client2" });
});
</script>
</head>
Event Trigger by server:
Pusher : Event recd : {"event":"client-myEvent","data":{"message":"i am pusher client2"},"channel":"private-channel"}
Then both client get same response. I want only one user subscribe only 1 channel.
It is possible to get subscription count for private channels, you don't have to use a presence channel. However, to get subscription count for a private channel you have to explicitly enable that feature via your Pusher dashboard as it's not enabled by default:
https://pusher.com/docs/rest_api#method-get-channel
You need to use presence channels to get information about the members in a channel. In your case you could get the count of subscribers with var count = presenceChannel.members.count;.

How to connect signalR from angularJs

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 });
}

Receiving Messages From Websocket Scala

I'm trying to configure a WebSocket in Scala. I have a function that broadcasts a bunch of JSON to a WebSocket. It works when I configure it through http://www.websocket.org/echo.html (inputting my own ws://localhost:9000/web-socket), but I need it to display the information on a new webpage.
To that effect I made a new webpage called client which is defined in my controllers as
def client = Action {
val data = new RedshiftData() // get the data
Ok(views.html.client(data))
}
In my views I have client.scala.html defined as (adapted from websockets.org)
#import datadump.RedshiftData
#(data: RedshiftData)
<!DOCTYPE html>
<html>
<script>
var wsUri = "ws://localhost:9000/web-socket";
var ws = new WebSocket(wsUri);
#data.pushToWebSocket
ws.onmessage = function (evt) {
var msg = JSON.parse(evt.data);
console.log(msg);
};
</script>
<body>
</body>
</html>
But, it never receives my message that I'm sending. How do I get it to listen to the message that I send out in the controller?

TypeError:Cannot read property hub of undefined

I am getting the exception when run on signalr javascript client..
TypeError:Cannot read property hub of undefined
Please help me to solve this exception.. Thank you..
My Javascript file is...
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="Scripts/jquery-1.6.4.min.js"></script>
<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-2.1.0.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="http://localhost:8080/signalr/hubs"></script>
<!--Add script to update the page and send messages.-->
<script type="text/javascript">
$(function () {
try
{
alert("inside function");
//Set the hubs URL for the connection
$.connection.hub.url = "http://localhost:8080/signalr";
// Declare a proxy to reference the hub.
var chat = $.connection.myHub;
alert(chat);
// Create a function that the hub can call to broadcast messages.
// Start the connection.
$.connection.hub.start().done(function () {
alert("Connection succeeded");
}).fail(function () {
alert("Connection failed");
});
}
catch (err) {
alert("Error:" + err);
}
});
</script>

How do I get email address field using the LinkedIn Javascript API?

I'm using the LinkedIn Javascript API to sign in users to my application, however the API is not returning the email address even though I'm requiring permission for that specific field. I'm including the API script as follows:
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: API_KEY
scope: r_fullprofile r_emailaddress
</script>
then I'm including the Log In button in the markup:
<script type="in/Login" data-onAuth="onLinkedInAuth">
and finally I have a function to add the callback for the API response:
function onLinkedInAuth() {
var fields = ['first-name', 'last-name', 'email-address'];
IN.API.Profile("me").fields(fields).result(function(data) {
console.log(data);
}).error(function(data) {
console.log(data);
});
};
I'm only getting the First and Last Name but the API doesn't return the email field.
Reference: https://developer.linkedin.com/documents/profile-fields#email
1- be sure you made email permission (r_emailaddress) in your app http://developer.linkedin.com/documents/authentication#granting
2- then you may use this
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: key
**onLoad: onLinkedInLoad**
authorize: true
</script>
<script>
function onLinkedInLoad() {
IN.Event.on(IN, "auth", onLinkedInAuth);
}
// 2. Runs when the viewer has authenticated
function onLinkedInAuth() {
IN.API.Profile("me").fields("first-name", "last-name", "email-address").result(function (data) {
console.log(data);
}).error(function (data) {
console.log(data);
});
}
</script>
hope this will help you :)
thanks
Hello there #Ulises Figueroa,
May be I am coming in a bit late but this is how I had got this done:
Start off with the initial script tag on the top of your page within the head section:
<script>
Client Id Number here:
onLoad: onLinkedInLoad
authorize: true
</script>
Then, in your JS File,(I had placed an external JS File to process this API sign up/ Auth), have the following details placed:
function onLinkedInLoad() {
IN.Event.on(IN, "auth", getProfileData);
}
function onSuccess(data) {
console.log(data);
}
function onError(error) {
console.log(error);
}
function getProfileData(){
IN.API.Profile("me").fields(["firstName","lastName", "email-address", "positions"]).result(function(data) {
var profileData = data.values[0];
var profileFName = profileData.firstName;
var profileLName = profileData.lastName;
if(data.values[0].positions._total == "0" || data.values[0].positions._total == 0 || data.values[0].positions._total == undefined) {
console.log("Error on position details");
var profileCName = "Details Are Undefined";
}
else {
var profileCName = profileData.positions.values["0"].company.name;
}
var profileEName = profileData.emailAddress;
//console.log all the variables which have the data that
//has been captured through the sign up auth process and
//you should get them...
});
}
Then last but not the least, add the following in your HTML DOCUMENT which can help you initiate the window popup for the linkedin auth sign up form:
<script type="in/Login"></script>
The above setup had worked for me. Sure this will help you out.
Cheers and have a nice day.
Implementation looks good. I'd believe this is a result from the profile's privacy settings. Per linked-in's docs:
Not all fields are available for all profiles. The fields available depend on the relationship between the user you are making a request on behalf of and the member, the information that member has chosen to provide, and their privacy settings. You should not assume that anything other than id is returned for a given member.
I figured out that this only happens with certain LinkedIn accounts, so this might be caused because some privacy setting with the email. I couldn't find any reference to the documentation so I had to consider the case when email field is not available.

Categories