SignalR Server Desktop application with Mosync mobile client application - c#

Now I am developing server desktop application in c#(visual Studio 2012) using SignalR.
Client Application using Mosync Mobile application(Mobile Platform Independent)
When server application and client application is on same machine(localhost), communication is successfully created and data feed from server to client is working fine. But When i put server application in remote server, Mosync client application is not communicate with server. Could any one help me?
Server side code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Hosting;
using Microsoft.Owin.Cors;
using Microsoft.Owin;
using Owin;
namespace SampleSignalRServer
{
public partial class Form1 : Form
{
private IDisposable signalR { get; set; }
const string ServerURI = "http://localhost:8080";
MyHub h = new MyHub();
public Form1()
{
InitializeComponent();
}
private void btnServerStart_Click(object sender, EventArgs e)
{
writeToConsole("Starting server...");
btnServerStart.Enabled = false;
Task.Run(() => StartServer());
}
private void StartServer()
{
try
{
signalR = WebApp.Start(ServerURI);
}
catch (TargetInvocationException)
{
writeToConsole("Server failed to start. A server is already running on" + ServerURI);
this.Invoke((Action)(() => btnServerStart.Enabled = true));
return;
}
this.Invoke((Action)(() => btnServerStart.Enabled = true));
writeToConsole("Server started at" + ServerURI);
}
public void writeToConsole(string message)
{
if (RichTextBoxConsole.InvokeRequired)
{
this.Invoke((Action)(() => writeToConsole(message)));
return;
}
RichTextBoxConsole.AppendText(message + Environment.NewLine);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (signalR != null)
{
signalR.Dispose();
}
}
private void btnSend_Click(object sender, EventArgs e)
{
string msg = txtMessage.Text;
h.Receive(msg);
}
private void timer1_Tick(object sender, EventArgs e)
{
string message = "hi";
// h.Receive(message);
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
public class MyHub : Hub
{
public void Send(string name, string message)
{
Clients.All.addMessage(name, message);
Program.mainform.writeToConsole(name + " : " + message);
}
public void Receive(string msg)
{
var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
context.Clients.All.addMessage("Admin", msg);
}
public override Task OnConnected()
{
Program.mainform.writeToConsole("Client Connected:" + Context.ConnectionId);
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
Program.mainform.writeToConsole("Client DisConnected: " + Context.ConnectionId);
return base.OnDisconnected(stopCalled);
}
}
}
Client mobile application Code(MOsync- Html + Javascript)
<!DOCTYPE html>
<!--
* #file index.html
*
* Template application that shows examples of how to access
* device services from JavaScript using the Wormhole library.
-->
<html>
<head>
<title>SignalR Simple Chat</title>
<style type="text/css">
.container {
background-color: #99CCFF;
border: thick solid #808080;
padding: 20px;
margin: 20px;
}
</style>
<meta name="viewport" content="width=320, user-scalable=no">
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Wormhole Template App</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" title="no title" charset="utf-8">
<script type="text/javascript" charset="utf-8" src="js/wormhole.js"></script>
<script src="js/jquery-1.6.4.min.js"></script>
<script src="js/jquery.signalR-2.0.3.min.js"></script>
<script src="http://localhost:8080/signalr/hubs"></script>
<script type="text/javascript">
function StartConnection()
{
alert("Start Button Clicked");
$.connection.hub.url = "http://localhost:8080/signalr";
var chats = $.connection.myHub;
alert(chats);
chats.client.addMessage = function (name, message)
{
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
chats.server.send($('#displayname').val(), $('#message').val());
$('#message').val('').focus();
});
});
}
// Register event listeners.
// The "deviceready" event is sent when the system
// has finished loading.
document.addEventListener(
"deviceready",
displayDeviceInfo,
true);
// Close the application when the back key is pressed.
document.addEventListener(
"backbutton",
function() { mosync.app.exit(); },
true);
</script>
</head>
<body>
<div class="container">
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="button" id="sendmessagfe" value="localhost:8080" />
<input type="hidden" id="displayname" />
<input type="button" value="Start" onclick="StartConnection()"/>
<ul id="discussion"></ul>
</div>
</body>
</html>

