I'am new in MVC. I'am currently working to transform a desktop to a web application.
I need to make an update to the user view when an event of an object occurred. I have an object that observe a humidity sensor. Let say This object will trigger an event when the humidity above 70%. The code might be like this:
Private Sub Humidity_Alert(sender As Object) Handles objSensor.Alert
'Update user chart
End Sub
In desktop application, I just make an update to the view as usual in realtime, but I don't have any idea yet how to return this event to the client in MVC, without using javascript timer to make an ajax call to request if there is any alert. How to solve my problem?
I would suggest using ASP.NET SignalR library: signalr.net
You can use it for real-time updates from server to client.
ASP.NET SignalR is a new library for ASP.NET developers that makes it incredibly simple to add real-time web functionality to your applications. What is "real-time web" functionality? It's the ability to have your server-side code push content to the connected clients as it happens, in real-time.
Some pseudo-code example:
SignalR Hub:
public class HumidityHub : Hub
{
public void RefreshChart(string data)
{
Clients.All.refreshChart(data);
}
}
ClientCode:
var hub = $.connection.humidityHub;
hub.client.refreshChart= function (data) {
//refresh your chart
};
$.connection.hub.start();
ServerCode:
var hubContext = GlobalHost.ConnectionManager.GetHubContext<HumidityHub >();
hubContext.Clients.All.refreshChart(data);
Related
I am struggling to achieve the following:
I have created a Java websocket server which publishes data every 1 sec.
In ASP MVC projest I would like to receive the data and save them in database only so no JS involved here.
I am able to read the websocket data using console application method below :
using WebSocketSharp;
List<string> readoutList = new List<string>();
public void receiveMessage() {
using (var ws = new WebSocket("ws://localhost:4567/socket/"))
{
ws.OnMessage += (sender, e) =>
{
if (e.IsText)
{
readoutList.Add(e.Data.ToString());
Console.WriteLine(e.Data.ToString());
}
};
ws.Connect();
Console.ReadKey(true);
}
}`
How to create a service of this kind within the ASP MVC project? I need some direction here.
MVC is stateless so you have to request back to the server to initiate the request (such as from a form post) but within the MVC controller response, you can kick off the request to the server (as an example using a different technology). The problem is there isn't necessarily a 1 to 1 translation in MVC; initiating the request using client-side JavaSvcript would be the option here. Initiating these types of requests within MVC may cause issues with timeouts too that you have to be aware of.
OR, you can consider a scheduled windows program or a windows service that is installed, which can manage itself and initiate the request every so often. I think this is the better option.
I have a need to use a .net client to connect to a Signalr enabled application.
The client class needs to be a singleton and loaded for use globally.
I want to know what is the best technique for using singletons globally within an MVC application.
I have been looking into using the application start to get the singleton, where I keep it is a mystery to me.
The HUB cant be a singleton by design SignalR creates a instance for each incoming request.
On the client I would use a IoC framework and register the client as a Singleton, this way eachb module that tries to get it will get the same instance.
I have made a little lib that takes care of all this for you, install server like
Install-Package SignalR.EventAggregatorProxy
Read here for the few steps to hook it up, it needs a back plate service bus or event aggregator to be able to pickup your events
https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/wiki
Once configured install the .NET client in your client project with
Install-Package SignalR.EventAggregatorProxy.Client.DotNet
See here how to set it up
https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/wiki/.NET-Client
Once configured any class can register itself as a listener like
public class MyViewModel : IHandle<MyEvent>
{
public MyViewModel(IEventAggregator eventAggregator)
{
eventAggregator.Subscribe(this);
}
public void Handle(MyEvent message)
{
//Act on MyEvent
}
}
On the server you can send a message from outside the hub to all connected clients using the GetClients() method like this:
public MyHub : Hub
{
// (Your hub methods)
public static IHubConnectionContext GetClients()
{
return GlobalHost.ConnectionManager.GetHubContext<MyHub>().Clients;
}
}
You can use it like this:
MyHub.GetClients().All.SomeMethod();
I can see custom menu items and custom conversation windows and events inside them but nothing referring to how you'd execute code once a user signs into Lync. Does such an API exist?
I guess my alternative would be creating a Lync Automation object/my own client using the Suppressed ui and building whatever features I want into one of those?
There's nothing you can build into the Lync application, but you could run a separate application which can subscribe to the SignIn state of the user. That way, you'd know when a user signs-in, and could take appropriate action. You wouldn't need to create a SuppressedUI application for that, just something that ran in the background, or taskbar or something.
Here's a bare bones example:
namespace ThoughtStuff
{
class Program
{
static void Main(string[] args)
{
var client = LyncClient.GetClient();
client.StateChanged += client_StateChanged;
}
static void client_StateChanged(object sender, ClientStateChangedEventArgs e)
{
if (e.NewState == ClientState.SignedIn)
{
//do something on sign in
}
}
}
}
You might get errors if you try and attach to Lync in the SDK code using LyncClient.GetClient() if the Lync exe isn't running...but if you know that's likely to be a problem (such as if your application might be running before the user starts Lync), then you can gracefully handle it and retry in code.
I am creating a chat embedded in my asp.net mvc 4 project. I have an online users ul list which add a user on OnConnected and remove it on OnDisconnected.
So, my app isn't a SinglePage app, which means that it refreshes on pages all the time.
I am encountering some difficulties to treat with this online users list on the client side, because signalr calls OnDisconnected and OnConnected on every page refresh.
While the other client is navigating normally in app, it keep being removed and added on every refresh of page.
How to avoid this behavior on client?
I am trying to do some like this, on client which are running the page with usersOnline list...
var timeout;
chat.client.login = function (chatUser) {
addUser(chatUser);
window.clearTimeout(timeout);
};
chat.client.logout = function (chatUser) {
timeout = setTimeout(function () { removeUser(chatUser.Id); }, 3000);
};
But I am suffering to deal with multi-users scenario... Because if more than one user executes the hub onDisconnected before the timeout runs, the second will override the instance of the first.
There is indeed no real way around this. A client will always disconnect when leaving a page, and connects to SignalR again when the next page is loaded.
The only way around this is to create a SPA, so SignalR doesn't need to be disconnected by navigating away.
Using the idea of SignalR hubs is to allow real-time actions with minimal programming or complications - the best way would be for SignalR to be pulling from a list of currently logged in users, not active connections, as that could have the same user multiple times.
Therefore, I suggest, instead of OnConnected and OnDisconnected, put it in your AccountController, in the LogIn and LogOut methods. For example:
public ActionResult LogIn()
{
//other stuff
var hub = GlobalHost.ConnectionManager.GetHubContext</*Hub Title*/>();
hub.client.chat.login()
}
public ActionResult LogOut()
{
// other stuff
var hub = GlobalHost.ConnectionManager.GetHubContext</*Hub Title*/>();
hub.client.chat.logout()
}
We are currently working on the finishing touches of an application which uses Phonegap and have hit some issues with the Blackberry port.
So far, we've been reviewing the content available online and can't find a really finale answer to this. Seems like the "right" way to make and oauth authentication process for either Twitter, Facebook or Foursquare would be to use the ChildBrowser plugin, instantiate a window and then use that to handle the process.
Rightly so, there seems to be a lack of a ChildBrowser plugin for Blackberry. We've been looking so far at a couple of private projects on Github that look like they build/use that capability but we are not sure on how to control the created window.
Most (or all?) of those plugins refer to invoking the native Blackberry browser to handle the URLS, but then how would be manage to work on the callbacks, get the tokens and close the windows since it's another process.
For example, we have this concept code:
function openWindow() {
if (typeof blackberry !== 'undefined') {
app_id = SOMETHING_HERE;
redirect = 'http://www.facebook.com/connect/login_success.html';
url = 'https://graph.facebook.com/oauth/authorizeclient_id='+app_id+'&redirect_uri='+redirect+'&display=touch&scope=publish_stream';
var args = new blackberry.invoke.BrowserArguments(url);
blackberry.invoke.invoke(blackberry.invoke.APP_BROWSER, args);
}
}
Which works for opening the URL, but that's it. Is there a way to get a handle on the window and inject some listener to events? What should be our correct approach?
Thanks!
I am not PhoneGap user, but we did have to handle a very similar scenario - native app invokes the mobile browser to prompt the oAuth flow and then be able to handle a callback to the aative app.
This is possible on the BlackBerry using the BrowserContentProviderRegistry API. You can register your app to be invoked whenever a particular MIME type is returned to the browser. Sounds complicated but its fairly straightforward when all the pieces are in play.
Here is the rough flow -
Native app invokes browser to the oAuth page. This is part is easy and seems like you got this part.
The oAuth redirect needs to go to a URL that you can control. Something like http://mycompany.com/oAuthRedirectHandler.asp.
The oAuthRedirectorHandler.asp has simple code like this (we chose classic ASP but this can be done in PHP or any language, you can also ignore the Android block below) -
<html><body>
<h1>Redirect page</h1>
If you are not re-directed, please open the application manually.
<% strUA = Request.ServerVariables("HTTP_USER_AGENT")
if (InStr(strUA, "BlackBerry")) then
Response.Write("Opening appplication on BlackBerry")
Response.ContentType="application/x-MyCustomApp"
elseif (InStr(strUA, "Android")) then
Response.Write("Opening appplication on Android")
Response.Redirect("MyCustomApp://mycompany.com")
end if %>
</body> </html>
In your BlackBerry code you want a new BrowserContentProvider like this -
final class CustomBrowserProvider extends BrowserContentProvider{
String[] ACCEPT = new String[]{"application/x-MyCustomApp};
String appName;
CustomBrowserProvider(String appName){
this.appName = ApplicationDescriptor.currentApplicationDescriptor().getModuleName();
//cache this appName from the constructor in the invocation code below.
}
public String[] getSupportedMimeTypes() { return ACCEPT;}
public String[] getAccept(RenderingOptions context){return ACCEPT;}
public BrowserContent getBrowserContent( BrowserContentProviderContext context) throws RenderingException {
//this is where the callback happens
//this is happening in a separate process, raise your main app here using the appName that got passed in
//I dont have a sanitized ready to go sample to post here on how to do this, but not too complicated
//as a hint use the ApplicationDescriptor and CodeModuleManager classes
return null;
}
}
Now, in your application initialization, register this new BrowserPlugin like this -
BrowserContentProviderRegistry converterRegistry = BrowserContentProviderRegistry.getInstance();
converterRegistry.register(new CustomBrowserProvider());
Hope this helps. This has worked pretty well for us. The one downside we've had here is that when the user returns to the browser app, they are left with an empty page and there is no good way to close that in the BB.