Good day,
Unfortunately, I can not get SignalR to work for a private 1 on 1 chat.
Here the following things that I have done:
References that are situated in the head tag of my layout page in the right order:
<script src="~/Scripts/jquery-1.6.4.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.3.0.js"></script>
Even added both bellow to check if either worked but no luck.
<script src="/signalr/hubs"></script>
<script src="http://localhost:50581/signalr/hubs"></script>
Have an Owin startup class:
[assembly: OwinStartup(typeof(Startup))]
namespace WebApplication6
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HubConfiguration();
config.EnableDetailedErrors = true;
config.EnableJavaScriptProxies = true;
app.MapSignalR("/signalr", config);
}
}
}
Have my chatHub class with my methods inside:
[HubName("chatHub")]
public class ChatHub : Hub
{
}
I have a javascript file named chatboxManager with the following inside:
var connection = $.hubConnection();
var ChatHub = connection.createHubProxy('chatHub');
Using the above I get a connection to the chatHub
but it does not recognise the .client the bellow:
// On New User Connected
debugger;
ChatHub.client.onNewUserConnected = function (id, name, userid) {
AddUser(ChatHub, id, name, userid);
}
If I use this at the beginning of the js file nothing works:
var ChatHub = $.connection.chatHub;
Is there something else that I could be missing?
I have de-installed the packages and re-installed them.
Any advice would greatly be appreciated to get this running.
Kind regards and thanks
I dont know if this might be the solution but give it a try
var hubConnection = new HubConnection("http://yourIpHere:yourPortNr/signalr");
var chatHubProxy = hubConnection.CreateHubProxy("chatHub");
Related
I am brand new on Apache Wicket and I need to set value on a Java attribute. This value comes from a var on JS filled by a specific function from a specific GIS lib (https://leaflet.github.io/Leaflet.draw/docs/leaflet-draw-latest.html). This setting must be triggered by some component behavior.
Here is a simplified example code:
Wicket web page:
public class MapPage extends WebPage {
private static final long serialVersionUID = 1L;
private Integer coordinates;
// getters and setters
}
Wicket html:
<html xmlns:wicket="http://wicket.apache.org">
<head>
<!-- metas, scripts, and css imports -->
</head>
<body>
<script>
// component declarations
var coordinates = ''
map.on('draw:edited', function (e) {
e.layers.eachLayer(function(layer) {
coordinates = toWKT(layer);
// send coordinates to coordinates java attribute ??? how??
});
});
</script>
</body>
Thanks a lot!
This is a piece of code from one of my projects, where I want to handle a click on a (HighCharts) chart. It passes data to Wicket and Wicket then updates another panel to display details related to the click.
The relevant javascript part, where interactionurl is actually the callbackScript that is generated by the behavior later on:
interactionurl(JSON.stringify(myDataToPass));
The behaviour:
this.add( this.interactionbehavior = new AbstractDefaultAjaxBehavior()
{
#Override
protected void respond( final AjaxRequestTarget target )
{
RequestCycle cycle = RequestCycle.get();
WebRequest webRequest = (WebRequest) cycle.getRequest();
String param1 = webRequest.getQueryParameters().getParameterValue( "mydict" ).toString( "" );
//param1 contains the JSON map passed from javascript.
//you can also do stuff now, like replacing components using ajax
}
#Override
protected void updateAjaxAttributes( AjaxRequestAttributes attributes )
{
super.updateAjaxAttributes( attributes );
attributes.getExtraParameters().put( "mydict", "__PLACEHOLDER__" );
}
#Override
public CharSequence getCallbackScript()
{
String script = super.getCallbackScript().toString().replace( "\"__PLACEHOLDER__\"", "data" );
return script;
}
} );
You only need to pass the interaction url to the page on some moment. For this you can use renderHead in the component that has the behaviour:
#Override
public void renderHead( final IHeaderResponse response )
{
...
//use the `setupCallback` to store the callback script somewhere.., I store it in 'interactionurl'
String script = String.format( " setupCallback(this.interactionbehavior.getCallbackScript()); ");
response.render( OnDomReadyHeaderItem.forScript( script )
}
I am trying to make a simple user counter with SignalR, but for unknown reasons to me I am getting this error in the console. I am very new to signalR and asp.net, but what I have make sense to me, and I don't know why am I getting the error. Can somebody please help me solve this and possibly explain why it is happening?
Here is the code in the Index view.
<div class="row">
Number of online users <strong id="counter"></strong>
<script src="#Url.Content("~/Scripts/jquery-3.1.1.min.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.signalR-2.2.1.min.js")"></script>
<script src="#Url.Content("~/signalr/hubs")"></script>
<script>
$(function () {
var counterHub = $.connection.counterHub;
$.connection.hub.start().done(function () {
});
counterHub.client.UpdateCount = function (count) {
$("#counter").text(count);
}
});
</script>
The hub class :
public class CounterHub : Hub
{
static long counter = 0;
public override System.Threading.Tasks.Task OnConnected()
{
counter = counter + 1;
Clients.All.UpdateCount(counter);
return base.OnConnected();
}
public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
{
counter = counter - 1;
Clients.All.UpdateCount(counter);
return base.OnDisconnected(stopCalled);
}
//public void Hello()
//{
// Clients.All.hello();
//}
}
And the Startup.cs :
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
ConfigureAuth(app);
}
}
Not sure why, but this made it work for me finally. I just surrounded the script tags with #section scripts :
#section scripts{
<script src="~/Scripts/jquery.signalR-2.2.1.min.js"></script>
<script src="~/signalr/hubs"></script>
<script>
$(function () {
var myHub = $.connection.counterHub;
$.connection.hub.start().done(function () {
});
myHub.client.UpdateCount = function (count) {
$("#counter").text(count);
}
});
</script>
}
Is your chat files in the root of application?
The only thing that I think is your page has not connected to Hub proxy javascript file:
ASP.NET SignalR JavaScript Library v1.0.0
This file has some methods to connect to hub, consists:
$.hubConnection.prototype.createHubProxies = function () {
var proxies = {};
this.starting(function () {
// Register the hub proxies as subscribed
// (instance, shouldSubscribe)
registerHubProxies(proxies, true);
this._registerSubscribedHubs(); .......
That lack of this method caused your error:
Cannot read property 'counterHub' of undefined
Because it can not connect to hob and create objec named counterHub.
So please test this: After loading your application in another tab of your browser test this url:
Your-App-Url/signalr/hubs
That in local host is some thing like this:
http://localhost:53398/signalr/hubs
And see if you get the javascript file or not. If not I suggest you to start another project(If it is test).
why $.connection.connectionhub is undefined, am using webform.
<script src="/scripts/jquery-1.6.4.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/signalr/hubs"></script>
<!--Add script to update the page and send messages.-->
<script type="text/javascript">
$(function () {
$.connection()
// why it is undefined
var chat = $.connection.connectionhub;
---------------------------Hub Class------------------------------
public class ConnectionHub : Microsoft.AspNet.SignalR.Hub
{
public void Hello()
{
Clients.All.hello();
}
public void SendMessage()
{
}
}
------------------------Scripts----------------------------------
I have found the solution, but am not satisfy what is the behavior of this code? any one can elaborate it?
when I write below code it works fine
var hubb = $.connection.connectionHub;
when I write the code
//only h is small it can't work
var hubb = $.connection.connectionhub;
can any one explain logic here??
snap shot of code
So I need to send an attachment to a document, but I have to validate if it is larger than 15mb , for so I am using this code in javascript to get the file :
var objFSO = new ActiveXObject("Scripting.FileSystemObject");
var filePath = document.getElementById(fileid).value;
var objFile = objFSO.getFile(filePath);
var fileSize = objFile.size; //size in kb
I'm having an error when I try to create ActiveXObject because my site is not "trusted " by not having a Mark of the Web
<!doctype html>
<!-- saved from url=(0023)http://www.contoso.com/ -->
<html>
<head>
<title>A Mark of the Web Example.</title>
</head>
<body>
<p>Hello, World</p>
</body>
</html>
so I wonder if it is possible to have a mark of the web in a XPage and how I could put it the body of the XPage.
My client does not want to manually place the security option , but want to use IE , please help me haha.
If there is another way to check the file size when selecting a file using javascript would be interesting.
Try this code to check file size in HTML5 should work in all modern browsers
var fileSize=0
if (typeof FileReader !== "undefined") {
var filePath = document.getElementById(fileid);
fileSize= filePath.files[0].size;
}
Check the filesize var for the max limit of you file.
Use this code if the browser is IE10 or newer and your old code if the browser is older.
You can create a Java validator for old browsers, but if the Javascript API is available (modern browsers), use it.
public class Attachment implements Validator {
private final static long BYTES_IN_1_MB = 1048576;
private final static long MAX_MB_ALLOWED = 10;
private final static String MSG_ERROR_SIZE = "File size cannot be bigger than {0} MBs";
public void validate(FacesContext fc, UIComponent uiComp, Object attach)
throws ValidatorException {
FacesMessage msg;
UploadedFile upFile = (UploadedFile) attach;
long max_bytes = BYTES_IN_1_MB * MAX_MB_ALLOWED;
// SIZE:
if (upFile.getContentLength() > max_bytes) {
String msgError = MSG_ERROR_SIZE.replace("{0}", String.valueOf(MAX_MB_ALLOWED));
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msgError, msgError);
throw new ValidatorException(msg);
}
}
}
These validators need to be added into the faces-config.xml
<validator>
<validator-id>attachmentValidator</validator-id>
<validator-class>com.faces.validator.Attachment</validator-class>
</validator>
Then you can add the validator into the fileUpload field:
<xp:this.validators>
<!-- Validator for Attachments -->
<xp:validator validatorId="attachmentValidator">
</xp:validator>
</xp:this.validators>
I can't seem to get websocket communication to work in the Play Framework version 2.1.
I created a simple test that does nothing but send messages back and forth with a push of a button. All the code for it is below. But nothing shows up except for the button.
Has anybody seen this problem or can someone tell me what I may be doing wrong in the code below?
I am using the latest version of Chrome.
Here is my simple setup.
In Application.java
public static Result index() {
return ok(index.render());
}
public static WebSocket<String> sockHandler() {
return new WebSocket<String>() {
// called when the websocket is established
public void onReady(WebSocket.In<String> in,
WebSocket.Out<String> out) {
// register a callback for processing instream events
in.onMessage(new Callback<String>() {
public void invoke(String event) {
System.out.println(event);
}
});
// write out a greeting
out.write("I'm contacting you regarding your recent websocket.");
}
};
}
In Routes File
GET / controllers.Application.index()
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.at(path="/public", file)
GET /greeter controllers.Application.sockHandler()
In Index.Scala.html
#main(null) {
<div class="greeting"></div>
<button class="send">Send</button>
<script type="text/javascript" charset="utf-8">
$(function() {
var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket
var sock = new WS("#routes.Application.sockHandler()")
sock.onmessage = function(event) {
$('.greeting').append(event.data)
}
$('button.send').click(function() {
sock.send("I'm sending a message now.")
});
})
</script>
}
In Main.scala.html
#(title: String)(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>#title</title>
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="#routes.Assets.at("images/favicon.png")">
<script src="#routes.Assets.at("javascripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
</head>
<body>
#content
</body>
The problem is in
var sock = new WS("#routes.Application.sockHandler()")
you have to specify the protocol and the complete url in the format: ws://localhost:9000/greeter.
Check this question to do it in javascript: How to construct a WebSocket URI relative to the page URI?
you can use a Route's webSocketURL() method to retrieve a url that can be passed to a WebSocket's constructor. Here's an example from Play's websocket-chat sample code:
$(function() {
var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket
var chatSocket = new WS("#routes.Application.chat(username).webSocketURL()")
var sendMessage = function() {
chatSocket.send(JSON.stringify(
{text: $("#talk").val()}
))
$("#talk").val('')
}
// ...
So in your code you can use something like
var sock = new WS("#routes.Application.sockHandler().webSocketURL()");
Personally I don't like intermingling interpolated code with JS, since I think that any code executing on the client should only be concerned with the state of the client, and not the server (not to mention it makes refactoring the script out into an external file impossible), so I tend to do something like this:
<div class="container app-container"
data-ws-uri="#routes.Application.WSUri.webSocketURL()">
.......
</div>
Then in my JS I can just do something like
var sock = new WS(document.querySelector(".app-container").dataset.wsUri);
// ....