MVC not functioning on server /signalr/hubs - asp.net-mvc

I have a project that uses SignalR (uses tutorial from https://gkulshrestha.wordpress.com/2014/05/02/signalr-with-sql-server-query-notification/)
When I run it from visual studio, my project works perfectly. However, when I run it on a server (after having published it and with IIS), it doesn't work.
Specifically, I found out that a certain part of the JS is not running.
I have
#section Scripts{
<script src="/Scripts/jquery.signalR-2.1.1.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
// Reference the auto-generated proxy for the hub.
alert(1);
var clientHub = $.connection.messageSender;
alert(5);
// Create a function that the hub can call back to display messages.
clientHub.client.broadcastMessage = function (message) {
// Add the message to page.
$('#messagecontainer').append('<li>' + message + '</li>');
};
alert(2);
$.connection.hub.start().done(function () {
alert("connection started")
}).fail(function (e) {
alert(e);
});
alert(3);
});
</script>
}
When running this through visual studio, I hit all the alerts in here. When running it on the server (by pressing Browse), I only hit alert(1) and none of the others.
Any help would be appreciated! Thanks!
[edit]
I've looked around and I'm suspecting it has to do with my signalr/hubs reference. I've tried everything on SignalR /signalr/hubs 404 Not Found but no luck.

Try using helpers when including static resources:
<script src="#Url.Content("~/Scripts/jquery.signalR-2.1.1.js")"></script>
and:
<script src="#Url.Content("~/signalr/hubs")"></script>
This will take into account the virtual directory in which your application might be running in IIS. Also if you are using the latest Razor you could just prefix with ~ to indicate the relative path:
<script src="~/Scripts/jquery.signalR-2.1.1.js"></script>
and:
<script src="~/signalr/hubs"></script>

Related

Not able to integrate AWS lex with web

Here is my index.html file. I have required loading lex-web-ui.js and config.js files in script but still getting the error.
The error I am getting is ChatBotUiLoader is not defined
<html>
<head>
<title>My Parent Page</title>
</head>
<body>
<h1>Welcome to my parent page</h1>
<!-- loader script -->
<script src="./dist/lex-web-ui.js"></script>
<script>
/*
The loader library creates a global object named ChatBotUiLoader
It includes the IframeLoader constructor
An instance of IframeLoader has the load function which kicks off
the load process
*/
// options for the loader constructor
var loaderOptions = {
// you can put the chatbot UI config in a JSON file
configUrl: './config.json',
// the full page chatbot UI that will be iframed
iframeSrcPath: './chatbot-index.html#/?lexWebUiEmbed=true'
};
// The following statement instantiates the IframeLoader
var iframeLoader = new ChatBotUiLoader.IframeLoader(loaderOptions);
// chatbot UI config
// The loader can also obtain these values from other sources such
// as a JSON file or events. The configUrl variable in the
// loaderOptions above can be used to put these config values in a file
// instead of explicitly passing it as an argument.
var chatbotUiConfig = {
ui: {
// origin of the parent site where you are including the chatbot UI
// set to window.location.origin since hosting on same site
parentOrigin: window.location.origin,
},
iframe: {
// origin hosting the HTML file that will be embedded in the iframe
// set to window.location.origin since hosting on same site
iframeOrigin: window.location.origin,
},
cognito: {
// Your Cognito Pool Id - this is required to provide AWS credentials
poolId: 'xxx'
},
lex: {
// Lex Bot Name in your account
botName: 'xxx'
}
};
// Call the load function which returns a promise that is resolved
// once the component is loaded or is rejected if there is an error
iframeLoader.load(chatbotUiConfig)
.then(function () {
console.log('iframe loaded');
})
.catch(function (err) {
console.error(err);
});
</script>
</body>
</html>
I am trying to integrate AWS lex on my website. I am using this repo https://github.com/aws-samples/aws-lex-web-ui/tree/master/dist
But getting an error: ChatBotUiLoader is not defined. Can anyone help?
enter image description here
Simply, the error is that an instance of ChatBotUiLoader cannot be created as the library/script containing that object was not found within the scope of the page.
It could be that the demo application is broken but the fix is fairly simple.
You need to include the lex-web-ui-loader.js script file (and its dependencies) in your web page to resolve the issue.