Assuming your code is ok, which it does at first glance, then it is probably either an IIS or network/infrastructure issue. Have you investigated this possibility?
SignalR is supported on IIS 7.0 and 7.5, but support for extensionless
URLs must be added. To add support for extensionless URLs, see
http://support.microsoft.com/kb/980368

Related

signalr/hubs file does not get generated

I saw similar questions on internet but no solution helps.
I'm working on web forms.
Installed SignalR 2.2.2 and jQuery 3.3.1.
my script
<script src='<%: ResolveClientUrl("/Scripts/jquery-3.3.1.min.js") %>'></script>
<script src='<%: ResolveClientUrl("/Scripts/jquery.signalR-2.2.2.min.js") %>'></script>
<script src="/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var alpha = $.connection.alphaHub;
// Create a function that the hub can call to broadcast messages.
alpha.client.broadcastMessage = function (message) {
alert(message);
//// Html encode display name and message.
//var encodedName = $('<div />').text(name).html();
//var encodedMsg = $('<div />').text(message).html();
//// Add the message to the page.
//$('#discussion').append('<li><strong>' + encodedName
// + '</strong>: ' + encodedMsg + '</li>');
};
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
alpha.server.display($("parameters here"));
});
});
});
</script>
Error is this
localhost:8888/signalr/hubs not found
Startup.cs (in the same directory as Default.aspx file)
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
Hub class
public class AlphaHub : Hub
{
public void Display(string name, string message)
{
Clients.All.broadcastMessage(name, message);
}
}
I tested same code. Built separate project and it worked there. The problem is in my current project.

Web Scraping Java Sites with HtmlAgilityPack

Let me start out by saying that I am no pro at web scraping. I can do the basics on most platforms, but that's about it.
I am trying to create the foundation for a web application that can helps users reinforce their language learning by generating additional data, metrics, as well as create new tools for self-testing. The Duolingo website is not offering up any sort of API so my next thought for now is just to scrape https://www.duome.eu/. I wrote a quick little scraper but didn't realize that the site was java. In the following example, it is my wish to collect all of the words from the Words tab that contain anchors:
using System;
using HtmlAgilityPack;
using System.Net.Http;
using System.Text.RegularExpressions;
namespace DuolingoUpdate
{
class Program
{
static void Main(string[] args)
{
string userName = "Podus";
UpdateDuolingoUser(userName);
Console.ReadLine();
}
private static async void UpdateDuolingoUser(string userName)
{
string url = "https://www.duome.eu/" + userName + "/progress/";
// Create the http client connection
HttpClient httpClient = new HttpClient();
var html = await httpClient.GetStringAsync(url);
// Store the html client data in an object
HtmlDocument htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(html);
//var words = htmlDocument.DocumentNode.Descendants("div")
// .Where(node => node.GetAttributeValue("id", "")
// .Equals("words")).ToList();
//var wordList = words[0].Descendants("a")
// .Where(node => node.GetAttributeValue("class", "")
// .Contains("wA")).ToList();
Console.WriteLine(html);
}
}
}
The html object of the above code contains:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="google" value="notranslate">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Duolingo · Podus # duome.eu</title>
<link rel="stylesheet" href="/style.css?1548418871" />
<link href="/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
if("".length==0){
var visitortime = new Date();
var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
//localStorage.tz = visitortimezone;
//timezone = Date.parse(localStorage.tz);
//timezone = localStorage.tz;
//console.log(timezone);
$.ajax({
type: "GET",
url: "/tz.php",
data: 'time='+ visitortimezone,
success: function(){
location.reload();
}
});
}
});
</script>
</head>
<body>
<noscript>Click here to adjsut XP charts to your local timezone. </noscript>
<!-- Yandex.Metrika counter --> <script type="text/javascript" > (function (d, w, c) { (w[c] = w[c] || []).push(function() { try { w.yaCounter47765476 = new Ya.Metrika({ id:47765476, clickmap:true, trackLinks:true, accurateTrackBounce:true }); } catch(e) { } }); var n = d.getElementsByTagName("script")[0], s = d.createElement("script"), f = function () { n.parentNode.insertBefore(s, n); }; s.type = "text/javascript"; s.async = true; s.src = "https://mc.yandex.ru/metrika/watch.js"; if (w.opera == "[object Opera]") { d.addEventListener("DOMContentLoaded", f, false); } else { f(); } })(document, window, "yandex_metrika_callbacks"); </script> <noscript><div><img src="https://mc.yandex.ru/watch/47765476" style="position:absolute; left:-9999px;" alt="" /></div></noscript> <!-- /Yandex.Metrika counter -->
</body>
</html>
But if you go to the actual url https://www.duome.eu/Podus/progress/, the site contains a ton of script. So upon inspection the first problem is that I am not getting the html that I see in the browser. The second problem is that if you view source, its nothing like what is in inspect and I don't see anything in source that would lead me to isolate the data from div id="words".
Given my lackluster knowledge of java built web pages, how do I do this, or is it even possible?
You can access dualingo profile data in JSON format via https://www.duolingo.com/users/<username>
eg. https://www.duolingo.com/users/Podus
This should be much easier than trying to scrape the duome profile page manually.

