client property undefined in SignalR Move Shape demo under IIS 7.5? - javascript

I'm having trouble getting the SignalR demo Move Shape working on IIS 7.5. It works for me on my development PC under IIS express and Visual Studio 2013.
I'm currently copying the Move.html file and /scripts from the project to the wwwroot directory on the IIS 7.5 PC.
When I load the Move.html on the IIS PC from http:// localhost/Move.html, I get the following error in the javascript:
Uncaught TypeError: Cannot read property 'client' of undefined
which is the result of my previous line var moveShapeHub = $.connection.moveShapeHub, returning moveShapeHub as undefined.
Move.html:
<!DOCTYPE html>
<html>
<head>
<title>SignalR MoveShape Demo</title>
<style>
#shape {
width: 100px;
height: 100px;
background-color: #FF0000;
}
</style>
</head>
<body>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script src="Scripts/jquery-ui-1.10.3.min.js"></script>
<script src="Scripts/jquery.signalR-2.1.2.min.js"></script>
<script src="/signalr/hubs"></script>
<script>
$(function () {
var moveShapeHub = $.connection.moveShapeHub,
$shape = $("#shape"),
// Send a maximum of 10 messages per second
// (mouse movements trigger a lot of messages)
messageFrequency = 10,
// Determine how often to send messages in
// time to abide by the messageFrequency
updateRate = 1000 / messageFrequency,
shapeModel = {
left: 0,
top: 0
},
moved = false;
moveShapeHub.client.updateShape = function (model) {
shapeModel = model;
// Gradually move the shape towards the new location (interpolate)
// The updateRate is used as the duration because by the time
// we get to the next location we want to be at the "last" location
// We also clear the animation queue so that we start a new
// animation and don't lag behind.
$shape.animate(shapeModel, { duration: updateRate, queue: false });
};
$.connection.hub.start().done(function () {
$shape.draggable({
drag: function () {
shapeModel = $shape.offset();
moved = true;
}
});
// Start the client side server update interval
setInterval(updateServerModel, updateRate);
});
function updateServerModel() {
// Only update server if we have a new movement
if (moved) {
moveShapeHub.server.updateModel(shapeModel);
moved = false;
}
}
});
</script>
<div id="shape" />
</body>
</html>
So it is able to find the /signalr/hubs and the other definitions but can't resolve the hub under IIS 7.5, but it works under IIS express.
Am I missing some setup under IIS 7.5?
What setup steps are needed under IIS 7.5?
Can this work under IIS 7.5?
Here is the hub code (straight from the demo):
using System;
using System.Threading;
using Microsoft.AspNet.SignalR;
using Newtonsoft.Json;
namespace MoveShapeDemo
{
public class Broadcaster
{
private readonly static Lazy<Broadcaster> _instance =
new Lazy<Broadcaster>(() => new Broadcaster());
// We're going to broadcast to all clients a maximum of 25 times per second
private readonly TimeSpan BroadcastInterval =
TimeSpan.FromMilliseconds(40);
private readonly IHubContext _hubContext;
private Timer _broadcastLoop;
private ShapeModel _model;
private bool _modelUpdated;
public Broadcaster()
{
// Save our hub context so we can easily use it
// to send to its connected clients
_hubContext = GlobalHost.ConnectionManager.GetHubContext<MoveShapeHub>();
_model = new ShapeModel();
_modelUpdated = false;
// Start the broadcast loop
_broadcastLoop = new Timer(
BroadcastShape,
null,
BroadcastInterval,
BroadcastInterval);
}
public void BroadcastShape(object state)
{
// No need to send anything if our model hasn't changed
if (_modelUpdated)
{
// This is how we can access the Clients property
// in a static hub method or outside of the hub entirely
_hubContext.Clients.AllExcept(_model.LastUpdatedBy).updateShape(_model);
_modelUpdated = false;
}
}
public void UpdateShape(ShapeModel clientModel)
{
_model = clientModel;
_modelUpdated = true;
}
public static Broadcaster Instance
{
get
{
return _instance.Value;
}
}
}
public class MoveShapeHub : Hub
{
// Is set via the constructor on each creation
private Broadcaster _broadcaster;
public MoveShapeHub()
: this(Broadcaster.Instance)
{
}
public MoveShapeHub(Broadcaster broadcaster)
{
_broadcaster = broadcaster;
}
public void UpdateModel(ShapeModel clientModel)
{
clientModel.LastUpdatedBy = Context.ConnectionId;
// Update the shape model within our broadcaster
_broadcaster.UpdateShape(clientModel);
}
}
public class ShapeModel
{
// We declare Left and Top as lowercase with
// JsonProperty to sync the client and server models
[JsonProperty("left")]
public double Left { get; set; }
[JsonProperty("top")]
public double Top { get; set; }
// We don't want the client to get the "LastUpdatedBy" property
[JsonIgnore]
public string LastUpdatedBy { get; set; }
}
}
And here is the Startup.cs:
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(MoveShapeDemo.Startup))]
namespace MoveShapeDemo
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Any connection or hub wire up and configuration should go here
app.MapSignalR();
}
}
}