Manage URL when debugging from Visual Studio 2015

I have an asp.net mvc site to which I've added some knockoutjs. The knockout code makes ajax request for data from the controllers e.g.
$.getJSON(BASE_URL + 'MyTasks/GetDataPage', { userKey: vm.UserKey, pageSize: pageSize }, function (returnedPayload) {
data = returnedPayload.filter(function (item) {
return JSON.stringify(item).toLowerCase().indexOf(ft) != -1;
});
self.setPagingData(data,page,pageSize);
The BASE_URL constant I set in the <head> of my layout razor page as follows:
<script type="text/javascript">
var BASE_URL = '/bamportal/';
</script>
All works fine when the website is deployed. However, when I run the website from VS by hitting F5 then I get a 404 such as:
http://localhost:49601/bamportal/MyTasks/GetDataPage?userKey=2&pageSize=50 Failed to load resource
If it had tried to address "http://localhost:49601/MyTasks/GetDataPage" (without the "/bamportal/") it would work.
What's the best solution for this problem?
Quick and dirty:
<script type="text/javascript">
var BASE_URL = '#Constants.BaseUrl';
</script>
where Constants is a static class defined as:
public static class Constants {
#if DEBUG
public const string BaseUrl = "/";
#else
public const string BaseUrl = "/bamportal/";
#endif
}
So when you compile your application in debug configuration you will get /, while in release you will get /bamportal/.
As alternative, a more complex and versatile approach could be obtained using Configuration Transforms and appSettings from Web.config:
<script type="text/javascript">
var BASE_URL = '#System.Configuration.ConfigurationManager.AppSettings["BaseUrl"];';
</script>
This, of course, will be extremely useful in scenarios where you need to deploy front-end and back-end on different domains/urls.
Your code should never know where the site will be hosted, you should use the correct helpers to determine where the action/content is located, this will prevent any issues with paths. Use Url.Content and Url.Action they will generate the correct path/url in the code.
As an example your action needs to point to the "MyTasks", "GetDataPage"
In your razor code you should have something like
<div id="urls" data-url="#Url.Action("ActionMethodName","YourControllerName")"></div>
Then in your get code get that stored url
$.getJSON($("#urls").data("url"),
To elaborate further this code will work on any environment (production, debug, iis, any location) without any developer worry or tweaking with config files or any other process. Tomorrow if you need to host your site on "osportal" not "bamportal" no changes need to be made, this should not be part of your code base.
One of the biggest benefits is that if the controller or action ever change the compiler will let you know that the url does not exist and you can fix it. Hardcoding paths/urls/location is a very bad/unmaintainable practice.

Get value from script to var in mvc

I Have This Script:
<script language="JavaScript" src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>
&&
<script type="text/javascript">
geoplugin_countryName();
geoplugin_countryCode();
</script>
this fun
#{
var current = Model.Where(f => f.CurrentRegion == "CurrentRegion" );
}
How can i make (CurrentRegion) = geoplugin_countryCode();
Note that the other does not work outside the script
#ViewBag.CurrentRegion = geoplugin_countryCode(); ///// Does not bring value
The name of this great website in value in the meaning of the need to ask for help
It does not work that way because the c# code in your view gets executed in the server while your javascript executes in the client side.
What you can do is keep 2 pages, In page1, execute your javascript and get the country code from your javascript function, then use that as a querystring param to naivgate to second page(Action method) where you will accept this country code in a parameter and do whatever you want.
So in your first page(view),
<script language="JavaScript" src="http://www.geoplugin.net/javascript.gp"
type="text/javascript"></script>
<script>
var countryCode = geoplugin_countryCode();
window.location.href="#Url.Action("SecondPage","YourControllerName")?country=" +
countryCode'
</script>
and the SecondPage action method
public ActionResult SecondPage(string country)
{
// use country to populate your view model
// to do : return something
}
You would need to POST this information back to the controller or make an AJAX request to a local web service that would know how to process the information.
Using JavaScript you can store the information in hidden input fields on the page and then POST that information back with page data you are submitting normally.

MVC receive post from another website - Chrome says Post Cancelled

I am posting via a plain html text file on c:\ drive into my mvc website running on my machine:
<body>
<a id="testPost" href="./post_files/post.htm">test post</a>
<script type="text/javascript">
$("#testPost").click(function () {
$.post("http://hml.backend/Helix/Authorisation",
{
ClientIP: "192.168.20.34"
}, function (resultData) {
alert(resultData);
});
return false;
});
the controller is setup thus:
[HttpPost]
public ActionResult Authorisation(string ClientIP)
{
string result = _videoSecurityService.CheckHelixAuthorisation(ClientIP);
return Content(result);
}
The controller event gets hit in debug and there is no exception but Chrome says
'POST: Cancelled' in the debug window
Any ideas why?
This is a cross domain call and is not allowed in a lot of browsers, since it's a possible security risk. You could try to redirect your call on the server-side. (make the call to your own application and handle the request-response to the other website there)

using SignalR with document onload instead of jquery onload

I have used the signalR chat app (as laid out in this tutorial http://sergiotapia.com/2011/09/signalr-with-mvc3-chat-app-build-asynchronous-real-time-persistant-connection-websites/) in a standalone test site and it all works great.
I'm now trying to incorporate it into my larger project.
Now unfortunately my larger project has a body onload function defined, so i don't use the standard jquery $(function () {}); syntax for executing stuff on page load. This hasn't been too much of an issue so far, most jquery plugins and scripts get executed in the function called by my body onload and its fine.
But for some reason, my signalR code just isn't executing.
Its the exact same code as laid out above, only its called on my body load.
The page loads, does a post to /signalr/negotiate (which returns the url and clientID)
In my sample app which works, it then does a continuous post to /signalr/connect
In my other app, it simply does a single get to the page im currently on.
Its not making the post to connect.
Is there a way to manually call this?
Here is the source of the page not working.
Please note that the reason im not referencing JQuery itself is because its loaded in my master page. JQuery is present.
<script src="/public/javascript/jquery.signalR.min.js">
<script src="/public/javascript/json2.js">
<script type="text/javascript" src="/signalr/hubs">
<div>
<input type="text" id="msg" />
<input type="button" id="broadcast" />
<ul id="messages"></ul>
</div>
<script type="text/javascript">
function ExecuteOnLoad() {
// Proxy created on the fly
var chat = $.connection.chat;
// Declare a function on the chat hub so the server can invoke it
chat.addMessage = function (message) {
$('#messages').append('<li>' + message + '</li>');
};
$("#broadcast").click(function () {
// Call the chat method on the server
chat.send($('#msg').val());
});
// Start the connection
$.connection.hub.start();
}
</script>
EDIT : here is the chat hub
public class Chat : SignalR.Hubs.Hub
{
public void Send(string message)
{
//Call the addMessage method on all clients.
Clients.addMessage(message);
}
}
DOUBLE EDIT : ok, i've made a standard html page in my mvc project and wired up the onload event again and everything works fine. the problem seems to be that polling doesn't seem to working when i call
$.connection.hub.start();
instead its doing a get to the current url and returning the page again in the get request.
The problem had nothing to do with the question I asked.
I thought it might have to do with the onload function, but it did not.
The problem was because my page had a reference to the Jquery.Validate plugin.
The version I was using was 1.7, I updated to 1.9 of the plugin and it worked fine.

Resources