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.
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.
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
I'm a serious MVC & SignalR newbie!
I found this tutorial online that shows how to use Database Change notifications and display the data in an MVC app. The issue I'm having is replicating the MVC side of things. I've managed I think to work through the tutorial correctly and spin up the application, however, I'm getting an Undefined connection and the app bombs out.
Does anyone know where I might find the associated source files for this example, or has anyone managed to successfully implement this and can shed some light on the configuration of this from an MVC point of view.
Thanks!
To display real time updates from the SQL Server by using SignalR and SQL Dependency I've done these steps:
Step 1: Enable Service Broker on the database
The following is the query that need to enable the service broker
ALTER DATABASE BlogDemos SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE ;
Step 2: Enable SQL Dependency
//Start SqlDependency with application initialization
SqlDependency.Start(connString);
Step 3: Create the hub Class
public class MessagesHub : Hub
{
private static string conString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
public void Hello()
{
Clients.All.hello();
}
[HubMethodName("sendMessages")]
public static void SendMessages()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessagesHub>();
context.Clients.All.updateMessages();
}
}
Step 4: Get the Data from the Repository
Create MessagesRepository to get the messages from the database when data is updated.
public class MessagesRepository
{
readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
public IEnumerable<Messages> GetAllMessages()
{
var messages = new List<Messages>();
using (var connection = new SqlConnection(_connString))
{
connection.Open();
using (var command = new SqlCommand(#"SELECT [MessageID], [Message], [EmptyMessage], [Date] FROM [dbo].[Messages]", connection))
{
command.Notification = null;
var dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
messages.Add(item: new Messages { MessageID = (int)reader["MessageID"], Message = (string)reader["Message"], EmptyMessage = reader["EmptyMessage"] != DBNull.Value ? (string) reader["EmptyMessage"] : "", MessageDate = Convert.ToDateTime(reader["Date"]) });
}
}
}
return messages;
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
MessagesHub.SendMessages();
}
}
}
Step 5: Register SignalR at startup class
app.MapSignalR();
Step 6: then use the method to show real time at your view
<script src="/Scripts/jquery.signalR-2.1.1.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var notifications = $.connection.messagesHub;
//debugger;
// Create a function that the hub can call to broadcast messages.
notifications.client.updateMessages = function () {
getAllMessages()
};
// Start the connection.
$.connection.hub.start().done(function () {
alert("connection started")
getAllMessages();
}).fail(function (e) {
alert(e);
});
});
function getAllMessages()
{
var tbl = $('#messagesTable');
$.ajax({
url: '/home/GetMessages',
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html'
}).success(function (result) {
tbl.empty().append(result);
}).error(function () {
});
}
</script>
Hope this helps :)
You should provide your code, it's easier to figure out what the problem is that way.
From what you have mentioned, I can think of only two things.
1) The tutorial you used, it's using SignalR 1.0. If you are using SignalR 2.0, you should not follow the tutorial exactly.
A few things changed in SignalR 2.0, you can read about it using below link:
http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/upgrading-signalr-1x-projects-to-20
2) If you are using SignalR 1.0, make sure you include the "jquery" file correctly, and if it's correct, try to change the hub proxy path like below:
<script src="/signalr/Hubs"></script>
Hope it helps
I have created a web service in C# and now need to call it from a mobile app. I'm trying to create a Windows 7 mobile app, but using HTML5 and Javascript not the native code. The web service takes 2 parameters, Email and Password, and returns a Dataset. I don't really have any javascript experience (or web services experience for that matter, trying to learn with this project), and when trying to research how to call a web service using javascript I just found too much information and didn't know where to begin because so many other technologies were also mentioned.
So I decided to try things out and this is what I came up with so far:
<script type="text/javascript">
document.addEventListener("deviceready", onDeviceReady, false);
// once the device ready event fires, you can safely do your thing! -jm
function onDeviceReady() {
}
function LoginButton_onclick() {
UpdateChildrenApp.PhoneWebServices.GetMyChildren(document.getElementById('EmailBox').value,document.getElementById('PasswordBox').value, OnComplete, OnError)
}
function OnComplete(result) {
for (var i = 0; i < result.tables[0].rows.length; i++)
document.getElementById('Test').innerHTML += ''+(result.tables[0].rows[i].col_name);
}
function OnError(result) {
document.getElementById('Test').innerHTML ='Error :'+result.get_message();
}
</script>
This code does nothing when I press the submit button. Could someone please point out what the problems are and how I can fix them or suggest what I should research to address the problems and put me on the right track? Any help is greatly appreciated.
First, your webservices should return a JSON object if you want to use it in javascript.
You can of course return any XML/string, but using JSON will be A LOT easy to use the data in javascript.
Then, I would advise you to use jquery to call the webservice, as jquery will do a lot of work for you.
Read this article, it should help you set different components correctly:
I would use jQuery to do this kind of thing.
The ajax functionality its provides is really easy to use.
I would use the Revealing Module Pattern (RMP) and 2 javascript files. If you're unfamiliar with the RMP, there is a great post covering it here:
http://weblogs.asp.net/dwahlin/archive/2011/08/02/techniques-strategies-and-patterns-for-structuring-javascript-code-revealing-module-pattern.aspx
I find that if I dont employ some kind of structure to my js code using the RMP, I just end up with a mess of functions in one file.
Id have Startup.js and Dataservice.js and they would look something like this:
Startup.js
var Startup = function () {
var isValid,
dataObject = {},
populateDataObject = function () {
dataObject.dealer = $("[id$='_txtUser']").val();
dataObject.password = $("[id$='_txtPassword']").val();
},
init = function () {
var dealerId = 0;
$("[id$='_SubmitButton']").bind('click', function (evt) {
evt.preventDefault();
populateDataObject();
if (isValid) {
Dataservice.processLoginRequest(dataObject, processLoginRequestResult);
}
});
};
return {
init: init,
processLoginRequestResult: processLoginRequestResult
};
} ();
Dataservice.js (assumes old school .asmx, change as needed)
var Dataservice = function () {
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
var serviceBase = '../services/LoginService.asmx/',
processScreenRequest = function (valObject, callback) {
$.ajax({
url: serviceBase + "ProcessLoginRequest",
data: JSON.stringify(valObject),
success: function (json) {
callback(json);
}
});
};
return {
processScreenRequest: processScreenRequest
};
} ();
and then I would include refereces to these 2 js files as well as jquery in my html page.
I hope this helps.
I've used Dojo for this once, its pretty simple you can make xhrget or xhrpost requests. It has a function called load that is the callback where you can modify the contents of the HTML components in the page.
Use these links : http://dojotoolkit.org/reference-guide/1.7/dojo/xhrGet.html
I am lazy loading snippets of html on our page in order to improve performance. jQuery's load method does not provide access to the full ajax api (things like error callbacks) so I created a more robust version of it.
I am calling this method 3-5 times per page on just about every page load and am logging when there is some sort of error with ajax call. What I am finding is that about 0.3% of the time the ajax calls are failing the majority of the failures are in firefox 3.6. I am using jQuery 1.5.1 with ASP.NET server side. The 'errorThrown' parameter of the error callback reads:
[Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIXMLHttpRequest.getAllResponseHeaders]" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)"
and the jqXHR reads:
{"readyState":4,"status":0,"statusText":"error"}
I have confirmed with users that they are experienceing this problem and it's not just bots or some logging of an unexperienced error.
here is the code for my "load" widget
(function ($) {
$.fn.elfLoad = function (url, options) {
return this.each(function () {
var $elem = $(this);
options = $.extend({}, {
type: "GET",
dataType: "html",
data: "",
error: function (jqXHR, status, errorThrown) {
$elem.html('<div class="elf-missing-content centerText">Doh! Something did not go so well when trying to load this content. Please try again later.');
elf.ajax.logInfo("data: " + options.data + " errorThrown: " + errorThrown + " webmethod: " + options.url + "jqXHR: " + JSON.stringify(jqXHR),"elfLoad");
}
}, options);
options.success = function (data, status, jqXHR, responseText) {
responseText = jqXHR.responseText;
if (jqXHR.isResolved()) {
jqXHR.done(function (r) {
responseText = r;
});
$elem.html(responseText);
}
if (options.callback) {
var callbackArgs = {
responseText: responseText,
$elem: $elem,
status: status,
jqXHR: jqXHR
};
$elem.each(options.callback, [callbackArgs]);
}
}
options.url = url;
if (options.data) {
options.data = $.param(options.data, $.ajaxSettings.traditional);
options.type = "POST";
} else {
options.data = "";
}
$.ajax(options);
});
}
})(jQuery);
A call to it would look like this $('#container').elfLoad('url.aspx',{foo:'bar'});
Has anyone else had this problem? Any ideas? jQuery claims to have recently closed a ticket that looks like this in 1.5.1 but I see someone else is having a similar issue. http://bugs.jquery.com/ticket/8400
Thanks!
I ended up solving this issue by using a setTimeout for 2 seconds and retrying the request. So far this is working 100% of the time.