SignalR client C# Windows Application using JavaScript (Without using any c# code) - signalr

I want to make an client Windows Application using java script by make my Windows Application as webBrowser1 (same idea of PhoneGap). I write html page that contains SignalR javascript code with necessary src.
This is the code in Windows Application:
webBrowser1.Url = new Uri(#"D:\Signal.html");
This is the src in Signal.html:
<script src="json2.js"></script>
<script src="jquery-1.6.4.js"></script>
<script src="jquery.signalR-2.2.0.js"></script>
<script src="http://localhost:5539/signalr/hubs" type="text/javascript"></script>
Unfortunately it doesn't work!! What is the wrong??
The hole Code of SignalR.html is here
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<title>SignalR Simple Chat</title>
<style type="text/css">
.container {
background-color: #99CCFF;
border: thick solid #808080;
padding: 20px;
margin: 20px;
}
</style>
</head>
<body>
<div class="container">
<input type="text" id="message" placeholder="Message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion"></ul>
</div>
<div style="background-color:GrayText; height:30%; text-align:center; ">
<h1>Groups</h1>
<input type="text" id="name" placeholder="User Name" />
<input type="text" id="groupName" placeholder="Group Name"/>
<input type="button" id="broadcast" value="Broadcast" />
<input type="button" id="join" value="Join" />
<input type="button" id="leave" value="Leave" />
<input type="button" id="refresh" value="Leave" />
</div>
<script src="json2.js"></script>
<script src="jquery-1.6.4.js"></script>
<script src="jquery.signalR-2.2.0.js"></script>
<script src="http://localhost:5539/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
//Set the hubs URL for the connection
$.connection.hub.url = "http://localhost:5539/signalr";
// Declare a proxy to reference the hub.
var chat = $.connection.chatingHub;
var counterh = $.connection.ConnectionCounter;
//counterh.client.NumberOfConnter = function (count) { $("div").append(count); }
chat.client.displayText = function (name, message) {
$('#messages').append('<li>' + name + ' said: ' + message + '</li>');
};
chat.client.le = function (id) { alert(id); }
chat.client.alertJoin = function (namePersonJoined) { $('#messages').append('<li>' + namePersonJoined + " Join to the Group" + '</li>').css("background-color", "white"); }
chat.client.alertLeave = function (namePersonLeaved) { $('#messages').append('<li>' + namePersonLeaved + " Leave from the Group" + '</li>'); }
// Create a function that the hub can call to broadcast messages.
chat.client.addMessage = 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();
});
$("#broadcast").click(function () {
chat.server.broadcastMessage({
Name: $('#name').val(),
Message: $('#message').val(), Group: $('#groupName').val()
});
});
$("#join").click(function () {
chat.server.join($('#groupName').val(), $('#name').val());
});
$("#leave").click(function () {
chat.server.leave($('#groupName').val(), $('#name').val());
});
$("#refresh").click(function () {
chat.server.nowID();
});
});
});
</script>
</body>
</html>

I think it's a CORS problem.
Your signalR client is in D:\SignalR.html
Your signalR server is in http://localhost:5539/signalr/hubs
meaning that it is a Cross Origin signalR calls. You need to enable CORS in order to let it works.

Related

Phonegap CRUD operations - window.openDatabase