Once you launch your site could you check to see if your hub proxy is getting loaded for /Signalr/hubs. Just hit your URL http:// localhost/SignalR/hubs.You should see the SignalR generated proxy (unless you have turned it off in your Global.asax which it does not look like it because you were able to hit it in IISExpress.
If you can bring up the hub proxy up then just change the following in your HTML, from
<script src="/signalr/hubs"></script>
to
<script src="http:/localhost/signalr/hubs"></script>
You can learn more about SignalR here - really good resource on everything that is signalR.
UPDATE:
You say that when running in visual studio and IIS expresss your Move.html works just fine. What else is in the Visual Studio solution or project as part of Move.html? You have C# code for your hub, have you deployed that? The use of /signalr/hubs suggests that Move.html and the hub are part of the same project, but in your original query you say that you just moved Move.html. You would have to publish the entire project and move that published version to the wwwroot folder. For publishing steps look here

Related

NetBeans: jLabel Icon only working if External?

New here, trying to set an icon for my jLabel but the program doesnt run unless I use an external image as the icon. If i Import the image and try to use that, I run the program and the app window doesnt even pop up
I have tried both having the images in the same package and also tried having the images in its own package
package tankidgroup.test;
public class test1 extends javax.swing.JFrame {
public test1() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/tankidgroup/test/test.JPG"))); // NOI18N
jLabel1.setText("jLabel1");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(159, Short.MAX_VALUE)
.addComponent(jLabel1)
.addGap(170, 170, 170))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(105, 105, 105)
.addComponent(jLabel1)
.addContainerGap(162, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(() -> {
new test1().setVisible(true);
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
// End of variables declaration

SWT Browser not displaying pages using D3

I would like to display a html page that uses D3 in an SWT Browser.
If I load a URL like www.google.com it loads correctly and allows me to search etc. If I try loading a page that contains D3 I find that nothing gets displayed and no errors are output.
Example
public class D3BrowserExample {
public static void main(String args[]) {
Display display = new Display();
final Shell shell = new Shell(display, SWT.SHELL_TRIM);
shell.setLayout(new FillLayout());
Browser browser = new Browser(shell, SWT.NONE);
browser.addTitleListener(new TitleListener() {
#Override
public void changed(TitleEvent event) {
shell.setText(event.title);
}
});
browser.setBounds(0, 0, 1200, 900);
shell.pack();
shell.open();
browser.setJavascriptEnabled(true);
browser.setUrl("https://observablehq.com/#d3/force-directed-graph");
browser.addProgressListener(new ProgressListener() {
#Override
public void completed(ProgressEvent event) {
System.out.println("Page loaded");
}
#Override
public void changed(ProgressEvent event) {
}
});
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
}
Is it possible to execute D3 using an SWT Browser? Also how can I get the Javascript output to debug the issue?
Update
I've tried this on another Windows 10 PC with version 4.3 of SWT. The complete method is called for the progress listener but nothing displays.
Eclipse Bugzilla
https://bugs.eclipse.org/bugs/show_bug.cgi?id=568789

How do i retrieve page information from inside of Unity?

I need to communicate Unity WebAssemly with page in both directions.
This is how I execute Unity functions from page:
<script>
var gameInstance = UnityLoader.instantiate("gameContainer", "https://propper_url/Build/_Builds.json", {onProgress: UnityProgress});
function unityObjectFun(index)
{
gameInstance.SendMessage ("ObjectInstance", "objectFunctionName", index);
}
</script>
<a onclick="unityObjectFun(1)">invoke</a>
<div class="webgl-content">
<div id="gameContainer" myValue="need this to read from Unity"></div>
</div>
But how can I do in reverse. Is it possible to retrieve myValue from Unity.
Alternatively is it possible to notify page that Unity loaded scene and started playing it so I could send to it myValue?
To perform any JavaScript code on a page from the Unity WebAssembly there are two things required:
Create the Javascript code as plugin.
Import the code in Unity script.
The whole procedure is described in this guide: https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html.
The plugin code must reside in Assets/Plugins/pluginname.jslib path (the extension is important) and have similar structure:
mergeInto(LibraryManager.library, {
Hello: function () {
window.alert("Hello, world!");
},
HelloReturn: function () {
return "Hello, world!";
}
}
To use it there is required import:
using System.Runtime.InteropServices;
public class NewBehaviourScript : MonoBehaviour {
[DllImport("__Internal")]
private static extern void Hello();
[DllImport("__Internal")]
private static extern string HelloReturn();
void Start() {
Hello();
Debug.log(HelloReturn());
}
}

Awesomium .NET. Wpf. TitleChanged event

I have a very basic application, that shows website content within the WPF app. Everything works fine, except TitleChangedEvent. Here is the code sample (XAML):
<Window xmlns:awe="http://schemas.awesomium.com/winfx" x:Class="ShopChat.Desktop.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:webControls="clr-namespace:System.Web.UI.WebControls;assembly=System.Web"
Title="{Binding ElementName=WebControl, Path=Title}" MinHeight="480" MinWidth="640">
<Grid>
<awe:WebControl x:Name="WebControl"/>
</Grid>
And this is main window code-behind:
public MainWindow()
{
InitializeComponent();
string url = #"http://shopchat.dev";
try
{
url = ConfigurationManager.AppSettings.Get("Url");
}
catch (Exception)
{
}
WebControl.Source = new Uri(url);
WebControl.TitleChanged += WebControl_OnTitleChanged;
this.WindowTitle = "Quickchat";
}
public string WindowTitle
{
get { return (string)GetValue(WindowTitleProperty); }
set { SetValue(WindowTitleProperty, value); }
}
// Using a DependencyProperty as the backing store for WindowTitle. This enables animation, styling, binding, etc...
public static readonly DependencyProperty WindowTitleProperty =
DependencyProperty.Register("WindowTitle", typeof(string), typeof(MainWindow), new PropertyMetadata(null));
private void WebControl_OnTitleChanged(object sender, TitleChangedEventArgs e)
{
this.WindowTitle = e.Title;
}
I've also tried to bind to window title directly using Binding ElementName=WebControl. That didn't help me either.
JavaScript client code is very simple: it changes the document title on timer (setInterval).
What am I doing wrong?
try like this code
public MainWindow()
{
InitializeComponent();
DataContext = this;
MyTitle = "Title";
}
Then you just need in the XAML
Title="{Binding MyTitle}"
Then you don't need the dependency property.
Then I would like to use this INotifyPropertyChanged with a standard property.
The issue was solved. TitleChanged event seemed to be insufficient. I've incorporated the usage of global js object to get the necessary behavior.

How to catch element click by ID in Android webview?

I have the viewPager component which is containing the several webviews with HTML content from remote server.
Is it simple HTML code without possibility to change the HTMl output on the server side.
I would like to ask, how can i catch the click(tap) event on the specified element with the given ID in Android?
ViewPager
private void initViewPager() {
pager = (ViewPager) findViewById(R.id.my_pager);
adapter = new FragmentStatePagerAdapter(
getSupportFragmentManager()
) {
#Override
public int getCount() {
// This makes sure getItem doesn't use a position
// that is out of bounds of our array of URLs
Logger.d(String.valueOf(mWelcomeController.loadedPagesToDisplay.size()));
return mWelcomeController.loadedPagesToDisplay.size();
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
Logger.d(mWelcomeController.loadedPagesToDisplay.toString());
return BrowserFragment.newInstance(
mWelcomeController.loadedPagesToDisplay.get(position)
);
}
};
//Let the pager know which adapter it is supposed to use
pager.setAdapter(adapter);
}
Because I cannot modify the HTML output on the server side (maybe inject some attributes into DOM on device ?) I cannot use something like that:
http://www.scriptscoop.com/t/21b53b896c9e/javascript-how-to-detect-button-click-in-webview-android.html
Detect click on HTML button through javascript in Android WebView.
I would like just something like this:
Find the given element in the HTML code
Update the HTML code (add
onclick event)
Catch this event in native code
For that you need to parse the html, a good html parser for Java (and therefor also Android) is Jsoup.
You can do something like:
// Connect to the web site
Document doc = Jsoup.connect(url).get();
Element button = doc.select("#buttonid");
button.html("new stuff here");
//parse back and put in webview
String finaloutput = doc.html();
1.
// setting
wv.addJavascriptInterface(new MyJsToAndroid(),"my");
WebSettings settings = wv.getSettings();
settings.setJavaScriptEnabled(true);
2.
// JsCallBack
class MyJsToAndroid extends Object{
#JavascriptInterface
public void myClick(String idOrClass) {
Log.d(TAG, "myClick-> " + idOrClass);
}
}
3.
// JS--
public static String addMyClickCallBackJs() {
String js = "javascript:";
js += "function myClick(event){" +
"if(event.target.className == null){my.myClick(event.target.id)}" +
"else{my.myClick(event.target.className)}}";
js += "document.addEventListener(\"click\",myClick,true);";
return js;
}
4.
#Override
public void onPageFinished(WebView wv, String url) {
//...
wv.evaluateJavascript(addMyClickCallBackJs(),null);
//...
}
So, look at the 2 log.

Categories

Resources