Send a broadcast POP-UP Message to All the Connected Clients

I am building(still learning) a web application in ASP.NET WebForms with C#.We have a Centralized Database and all Clients are connected to the Database through a same static IP.Each of the Clients have their own
Unique Office ID.We have 16 Offices each having their own office ID.Every Day we update new features with new build.Instead of sending chat message
to individual client about the new changes/updates/features, can we make it send as a broadcast message like from all the offices i have mentioned
there is a corporate office with OfficeId=14.So the moment the User from other office Logs in, he/she should see a pop-up notification message
about the changes.Is it possible to make say a form to enter the details about the changes and the moment the user from the corporte office saves it, it shows in the index page of
all the clients?
I did a lot of research on this, but couldnt get a solid explanation.This might be a duplicate or lame question for all the experts out here,please
bear with me.
Check this link ASP.Net SignalR: Building a Simple Real-Time Chat Application
from the ChatHub class and Use following Code.
public class ChatHub : Hub
{
static ConcurrentDictionary<string, string> dic = new ConcurrentDictionary<string, string>();
public void Send(string name, string message)
{
Clients.All.broadcastMessage(name, message);
}
public void Notify(string name, string id)
{
if (dic.ContainsKey(name))
{
Clients.Caller.differentName();
}
else
{
dic.TryAdd(name, id);
foreach (KeyValuePair<String, String> entry in dic)
{
Clients.Caller.online(entry.Key);
}
Clients.Others.enters(name);
}
}
public override Task OnDisconnected()
{
var name = dic.FirstOrDefault(x => x.Value == Context.ConnectionId.ToString());
string s;
dic.TryRemove(name.Key, out s);
return Clients.All.disconnected(name.Key);
}
}
And in HTML + javascript
<script type="text/javascript">
$(function () {
showModalUserNickName();
});
function showModalUserNickName() {
$("#dialog").dialog({
modal: true,
buttons: {
Ok: function () {
$(this).dialog("close");
startChartHub();
}
}
});
}
function startChartHub() {
var chat = $.connection.chatHub;
// Get the user name.
$('#nickname').val($('#nick').val());
chat.client.differentName = function (name) {
showModalUserNickName();
return false;
// Prompts for different user name
$('#nickname').val($('#nick').val());
chat.server.notify($('#nickname').val(), $.connection.hub.id);
};
chat.client.online = function (name) {
// Update list of users
if (name == $('#nickname').val())
$('#onlineusers').append('<div class="border" style="color:green">You: ' + name + '</div>');
else {
$('#onlineusers').append('<div class="border">' + name + '</div>');
}
};
chat.client.enters = function (name) {
$('#chatlog').append('<div style="font-style:italic;"><i>' + name + ' joins the conversation</i></div>');
$('#onlineusers').append('<div class="border">' + name + '</div>');
};
// Create a function that the hub can call to broadcast chat messages.
chat.client.broadcastMessage = function (name, message) {
//Interpret smileys
message = message.replace(":)", "<img src=\"/images/smile.gif\" class=\"smileys\" />");
message = message.replace("lol", "<img src=\"/images/laugh.gif\" class=\"smileys\" />");
message = message.replace(":o", "<img src=\"/images/cool.gif\" class=\"smileys\" />");
//display the message
$('#chatlog').append('<div class="border"><span style="color:red">' + name + '</span>: ' + message + '</div>');
};
chat.client.disconnected = function (name) {
//Calls when someone leaves the page
$('#chatlog').append('<div style="font-style:italic;"><i>' + name + ' leaves the conversation</i></div>');
$('#onlineusers div').remove(":contains('" + name + "')");
}
// Start the connection.
$.connection.hub.start().done(function () {
//Calls the notify method of the server
chat.server.notify($('#nickname').val(), $.connection.hub.id);
$('#btnsend').click(function () {
// Call the Send method on the hub.
chat.server.send($('#nickname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
}
</script>
<div id="container">
<input type="hidden" id="nickname" />
<div id="chatlog"></div>
<div id="onlineusers">
<b>Online Users</b>
</div>
<div id="chatarea">
<div class="messagelog">
<textarea spellcheck="true" id="message" class="messagebox"></textarea>
</div>
<div class="actionpane">
<input type="button" id="btnsend" value="Send" />
</div>
<div class="actionpane">
</div>
</div>
<div id="dialog" title="Enter your name to start a chat.">
<input type="text" id="nick" />
</div>

SignalR 2.0.0.0: $.connection is undefined

I am trying to run my first SignalR v2 project but with no luck, $.connection is undefined.
Here is the error from web console:
Uncaught TypeError: Cannot read property 'chatHub' of undefined (anonymous function)
k
l.fireWith
p.extend.ready
D
My hub:
using Microsoft.AspNet.SignalR;
namespace InstantMessage
{
public class ChatHub : Hub
{
public void Hello()
{
Clients.All.hello();
}
}
}
Startup.cs
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(InstantMessage.Startup))]
namespace InstantMessage
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
Fontend:
<head>
.....
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-2.0.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
</head>
<body>
<h2>Instant Message Demo</h2>
<div class="container">
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion">
</ul>
</div>
<!--Add script to update the page and send messages.-->
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
console.log($.connection);
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
</body>
It seems like the js code in /signalr/hubs is correct, chathub is there and the autogeneration of the file works fine.
$.hubConnection.prototype.createHubProxies = function () {
var proxies = {};
this.starting(function () {
// Register the hub proxies as subscribed
// (instance, shouldSubscribe)
registerHubProxies(proxies, true);
this._registerSubscribedHubs();
}).disconnected(function () {
// Unsubscribe all hub proxies when we "disconnect". This is to ensure that we do not re-add functional call backs.
// (instance, shouldSubscribe)
registerHubProxies(proxies, false);
});
proxies.chatHub = this.createHubProxy('chatHub');
proxies.chatHub.client = { };
proxies.chatHub.server = {
hello: function () {
return proxies.chatHub.invoke.apply(proxies.chatHub, $.merge(["Hello"], $.makeArray(arguments)));
}
};
return proxies;
};
Should also mention that I installed Signalr from nuget and I am using VS2012.
Removing BundleConfig.RegisterBundles(BundleTable.Bundles); from Global.asax.cs fixed this for me. I encountered this problem because jQuery was being included twice.
Place a metatag like the following just before your ChatHub Class definition
[HubName("chatHub")]
Is your reference to jquery correct? The SignalR package currently installs 1.6.4--

500 Internal Server error when trying to pass messages between SignalR self-hosted server and client

I'm trying to work up a simple example of a SignalR self hosted server on a Mono solution to demo to our executive department. I've followed the github example code, and I have half of the functionality working. When the 'broadcast' button is pushed, the message in the text box is echoed in the server console, but it does not get broadcast back to the client.
The server code:
public class Global : System.Web.HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
//Initialize your application
new AppHost().Init();
WebApplication.Start<Startup>("http://127.0.0.1:10000");
}
protected void Application_BeginRequest(object src, EventArgs e)
{
this.Context.Response.AddHeader("Access-Control-Allow-Headers", "accept,origin,authorization,content-type");
#if DEBUG
Profiler.Start();
#endif
}
protected void Application_EndRequest(object src, EventArgs e)
{
#if DEBUG
Profiler.Stop();
#endif
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapHubs(new HubConfiguration { EnableCrossDomain = true });
}
}
public class Chat : Hub
{
public void Send(string message)
{
Console.WriteLine(message);
Clients.All.addMessage(message);
}
}
}
The client code:
<script src="http://code.jquery.com/jquery-1.9.1.min.js" type="text/javascript"> </script>
<script src="Scripts/jquery.signalR.min.js" type="text/javascript"></script>
<!-- If this is an MVC project then use the following -->
<!-- <script src="~/signalr/hubs" type="text/javascript"></script> -->
<script src="http://127.0.0.1:10000/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$.connection.hub.url = "http://127.0.0.1:10000/signalr";
$.connection.hub.logging = true;
// Proxy created on the fly
var chat = $.connection.chat;
// Declare a function on the chat hub so the server can invoke it
chat.client.addMessage = function (message) {
$('#messages').append('<li>' + message + '</li>');
};
// Start the connection
$.connection.hub.start({ jsonp: true }).done(function() {
$("#broadcast").click(function () {
// Call the chat method on the server
chat.server.send($('#msg').val());
});
});
});
</script>
<div>
<input type="text" id="msg" />
<input type="button" id="broadcast" value="broadcast" />
<ul id="messages">
</ul>
</div>
When I start the client up, I do get a strange error in the negotiation process, which seems strange since the client can successfully push messages to the server.
[17:13:54 GMT-0400 (EDT)] SignalR: Auto detected cross domain url. jquery.signalR.min.js:10
[17:13:54 GMT-0400 (EDT)] SignalR: Negotiating with 'http://127.0.0.1:10000/signalr/negotiate'. jquery.signalR.min.js:10
[17:13:54 GMT-0400 (EDT)] SignalR: SignalR: Initializing long polling connection with server. jquery.signalR.min.js:10
[17:13:54 GMT-0400 (EDT)] SignalR: Attempting to connect to 'http://127.0.0.1:10000/signalr/connect?transport=longPolling&connectionToke…kjVpNzqCLDXzDDRkE&connectionData=%5B%7B%22name%22%3A%22chat%22%7D%5D&tid=2' using longPolling. jquery.signalR.min.js:10
GET http://127.0.0.1:10000/signalr/connect?transport=longPolling&connectionToke…D&tid=2&callback=jQuery191021586751635186374_1366665233871&_=1366665233874 500 (Internal Server Error) jquery-1.9.1.min.js:5
send jquery-1.9.1.min.js:5
b.extend.ajax jquery-1.9.1.min.js:5
s jquery.signalR.min.js:10
(anonymous function) jquery.signalR.min.js:10
[17:13:54 GMT-0400 (EDT)] SignalR: Longpolling connected
Any help would be greatly appreciated.

Categories

Resources