Am trying to create a CRUD operation using phonegap/cordova, and I keep receiving "Uncaught DOMException: An attempt was made to break through the security policy of the user agent. at window.onload - Line 17" pointing to =>"db = window.openDatabase("employee", "1.1", "LearnToProgram", 200000);". This further affects db.transaction Line 25 “Uncaught TypeError: Cannot read property 'transaction' of undefined”, because Database was not created. Do I need any SQLLite plugin on maybe there is something else missing?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>SQLLite DB App</title>
<script type="text/javascript" src="cordova.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script>
var db;
window.onload=function()
{
document.getElementById('btnSave').addEventListener('click', saveData);
db = window.openDatabase("employees", "1.0", "LearnToProgram", 200000);
}
function saveData(e)
{
db.transaction(saveRecord, onSuccess, onError);
}
function saveRecord(transaction)
{
var name= document.getElementById('name').value;
var email = document.getElementById('email').value;
transaction.executeSql('CREATE TABLE IF NOT EXISTS employeesList (id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT NOT NULL, Email TEXT NOT NULL) ');
var sql= "INSERT INTO employeesList (Name,Email) VALUES ('" + name +"', '" + email + "')";
console.log(sql);
transaction.executeSql(sql);
}
function onSuccess()
{
console.log("Record Saved");
}
function onError(error)
{
console.log("SQL error: " + error.code);
}
</script>
</head>
<body>
<div data-role="page">
<div data-role="header"><h1>Database Storage</h1></div>
<div data-role="main" class="ui-content">
<label for="name">Name</label>
<input type="text" id="name" />
<label for="email">Email</label>
<input type="text" id="email" />
<button id="btnSave" type="submit">Save</button>
<button id="showList">Show Employees</button>
</div><!-- main-->
</div><!-- page -->
</body>
</html>
maybe I help you.
To open a database:
var db = null;
document.addEventListener('deviceready', function() {
db = window.sqlitePlugin.openDatabase({
name: 'my.db',
location: 'default',
});
});
IMPORTANT: Like with the other Cordova/phonegap plugins your application must wait for the deviceready event. This is especially tricky in Angular/ngCordova/Ionic controller/factory/service callbacks which may be triggered before the deviceready event is fired.

SignalR doesn't work in WebForm

I'm using Visual Studio 2015 to develop an asp.net webform. I'm new to SignalR and I'm trying to get the demo piece to work in an existing site. When I create an html page it works fine:
<!DOCTYPE html>
<html>
<head>
<title>SignalR Simple Chat</title>
<style type="text/css">
.container {
background-color: #99CCFF;
border: thick solid #808080;
padding: 20px;
margin: 20px;
}
</style>
</head>
<body>
<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>
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="Scripts/jquery-1.10.2.min.js"></script>
<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-2.2.1.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="signalr/hubs"></script>
<!--Add script to update the page and send messages.-->
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
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>
</html>
However, when I use the same code, in the same project, but using a WebForm it gives me an error message: 0x800a138f - JavaScript runtime error: Unable to get property 'ChatHub' of undefined or null reference. I've been blowing an entire day on trying to get SignalR going and I'm at a loss.
Here's the code that blows up:
<%# Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/MasterPages/Site.Master" CodeBehind="WebForm2.aspx.vb" Inherits="RealtimeReportsWF.WebForm2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<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>
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="Scripts/jquery-1.10.2.min.js"></script>
<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-2.2.1.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="signalr/hubs"></script>
<!--Add script to update the page and send messages.-->
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
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>
</asp:Content>
I slept on it and had to remember the golden rule of frameworks like SignalR... it's just java. I then realized I didn't include the ../ in the path. Makes sense since on the HTML version it was contained in the path. So modifying the code to include this solved the problem:
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="../Scripts/jquery-1.10.2.min.js"></script>
<!--Reference the SignalR library. -->
<script src="../Scripts/jquery.signalR-2.2.1.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="../signalr/hubs"></script>

How to use ocpu.r_fun_call?

I am able to use the opencpu function ocpu.rpc. But not the function ocpu_r_fun_call. Why the above code does not work?
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="//cdn.opencpu.org/opencpu-0.4.js"></script>
<script>
$(document).ready(function(){
$("#submitbutton").click(function(){
var req = ocpu.r_fun_call("mean", {"x" : 10}, function(session){
$("#namefield").val(session);
});
});
});
</script>
</head>
<body>
<input type="text" id="namefield" value="">
<button id="submitbutton" type="button">Submit!</button>
</body>
</html>
I also tried:
$("#submitbutton").click(function(){
var req = ocpu.r_fun_call("mean", {"x" : 10}, function(session){
session.getObject(function(data){
$("#namefield").val(data);
});
});
});
And I also tried with session.getConsole, and also:
var req = ocpu.r_fun_call("mean", {"x" : 10}, function(session){
$("#submitbutton").on("click", function(){
$("#namefield").val(session.getObject());
});
});
The main problems were:
the js function is ocpu.call, not ocpu.r_fun_call
the fact that the mean function does not belong to my package. If I put an average function in my package:
average <- mean
Then I can use it with opencpu like this:
<html>
<head>
<script src="opencpu/jquery-1.10.2.min.js"></script>
<script src="opencpu/opencpu-0.4.js"></script>
<script>
$(document).ready(function(){
$("#submitbutton").on("click", function(){
var req = ocpu.call("average", {
x : 10
}, function(session){
session.getObject(function(data){
$("#namefield").val(data)
});
});
//if R returns an error, alert the error message
req.fail(function(){
alert("Server error: " + req.responseText);
});
});
});
</script>
</head>
<body>
<button id="submitbutton" type="button">Submit!</button>
<input type="text" id="namefield" value="">
</body>
</html>
Note the tip to know more when there's a problem:
//if R returns an error, alert the error message
req.fail(function(){
alert("Server error: " + req.responseText);
});

