XDomainRequest open not working on clients IE8 machine - xdomainrequest

Can anyone tell me why XDomainRequest is not working on my clients login computers?
It works on my IE9 and my servers.
It works on their servers but will not work on their IE8 logins
function CreateCrossDomainMessage(ExecuteExternalWebServiceClass, EndpointAddress, PostData) {
alert("Testing XDomainRequest");
var xdr = new XDomainRequest();
xdr.open("POST", EndpointAddress); // Does not open on clients computer, works on their servers ????
xdr.timeout = 2000;
xdr.ontimeout = function () {
alert("ontimeout");
};
xdr.onerror = function () {
alert("onerror");
};
xdr.onload = function () {
alert("onload");
};
xdr.send(PostData);
// new CrossDomainMessage(ExecuteExternalWebServiceClass, EndpointAddress, PostData);
}

Related

read consecutive web pages with CefSharp

What should I do to be able read several consecutive pages from a web site? I am working with CefSharp WinForms and my problem is: In the loop I can get the source from the first page, but any other page gives only part of the source.
I use settings:
CefSettings settings = new CefSettings();
settings.CefCommandLineArgs.Add("enable-media-stream", "1");
settings.CefCommandLineArgs.Add("no-proxy-server", "1");
settings.CefCommandLineArgs.Add("disable-web-security", "1");
settings.CefCommandLineArgs.Add("allow-file-access-from-files", "1");
Cef.Initialize(settings);
And use
public static Task LoadPageAsync(this IWebBrowser browser, string address = null)
{
var tcs = new TaskCompletionSource<bool>();
EventHandler<LoadingStateChangedEventArgs> handler = null;
handler = (sender, args) =>
{
//Wait for while page to finish loading not just the first frame
if (!args.IsLoading)
{
browser.LoadingStateChanged -= handler;
tcs.TrySetResult(true);
}
};
browser.LoadingStateChanged += handler;
if (!string.IsNullOrEmpty(address))
{
browser.Load(address);
}
return tcs.Task;
}

SignalR : How can I broadcast message to Other page of the application

I am creating a test app, where one can download some files and on download success notification will be propagated to admin ,something like notification in
www.ge.tt,or panel notification in Facebook.
I have two pages
a)Download.aspx
b)LandingPage.aspx
In Download.aspx
function PushNotification() {
alert("I ran Upto Here");
//Declare a proxy to Reference a Hub
var notification = $.connection.notificationHub;
//Start a Connection
$.connection.hub.start().done(function () {
notification.server.send(21);
//$("#hdnFileId").val()
alert("I ran Upto Here 2 ");
});
notification.client.broadcastMessage = function (FileID) {
alert("file was Downloaded" + FileID);
};
}
Here two different tabs/browser are working Fine showing alert message if page Loads.
but i want to use the brodcast message in my LandingPage.aspx
here is the Js
$(function () {
var notification = $.connection.notificationHub;
notification.client.broadcastMessage = function (FileID) {
alert("file was Downloaded" + FileID);
};
});
And my hubclass ..
namespace TestApplication.Entities
{
public class NotificationHub : Hub
{
//public void Hello()
//{
// Clients.All.hello();
//}
public void Send(int FileID)
{
Clients.All.broadcastMessage(FileID);
}
}
}
but the notification is not coming here, whats wrong Here?
You didn't start connection in LandingPage.aspx
Try like this in LandingPage.aspx
var notification = $.connection.notificationHub;
$.connection.hub.start();
notification.client.broadcastMessage = function (FileID) {
alert("file was Downloaded" + FileID);
};

Older asynchronous messages overwriting newer ones

