My angularclient is able to invoke the serverhub. But never receive push messages from the server, send with this line:
hub.Clients.All.serverTime(DateTime.UtcNow.ToString());
For debug purposes I've added console.log(...) in the subscription (signalrhubproxy.js):
proxy.on(eventName, function (result) {
console.log('event:' + eventName + ' received.' ); <--- never fired
$rootScope.$apply(function () {
if (callback) {
callback(result);
}
});
});
I've followed this tutorial Pushing Data: Integrating with ASP.NET SignalR Hubs wih a few
modifications in my app:
it has a WebAPI structure with a startup.cs, with this SignalR configuration:
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
EnableDetailedErrors = true,
EnableJSONP = true
};
map.RunSignalR(hubConfiguration);
});
instead of this in the global.asax:
RouteTable.Routes.MapHubs(new HubConfiguration
{ EnableCrossDomain = true });
AreaRegistration.RegisterAllAreas();
The WebAPI runs on localhost:2034 (VS)
The Client runs on localhost:9000 (grunt)
I'm able to:
- invoke the servermethod getServerTime from the client.
- run the BackgroundServerTimeTimer
- get the hub in the BackgroundServerTimeTimer with:
hub = GlobalHost.ConnectionManager.GetHubContext<ClientPushHub>();
and notifies the clients with:
hub.Clients.All.serverTime(DateTime.UtcNow.ToString()); <--- no error serverside, no glory clientside
Is it my box?
- My box runs on Windows 7 and has VS 2013
UPDATE
I've implemented the simple 'Getting started chatsample' without changes in the server config. And that's working. So, it's clear that it's a clientside problem in my angularjs.
app.js has a value: .value('signalRServer', 'http://localhost:2032/')
The example from the website creates hubproxies like this, without usage of the .value:
function ServerTimeController($scope, signalRHubProxy) {
var clientPushHubProxy = signalRHubProxy(
signalRHubProxy.defaultServer, 'clientPushHub', <--- signalRHubProxy.defaultServer should be: signalRServer
{ logging: true });
var serverTimeHubProxy = signalRHubProxy(
signalRHubProxy.defaultServer, 'serverTimeHub'); <--- signalRHubProxy.defaultServer should be: signalRServer
clientPushHubProxy.on('serverTime', function (data) {
$scope.currentServerTime = data;
var x = clientPushHubProxy.connection.id;
});
$scope.getServerTime = function () {
serverTimeHubProxy.invoke('getServerTime', function (data) {
$scope.currentServerTimeManually = data;
});
};
};
For completeness, the right way:
angular.module('yourApp').controller('yourCtrl', function ($scope, signalRHubProxy, signalRServer ) {
var clientPushHubProxy = signalRHubProxy(
signalRServer, 'clientPushHub',
{ logging: true });
var serverTimeHubProxy = signalRHubProxy(
signalRServer, 'serverTimeHub',
{ logging: true });
clientPushHubProxy.on('serverTime', function (data) {
$scope.currentServerTime = data;
//jshint unused:false
var x = clientPushHubProxy.connection.id;
console.log('Client pushhubproxy id: ' + x );
});
.....
The real problem: I was digging around with different signalR versions and a old version of the example.
Here is the version for SignalR 2 located: signalr angular example
Related
I have problems in my web console, first it gives me error 415 without contentType: 'application/json; charset=UTF-8', in ajax method and with it gives me error 400.
I also try doing debug if the error is in backend code but it never happens and it jumps off (this don't make any sense, the debugger should run...)
My goal is to return a list of users and their email, something like this
//trying to do this in my service
IEnumerable()
//class c#
ShowUsers:
(string)Username: User1
(string)Email:user1#example.com
But I'm doing this in gRPC, so I'll have a web API controller calling the gRPC method
As there is no IEnumerable in gRPC, so my proto and method look like this:
Proto:
syntax = "proto3";
option csharp_namespace = "GrpcService1.Protos";
package UserAuth;
service UserAuth {
rpc GetAllUsers(MessageRequest) returns(ListUsersResponse);
}
message ListUserResponse{
string username = 1;
string email = 2;
}
message ListUsersResponse{
repeated ListUserResponse lstUsers = 1;
}
message MessageRequest{
string message = 1;
}
gRPC method service c#
public override Task<ListUsersResponse> GetAllUsers(MessageRequest request, ServerCallContext context)
{
//This gives me an IEnumerable<ShowUsers> (this is
correct)
var a = _userBll.getAllUsers();
//Here in this lines maybe be the problem but I don't
//know where (maybe be because of json type or something into a list)
//here im trying to put separate list of users and emails
var names = a.Select(x => x.Username);
var emails = a.Select(y => y.Email);
//here im trying to put the lists into a Response
var all = new ListUserResponse
{
Username = names.ToString(),
Email = emails.ToString()
};
//the above will give the same but the
ListUsersResponse is a repeated attribute
var response = new ListUsersResponse
{
LstUsers = { all }
};
//all ok
request.Message = "Sucess";
return Task.FromResult(response);
}
The code below is correct (I test with a POST method the controller and the ajax I test without the gRPC and works fine) but you will have the idea of what I'm doing (its the controller and the ajax method)
Controller [HTTPGET]:
[HttpGet("getAllUserInfo_2"), Authorize]
public async Task<ActionResult<ListUsersResponse>> GetAll_2([FromBody] MessageRequest message)
{
_logger.Log(LogLevel.Information, "Request Received for AuthController::Register");
var results = await _userClient.GetAllUsersAsync(message);
_logger.Log(LogLevel.Information, "Sending Response from AuthController::Register");
return Ok(results);
}
Ajax Method:
$(function b() {
debugger;
var $users_A = $('#users_A');
$.ajax({
contentType: 'application/json; charset=UTF-8', //if I comment this gives me 415
url: uri_3_2,
type: 'GET',
dataType: 'json',
beforeSend: function(request) {
request.setRequestHeader("Authorization", 'Bearer ' + localStorage.getItem("key"));
},
success: function(date) {
$.each(data, function (i, rice) {
$users_A.append('<li>Name: ' + arroz.username + ' Email: ' + arroz.email + ' </li>');
});
},
error: function (xhr, textStatus, errorThrown) {
console.log('XHR:' + xhr + '\nTextStatus:' + textStatus + '\nErrorThrown:' + errorThrown); //this should give me more info about the error but don't works... But it
//works fine the implementation code
$users_A.append('<h4>ERRRROORRRR</h4>');
}
});
});
Any help is welcome
A bi-directional streaming RPC would be a better option as it will
improve your performance significantly and may solve your problem.
you need to change your proto as the following:
syntax = "proto3";
option csharp_namespace = "GrpcService1.Protos";
package UserAuth;
service UserAuth {
rpc GetAllUsers(MessageRequest) returns(stream UserResponse);
}
message UserResponse{
string username = 1;
string email = 2;
}
message MessageRequest{
string message = 1;
}
gRPC method service c#
public override async Task GetAllUsers(MessageRequest request, IServerStreamWriter<UserResponse> responseStream, ServerCallContext context)
{
var users = _userBll.getAllUsers();
foreach (user in users)
{
await responseStream.WriteAsync(new UserResponse
{
Username = user.Username.ToString(),
Email = user.Email.ToString()
});
}
}
in client:
public async Task<List<UserResponse> GetAllUsers()
{
var userResponseList = new List<UserResponse>();
using var call = client.GetAllUsers(new MessageRequest());
while (await call.ResponseStream.MoveNext())
{
var userResponse = new UserResponse
{
Username = call.ResponseStream.Current.Username,
Email = call.ResponseStream.Current.Email
});
userResponseList.Add(userResponse);
}
return userResponseList;
}
the client object has come from the channel which is created from the gRPC service URL (I assume you know it).
Now you can make this a service and call it by dependency injection from your controller.
I didn't test it so it may have some compile errors but the approach is correct.
Below is my code from view from my ASP.NET MVC project. I am using datatable to create a table. I am fetching data from a Web API. Data is being returned but while binding I get the error shown here. I tried deleting a lot of code which had buttons. Now I just have code for simply binding it.
datatables warning: table id=patients - ajax error. for more information about this error, please see http://datatables.net/tn/7
jQuery code :
$(document).ready(function () {
debugger;
var table = $("#patients").DataTable({
ajax: {
url: "/api/patients",
dataSrc: ""
},
columns: [
{
data: "First_Name"
},
{
data: "phoneNumber",
render: function (data) {
debugger;
return data.toString().replace(
/(\d\d\d)(\d\d\d)(\d\d\d\d)/g, '$1-$2-$3');
}
},
{
data: "Address"
},
]
});
});
API code from controller:
public IHttpActionResult GetPatients()
{
var patientDto = getdata();
return Ok(patientDto);
}
public IEnumerable<Patient_Response> getdata()
{
IEnumerable<Patient_Response> students = null;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer 0f6af107-6ad2-4665-ad24-f09402d50082");
client.BaseAddress = new Uri("http://localhost:6600/api/");
// HTTP GET
var responseTask = client.GetAsync("patients");
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<IList<Patient_Response>>();
readTask.Wait();
students = readTask.Result;
}
else //web api sent error response
{
// log response status here..
students = Enumerable.Empty<Patient_Response>();
ModelState.AddModelError(string.Empty, "Server error. Please contact administrator.");
}
}
return students;
}
What is wrong? I am not able to figure out.
Did you read the documentation: https://datatables.net/manual/tech-notes/7
This occurs when jQuery falls into its error callback handler (this callback built into DataTables), which will typically occur when the server responds with anything other than a 2xx HTTP status code.
That means that your call go the controller, failed to bring any data.
You can use the following code to see what went wrong:
$.fn.dataTable.ext.errMode = 'none';
$('#patients')
.on( 'error.dt', function ( e, settings, techNote, message ) {
alert( 'An error has been reported by DataTables: ', message );
} )
.DataTable();
I am creating a web app in mvc-5 with the help of angularjs i created 10-12 pages and there are lots of insert/update/delete commands there and till now everything was working fine but today when i tried to update trainer name from select(html) one extra line is being added automatically
<select ng-model="mdupdpm" ng-options="a.empname as a.empname for a in gettrainername" ng-change="zoneupd(z)" style="width:270px;"></select>
and my angularjs controller
$scope.getupdateparams = function (param) {
$('#update').modal({
show: true,
backdrop: 'static'
});
$scope.updtparam = param;
console.log($scope.data.mdupm);
$http.get('/companyregistration.asmx/updateempname', {
params: {
empname: $scope.updtparam.pm
}
}).then(function (response) {
$scope.gettrainername = response.data.info;
console.log(response.data.info);
})
}
i don't know why this is not working because i did this in my previous pages and all of that worked well I am giving one example of worked code from my previous page
<select ng-model="ucomname" ng-options="o.comname as o.comname for o in comnamelistfun" ng-change="uucomname(o)" style="width:270px;"></select>
now my controller
$scope.updatefunction = function (param) {
$scope.updateparam = param;
//comnamebyid
$scope.updmodal = true;
$http.get('/csuv.asmx/getcompanyname', {
params: {
log: log,
pm: pm,
id: $scope.updateparam.Id
}
})
.then(function (response) {
{
$scope.updmodal = false;
$scope.comnamelistfun = response.data.cdetails;
}
$scope.ucomname = $scope.comnamelistfun[0].comname;
});
what is wrong guys??
I used mqtt code with nodeJs which runs in console.
But I want to use this nodeJs Mqtt code in c# MVC.
How can I achieve it?
My NodeJs Code as follows,
Server.js
var mqtt = require('mqtt');
var sys = require("sys");
var stdin = process.openStdin();
var client = mqtt.connect('http://broker.mqttdashboard.com');
client.on('connect', function () {
console.log("Chat Application");
stdin.addListener("data", function(d) {
client.publish('presence',d.toString());
});
client.subscribe('msg');
client.on('message', function (topic, message) {
console.log('User2:',message.toString());
});
});
Client.js
var mqtt = require('mqtt');
var client = mqtt.connect('http://broker.mqttdashboard.com');
var sys = require("sys");
var stdin = process.openStdin();
client.on('connect', function () {
console.log("Chat Application");
client.subscribe('presence');
});
client.on('message', function (topic, message) {
console.log('User1:',message.toString());
});
stdin.addListener("data", function(d) {
client.publish('msg',d.toString());
});
please give some example code for using nodejs in c# MVC.
I Got a solution for this but i want to clarify that this code uses NodeJs or it is a Native c# Code?
<script>
var client = new Messaging.Client("broker.mqttdashboard.com", 8000, "myclientid_" + parseInt(Math.random() * 100, 10));
client.onConnectionLost = function (responseObject) {
alert("connection lost: " + responseObject.errorMessage);
};
client.onMessageArrived = function (message) {
$('ol').append('<li> ' + $("#TUserName").val() + ' : ' + message.payloadString + '</li><br/>');
};
var options = {
timeout: 3,
onSuccess: function () {
client.subscribe("MQTT/Message", { qos: 2 });
alert("Connected");
},
onFailure: function (message) {
alert("Connection failed: " + message.errorMessage);
}
};
var publish = function (payload, topic, qos, retained) {
var message = new Messaging.Message(payload);
message.destinationName = topic;
message.qos = qos;
message.retained = retained;
client.send(message);
}
$(document).ready(function () {
client.connect(options);
$("#btn").click(function () {
publish($('#test').val(),"MQTT/Message", 2, true);
$("ol").append("<li> You : " + $("#test").val() + "</li>");
});
</Script>
It works good.
but i want to know is this code uses NodeJs or Not?
Please let me Know.
You never directly use node in your client side application. But yes, the functionalities can be accessed by making AJAX or XHR requests to the connection endpoints specified in your node application.
Example
To access MongoDb database in your javascript application, you specify some urls or endpoints in your node application which further invokes the callback function. These callback functions contain your code to connect to a mongo database.
From the client side, you make an AJAX request to the specified url along with the required data. The callback then does the CRUD operations and returns respective result back.
P.S. What you wrote in your answer in C# file inside the <script> tag is pure javascript. Nothing like Node.Js in it.
Hello i'm new to angularjs and i'm creating an Angularjs application with visualstudio 2012 mvc4 and i need some help with a request.
this is my get method
// GET: /getCard/
Logic l = new Logic();
public List<Cards> Index()
{
var cards = ml.getSortedDeck();
return cards;
}
here is my js code
MemoryApp.factory('Cards', function($resource){
return $resource('/getCard/', { method: 'GET', isArray: true });
});
var ColourCtrl = function ($scope, Cards, $routeParams, $resource) {
$scope.cards = [];
$scope.setcards = function () {
Cards.query(function (data) {
console.log(data);
$scope.cards = $scope.cards.concat(data);
});
}
$scope.setcards();
}
when i stepped through my backend code it worked fine, i got 16 hits back in the "cards" list which is the right amount. Though when i check my console.log on the website i have an array with 59 items that are unuseable to me.
When i check the response section in under the network tab i get this message
"System.Collections.Generic.List`1[Memory.Models.Cards]" and that seems right to me.
best regards /M
Return JSON.
public JsonResult Index()
{
var cards = ml.getSortedDeck();
return Json(cards, JsonRequestBehavior.AllowGet);
}