pass form values to server in Meteor

I have a simple form in meteor which would help configure the execution of my custom application.
This form receives two arguments, Username and Password.
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Execute my custom app</title>
</head>
<body>
{{> configDetails}}
</body>
<template name="configDetails">
<div class="container">
<form class="form-signin" role="form" id="form-signin" >
<div class="row">
<div class="span3 offset"><input type="textBox" class="input-block-level" placeholder="User Name" ></div>
<div class="span3 offset1"><input type="textBox" class="input-block-level" placeholder="Password" ></div>
</div>
<input class="btn btn-lg btn-primary" type="submit" style="display: block; width: 100%;" id="submit"/>
</form>
</div>
</template>
Now I want these values to be received on the server side so that I can run my external app using child_process and pass these values as arguments to the external app. How can I receive these value in the meteor server section:
if (Meteor.isServer) {
//I intend to use child_process to run my external application here
}
If the values cannot directly be received in the server section, how can I receive them in client section and pass them onto server. I am having difficulties receiving them in client section as well:
if (Meteor.isClient) {
Template.configDetails.events({
'click input': function () {
console.log( 'Submitting form!' );
// template data, if any, is available in 'this'
if (typeof console !== 'undefined')
console.log("You pressed the button");
}
});
Template.configDetails.events({
'submit form': function( event ){
console.log( 'Submitting form!' );
event.preventDefault();
event.stopPropagation();
return false;
}
});
None of the above functions execute the console.log method. Any ideas what I am doing wrong. Let me know if you need further info.
In my projets I'm using smth like this:
Template.configDetails.events({
"click #submit": function(e, t) {
e.preventDefault();
Meteor.call('someMethod', attributes, function(error, id) {
if (error) {
return console.log("Error..........");
} else {
//Do smth
}
});
});
}
});

How to mix jQuery Mobile and ASP.NET

I'm making a mobile website, using jQuery Mobile and ASP.NET 4.0 Webforms. I have made an initial login page (Default.aspx) in which the button calls an ajax JavaScript function, which calls a page method in the backend like so:
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UCP.Default" %>
<!DOCTYPE html>
<html>
<head>
<title>UA Cover Plus</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"></script>
</head>
<body>
<!-- Login -->
<div data-role="page" id="login">
<div data-role="header" data-position="fixed">
<h1>Login</h1>
<a href="#Family" data-icon="gear" class="ui-btn-right" data-iconpos="notext" data-theme="b" >Options</a>
</div>
<div data-role="content" data-theme="a">
<input type="text" id="txtUserName" placeholder="Username" />
<input type="password" name="passwordinput" id="txtPassword" placeholder="Password" value="" />
Log Me In!
</div><!-- /content -->
</div><!-- /page -->
</body>
Ajax JQuery Function :
function Authenticate() {
$.ajax({
type: "POST",
url: "Default.aspx/Authenticate",
data: "{'name': '" + $('#txtUserName').val() + "','pass': '" + $('#txtPassword').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if (msg.d != '-1') {
userId = msg.d;
GetCustomisedConsole();
} else {
alert("Authentication Failed");
}
},
error: function () {
alert("Error :(");
}
});
};
Page method in Default.aspx.cs
[WebMethod]
public static int Authenticate(string name, string pass)
{
using (DbContext db = new DbContext())
{
var user = db.Users.Where(x => x.UserName == name && x.Password == pass).SingleOrDefault();
if (user != null)
{
return user.Id;
}
else
{
return -1;
}
}
}
My question is, is this the way its meant to be done? I ask this because I see in the jQuery examples the use of forms and submits, which I have no idea how to implement in asp.net.
I'm doing in the same way and works perfect.
Please take a look to this example
Invoking Server Methods Using Jquery

Resources