We are developing a document collaboration tool in SignalR where multiple users can update one single WYSIWYG form.
We are struggling getting the app to work using the KeyUp method to send the changes back to the server. This causes the system to overwrite what the user wrote after his first key stroke when it sends the message back.
Is there anyway to work around this problem?
For the moment I tried to set up a 2 seconds timeout but this delays all updates not only the "writer" page.
public class ChatHub : Hub
{
public ChatHub()
{
}
public void Send(int id,string message)
{
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(id,message); //id is for the document id where to update the content
}
}
and the client:
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
//console.log("Declare a proxy to reference the hub.");
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (id, message) {
var encodedValue = $('<div />').text(id).html();
// Add the message to the page.
if (encodedValue == $('#hdnDocId').val()) {
$('#DiaplayMsg').text(message);
tinyMCE.activeEditor.setContent("");
tinyMCE.get('txtContent').execCommand('insertHTML', false, message); //!!!
}
};
// Start the connection.
$.connection.hub.start().done(function (e) {
//console.log("Start the connection.");
if ($('#hdnDocId').val() != '') {
tinyMCE.activeEditor.onKeyUp.add(function (ed, e) {
var elelist = $(tinyMCE.activeEditor.getBody()).text();
var content = tinyMCE.get('txtContent').getContent();
function Chat() {
var content = tinyMCE.get('txtContent').getContent();
chat.server.send($('#hdnDocId').val(), content); //send a push to server
}
typewatch(Chat, 2000);
});
}
});
});
var typewatch = function () {
var timer = 0;
return function (Chat, ms) {
clearTimeout(timer);
timer = setTimeout(Chat, ms);
}
} ();
</script>
Hello, here is an update of the client KeyUp code. It seems to be working but I would like your opinion. I've used a global variable to store the timeout, see below:
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
//console.log("Declare a proxy to reference the hub.");
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (id, message) {
var encodedValue = $('<div />').text(id).html();
var currenttime = new Date().getTime() / 1000 - 2
if (typeof window.istyping == 'undefined') {
window.istyping = 0;
}
if (encodedValue == $('#hdnDocId').val() && window.istyping == 0 && window.istyping < currenttime) {
function Update() {
$('#DiaplayMsg').text(message);
tinyMCE.activeEditor.setContent("");
tinyMCE.get('txtContent').execCommand('insertHTML', false, message); //!!!
// tinyMCE.get('txtContent').setContent(message);
window.istyping = 0
}
Update();
}
};
// Start the connection.
$.connection.hub.start().done(function (e) {
//console.log("Start the connection.");
if ($('#hdnDocId').val() != '') {
tinyMCE.activeEditor.onKeyUp.add(function (ed, e) {
var elelist = $(tinyMCE.activeEditor.getBody()).text();
var content = tinyMCE.get('txtContent').getContent();
function Chat() {
//alert("Call");
var content = tinyMCE.get('txtContent').getContent();
chat.server.send($('#hdnDocId').val(), content);
window.istyping = new Date().getTime() / 1000;
}
Chat();
});
}
});
});
var typewatch = function () {
var timer = 0;
return function (Chat, ms) {
clearTimeout(timer);
timer = setTimeout(Chat, ms);
}
} ();
Thanks,
Roberto.
Is there anyway to work around this problem?
Yes, by not sending the entire document to the server, but document elements like paragraphs, table cells, and so on. You can synchronize these after the user has stopped typing for a period, or when focus is lost for example.
Otherwise add some incrementing counter to the messages, so older return values don't overwrite newer ones arriving earlier.
But you're basically asking us to solve a non-trivial problem regarding collaborated document editing. What have you tried?
"This causes the system to overwrite what the user wrote"
that's because this code isn't making any effort to merge changes. it is just blindly overwriting whatever is there.
tinyMCE.activeEditor.setContent("");
tinyMCE.get('txtContent').execCommand('insertHTML', false, message);
as #CodeCaster hinted, you need to be more precise in the messages you send - pass specific changes back and forth rather re-sending the entire document - so that changes can be carefully merged on the receiving side

SignalR - Javascript Hub Proxies

When you use SignalR, in your HTML you need to reference the following two scripts:
<script src="~/Scripts/jquery.signalR-1.0.0.js"></script>
<script src="/signalR/hubs"></script>
The second one is for a JavaScript hub proxy which will be auto generated. Everything works fine. However what happens if the JavaScript Hub Proxy generation is disabled somehow, perhaps by setting DisableJavaScriptProxies property (https://github.com/SignalR/SignalR/commit/7e974f4e92551a26f3e3e0a166e1dbf6c064e850). When JavaScript proxy generation is disabled and you try to reference /signalr/hubs in your HTML, it gives the JavaScript error:
Uncaught Error: SignalR: JavaScript Hub proxy generation has been disabled.
When I browse to that path in the browser, the response is:
throw new Error('SignalR: JavaScript Hub proxy generation has been disabled.')
If the JavaScript proxy generation is disabled, how is the $.connection.myHub.client JavaScript code going to work? What extra do I have to do to make it work? The JavaScript error I get is
Uncaught TypeError: cannot read property 'client' of undefined.
You can create the proxies yourself. See here.
This is also done in the samples project within the SignalR source. See the MouseTracking example. JS for it (from here):
/// <reference path="../../Scripts/jquery-1.8.2.js" />
/// <reference path="../../Scripts/jquery.signalR.js" />
$(function () {
var hubConnection = $.hubConnection('/signalr', { qs: 'test=1', logging: false, useDefaultPath: false }),
hub = hubConnection.createHubProxy('mouseTracking');
hub.on('move', updateCursor);
function updateCursor(id, x, y) {
var e = document.getElementById(id);
if (!e) {
e = $('<div id="' + id + '"><i class="icon-screenshot"></i>' + id + '</div>').appendTo(document.body);
e.css('position', 'absolute');
}
else {
e = $(e);
}
e.css({ left: x + 15, top: y + 15 });
}
hubConnection.logging = true;
hubConnection.start({ transport: activeTransport })
.pipe(function () {
return hub.invoke('join');
})
.pipe(function () {
$(document).mousemove(function (e) {
hub.invoke('move', e.pageX, e.pageY);
updateCursor(hub.state.id, e.pageX, e.pageY);
});
});
});
You may have disabled it in your Startup class, like so:
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
var hubConfiguration = new HubConfiguration();
hubConfiguration.EnableDetailedErrors = true;
hubConfiguration.EnableJavaScriptProxies = false;
app.MapSignalR("/signalr", hubConfiguration);
}
}
I had the code above. Removing/commenting out this line: hubConfiguration.EnableJavaScriptProxies = false; should give you proxy generation.
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
var hubConfiguration = new HubConfiguration();
hubConfiguration.EnableDetailedErrors = true;
app.MapSignalR("/signalr", hubConfiguration);
}
}
For everybody who stumbles on this issue. It seems to be by design, and even the SignalR utility generates only server proxy methods.
It will not create client methods, even if you have a strongly typed Hub (Client interface).
So, the only correct answer, should be that you should generate small functions, as documented at Microsoft.
As in the stockticker sample:
$.connection.hub.start()
.then(init)
.then(function () {
return ticker.server.getMarketState();
})
.done(function (state) {
if (state === 'Open') {
ticker.client.marketOpened();
} else {
ticker.client.marketClosed();
}
The stockticker itself is defined like this
public class StockTickerHub : Hub
and the interface
public interface IClientStock
{
void MarketOpened();
void MarketClosed();
void MarketReset();
void UpdateStockPrice(Stock stock);
}
So for each client proxy method, repeat this. This should not break any bodies project targets.
$.extend(ticker.client, {
updateStockPrice: function (stock) {
var displayStock = formatStock(stock),
$row = $(rowTemplate.supplant(displayStock)),
$li = $(liTemplate.supplant(displayStock)),
bg = stock.LastChange < 0
? '255,148,148' // red
: '154,240,117'; // green
$stockTableBody.find('tr[data-symbol=' + stock.Symbol + ']')
.replaceWith($row);
$stockTickerUl.find('li[data-symbol=' + stock.Symbol + ']')
.replaceWith($li);
$row.flash(bg, 1000);
$li.flash(bg, 1000);
},
marketOpened: function () {
$("#open").prop("disabled", true);
$("#close").prop("disabled", false);
$("#reset").prop("disabled", true);
scrollTicker();
},

Close/kill the session when the browser or tab is closed

Can somebody tell me how can I close/kill the session when the user closes the browser? I am using stateserver mode for my asp.net web app. The onbeforeunload method is not proper as it fires when user refreshes the page.
You can't. HTTP is a stateless protocol, so you can't tell when a user has closed their browser or they are simply sitting there with an open browser window doing nothing.
That's why sessions have a timeout - you can try and reduce the timeout in order to close inactive sessions faster, but this may cause legitimate users to have their session timeout early.
As said, the browser doesn't let the server know when it closes.
Still, there are some ways to achieve close to this behavior. You can put a small AJAX script in place that updates the server regularly that the browser is open. You should pair this with something that fires on actions made by the user, so you can time out an idle session as well as one that has closed out.
As you said the event window.onbeforeunload fires when the users clicks on a link or refreshes the page, so it would not a good even to end a session.
http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx describes all situations where window.onbeforeonload is triggered. (IE)
However, you can place a JavaScript global variable on your pages to identify actions that should not trigger a logoff (by using an AJAX call from onbeforeonload, for example).
The script below relies on JQuery
/*
* autoLogoff.js
*
* Every valid navigation (form submit, click on links) should
* set this variable to true.
*
* If it is left to false the page will try to invalidate the
* session via an AJAX call
*/
var validNavigation = false;
/*
* Invokes the servlet /endSession to invalidate the session.
* No HTML output is returned
*/
function endSession() {
$.get("<whatever url will end your session>");
}
function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function() {
if (!validNavigation) {
endSession();
}
}
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();
});
This script may be included in all pages
<script type="text/javascript" src="js/autoLogoff.js"></script>
Let's go through this code:
var validNavigation = false;
window.onbeforeunload = function() {
if (!validNavigation) {
endSession();
}
}
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
A global variable is defined at page level. If this variable is not set to true then the event windows.onbeforeonload will terminate the session.
An event handler is attached to every link and form in the page to set this variable to true, thus preventing the session from being terminated if the user is just submitting a form or clicking on a link.
function endSession() {
$.get("<whatever url will end your session>");
}
The session is terminated if the user closed the browser/tab or navigated away. In this case the global variable was not set to true and the script will do an AJAX call to whichever URL you want to end the session
This solution is server-side technology agnostic. It was not exaustively tested but it seems to work fine in my tests
Please refer the below steps:
First create a page SessionClear.aspx and write the code to clear session
Then add following JavaScript code in your page or Master Page:
<script language="javascript" type="text/javascript">
var isClose = false;
//this code will handle the F5 or Ctrl+F5 key
//need to handle more cases like ctrl+R whose codes are not listed here
document.onkeydown = checkKeycode
function checkKeycode(e) {
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (e)
keycode = e.which;
if(keycode == 116)
{
isClose = true;
}
}
function somefunction()
{
isClose = true;
}
//<![CDATA[
function bodyUnload() {
if(!isClose)
{
var request = GetRequest();
request.open("GET", "SessionClear.aspx", true);
request.send();
}
}
function GetRequest() {
var request = null;
if (window.XMLHttpRequest) {
//incase of IE7,FF, Opera and Safari browser
request = new XMLHttpRequest();
}
else {
//for old browser like IE 6.x and IE 5.x
request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
}
return request;
}
//]]>
</script>
Add the following code in the body tag of master page.
<body onbeforeunload="bodyUnload();" onmousedown="somefunction()">
I do it like this:
$(window).bind('unload', function () {
if(event.clientY < 0) {
alert('Thank you for using this app.');
endSession(); // here you can do what you want ...
}
});
window.onbeforeunload = function () {
$(window).unbind('unload');
//If a string is returned, you automatically ask the
//user if he wants to logout or not...
//return ''; //'beforeunload event';
if (event.clientY < 0) {
alert('Thank you for using this service.');
endSession();
}
}
Not perfect but best solution for now :
var spcKey = false;
var hover = true;
var contextMenu = false;
function spc(e) {
return ((e.altKey || e.ctrlKey || e.keyCode == 91 || e.keyCode==87) && e.keyCode!=82 && e.keyCode!=116);
}
$(document).hover(function () {
hover = true;
contextMenu = false;
spcKey = false;
}, function () {
hover = false;
}).keydown(function (e) {
if (spc(e) == false) {
hover = true;
spcKey = false;
}
else {
spcKey = true;
}
}).keyup(function (e) {
if (spc(e)) {
spcKey = false;
}
}).contextmenu(function (e) {
contextMenu = true;
}).click(function () {
hover = true;
contextMenu = false;
});
window.addEventListener('focus', function () {
spcKey = false;
});
window.addEventListener('blur', function () {
hover = false;
});
window.onbeforeunload = function (e) {
if ((hover == false || spcKey == true) && contextMenu==false) {
window.setTimeout(goToLoginPage, 100);
$.ajax({
url: "/Account/Logoff",
type: 'post',
data: $("#logoutForm").serialize(),
});
return "Oturumunuz kapatıldı.";
}
return;
};
function goToLoginPage() {
hover = true;
spcKey = false;
contextMenu = false;
location.href = "/Account/Login";
}
It is not possible to kill the session variable, when the machine unexpectly shutdown due to power failure. It is only possible when the user is idle for a long time or it is properly logout.
For browser close you can put below code into your web.config :
<system.web>
<sessionState mode="InProc"></sessionState>
</system.web>
It will destroy your session when browser is closed, but it will not work for tab close.
Use this:
window.onbeforeunload = function () {
if (!validNavigation) {
endSession();
}
}
jsfiddle
Prevent F5, form submit, input click and Close/kill the session when the browser or tab is closed, tested in ie8+ and modern browsers, Enjoy!

Resources