check if website is online - problems with postback - c#

I've got a webpage that people in my company are filling in using mobile handsets. Only problem is, if they move out of a signal area, then when they try and update their work the page will go to a "page not found" and they'll lose the work they've filled in.
I'm trying to remedy this and, at the moment, have this solution:
protected void Button1_Click(object sender, EventArgs e)
{
Session["Online"] = 0;
CheckConnect();
if ((int)Session["Online"] == 1) { Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "alertMessage", "alert('You are currently online')", true); }
if ((int)Session["Online"] == 0) { Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "alertMessage", "alert('You are currently offline')", true); }
}
protected void CheckConnect()
{
System.Uri Url = new System.Uri("http://www.mypage.com/pixel.jpg?" + DateTime.Now);
System.Net.WebRequest WebReq;
System.Net.WebResponse Resp;
WebReq = System.Net.WebRequest.Create(Url);
try
{
Resp = WebReq.GetResponse();
Resp.Close();
WebReq = null;
Session["Online"] = 1;
}
catch
{
WebReq = null;
Session["Online"] = 0;
}
}
Now, this will check if the pixel file at www.mypage.com exists (no, that's not actually my page, I've substituted it for this example) and, if so, it returns a 0, if not a 1. Which is fine and dandy.
However, pressing the button causes the page to be reloaded. Then, if it's offline, it does the usual "page not found" business. My button code is here:
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
Basically, I want it to not reload the page if we're offline (or indeed if we are online, as the code that does the updating handles that part anyway).
EDIT - alright, different approach now. Doing this entirely through javascript using the following:
<asp:Button ID="Button1" runat="server" OnClientClick="ifServerOnline()" Text="Button" />
<script type="text/javascript">
function ifServerOnline(ifOnline, ifOffline)
{
var img = document.body.appendChild(document.createElement("img"));
img.onload = function ()
{
ifOnline && ifOnline.constructor == Function && ifOnline();
};
img.onerror = function ()
{
ifOffline && ifOffline.constructor == Function && ifOffline();
};
img.src = "http://www.mypage.com/pixel.jpg?" + Date.now;
}
ifServerOnline(function ()
{
return confirm('Online');
},
function ()
{
return confirm('Offline');
});
</script>
Unfortunately still causing a page refresh.

In your page's javascript assign form onsubmit event handler, where you cancel default submit. Also, in this event handler, issue an ajax request to the server with a very brief response. In onsuccess event handler of this ajax request - resubmit the form, in onerror handler - tell the user that they lost connection to server.

You can't do postback to the server when you offline.
No way to do it..
But maybe you can do that's with javascript.. try this way.

Managed it with this...
<asp:Button ID="btnRouteC" runat="server" OnClientClick="return ifServerOnlineA(ifServerOnlineA1, ifServerOfflineA1);" Text="Route" Width="45%" />
<script type="text/javascript">
function ifServerOnlineA(ifOnline, ifOffline)
{
var img = document.body.appendChild(document.createElement("img"));
img.onload = function ()
{
ifOnline && ifOnline.constructor == Function && ifOnline();
};
img.onerror = function ()
{
ifOffline && ifOffline.constructor == Function && ifOffline();
};
img.src = "http://www.myserver.com/pixel.jpg?" + Date.now;
return false;
}
function ifServerOnlineA1()
{
document.getElementById('btnRoute').click();
return false;
}
function ifServerOfflineA1()
{
alert("There is no connection at the moment. Please try again later.");
return false;
}
</script>
As Itiel said, it won't work through the codebehind but will through the Javascript.

Related

Cefsharp winforms: Inject jquery into page

I'm using ChromiumWebBrowser to load a website, and after page loaded, I'll execute some script
browser.ExecuteScriptAsync(script)
But that website not use jquery, so difficult to code my script. I want to inject jquery into that site to write my script easier. How can I do it? Thank you very much
EDIT:
I have had a jquery file in my computer. And I would like to add it to the page where I want to crawl data. I tried using LoadingStateChanged event, but not worked.
private void Browser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
{
ChromiumWebBrowser browser = (ChromiumWebBrowser)sender;
lbStatus.SetText(e.IsLoading ? "Loading..." : browser.Address);
if (!e.IsLoading)
{
//Load jquery
}
else
{
}
}
Set this code to script variable as string and then call browser.ExecuteScriptAsync(script)
(function () {
// more or less stolen form jquery core and adapted by paul irish
function getScript(url, success) {
var script = document.createElement('script');
script.src = url;
var head = document.getElementsByTagName('head')[0],
done = false;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function () {
if (!done && (!this.readyState
|| this.readyState == 'loaded'
|| this.readyState == 'complete')) {
done = true;
success();
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
head.appendChild(script);
}
getScript('http://code.jquery.com/jquery-latest.min.js', function () {
if (typeof jQuery == 'undefined') {
console.log('Sorry, but jQuery wasn\'t able to load');
} else {
console.log('This page is now jQuerified with v' + $.fn.jquery);
$(document).ready(function () {
alert(1);
//here you can write your jquery code
});
}
});
})();
i push the entire jquery js-file as inline-code and works great:
browser.ExecuteScriptAsync(File.ReadAllText(#"content\jquery.1.11.1.min.js"));
reduces loading times...
it's very easy :)
string script_1 = "document.getElementsByTagName('head')[0].appendChild(document.createElement('script')).src = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'";
browser.ExecuteScriptAsync(script_1);
and for call any custom jquery function or class:
string script_2 = "$('.contact').css('color','#aabbcc');";
browser.ExecuteScriptAsync(script_2);

Why Jquery is not working for asp.net textbox's CssClass Property?

I am tying to validate the textboxes for achieving 'alphabets only' property in asp.net page with Jquery.
Here is the code
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
.............codes.............
<script type="text/javascript">
$('.alph').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z\s]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
else {
e.preventDefault();
alert('Alphabets only');
return false;
}
});
</script>
.............codes.............
<asp:TextBox ID="txt_name" CssClass="alph" BorderColor="Gray" Font-Size="Large" Height="25" Width="250" runat="server"></asp:TextBox>
This code didn't work and I am sure my computer is connected to the internet to reach code.jquery.com. Help me please.
try this script code after Document.ready block
$(document).ready(function(){
$('.alph').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z\s]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
else {
e.preventDefault();
alert('Alphabets only');
return false;
}
});
});
Before you can safely use jQuery you need to ensure that the page is in a state where it's ready to be manipulated. With jQuery, we accomplish this by putting our code in a function, and then passing that function to $(document).ready(). The function we pass can just be an anonymous function.
My mistake! Since I am new to Jquery I didn't know about 'doc.ready' I corrected the code as
$(document).ready(function () {
$('#<%=txt_name.ClientID %>').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z\s]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
else {
e.preventDefault();
alert('Alphabets only');
return false;
}
});
});
Code works perfect!

asp button is not working for js script

I have js code which gets which gets users lat long but the problem is when I call the js function in my asp.net control button it does not work and no alert is shown and the function getLocation does not work
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
else { x.innerHTML = "Geolocation is not supported by this browser."; }
}
function showPosition(position) {
// var latlondata = position.coords.latitude + "," +position.coords.longitude;
var latlon = position.coords.latitude;
alert(latlon)
document.getElementById('<%=abc123.ClientID%>').innerText = latlon;
}
function showError(error) {
if (error.code == 1) {
x.innerHTML = "User denied the request for Geolocation."
}
else if (err.code == 2) {
x.innerHTML = "Location information is unavailable."
}
else if (err.code == 3) {
x.innerHTML = "The request to get user location timed out."
}
else {
x.innerHTML = "An unknown error occurred."
}
}
and here is my control code
<asp:Label ID="abc123" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="getLocation()" OnClick="Button1_Click " />
The OnClick event will reload the page and therefore the JS called from the OnClientClick will never be triggered. Remove the OnClick event.
Edit:
If you need to trigger the serverside event let your JS trigger it after the alert.
Just add the following code to your button:
OnClientClick="getLocation(); return false;"

return false in firefox causing ajax timing issue i'm thinking

I have a simple ajax page that adds 2 numbers.
When I run in IE, the async callback works.
When I run in Firefox it doesn't work.
I get the correct return value in Firebug but lblSum remains blank in Firefox.
It has something to do with the return false at the end of the btnAdd click handler.
There is a server-side handler in case Javascript is disabled, so in the Javascript I add a return false.
<script type="text/javascript">
var pageWebForm1 = {
txt1: document.getElementById('TextBox1'),
txt2: document.getElementById('TextBox2'),
lblSum: document.getElementById('LblSum'),
btnAdd: document.getElementById('BtnAdd'),
init: function() {
this.btnAdd.onclick = function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
xhrCallback(xhr.responseText);
}
}
xhr.open("POST", "Handler.ashx", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("x=" + pageWebForm1.txt1.value + "&" + "y=" + pageWebForm1.txt2.value);
return false;
}
}
}
pageWebForm1.init();
function xhrCallback(retval) {
pageWebForm1.lblSum.innerText = retval;
}
</script>
It has nothing to do with the return false statement. Your problem is innerText is IE only. Another stackoverflow post on a cross-browser solution.

JQuery Validator Plugin Asp.Net call server method

I use the JQuery Validation plugin to validate a form (http://docs.jquery.com/Plugins/Validation/)
For example, I can validate an email in a form.
What I would like to do is to validate if the username chosen already exists. So, I need to call a server method that query the database. How can I do that ?
UPDATE
From balexandre answer, I try the following :
$.validator.addMethod("userName",
function(value, element)
{
$.get
(
"CheckUser.aspx?User=" + value,
function(data)
{
if (data == "True")
{
return false;
}
else if (data == "False")
{
return true;
}
else
{
alert(data);
}
}
);
},
"User already exists");
$(document).ready
(
function()
{
$("#aspnetForm").validate
(
{
rules:
{
<%=txtUserName.UniqueID %>:
{
required: true,
email: true,
userName: true
}
}
}
);
}
);
In the Response, I write a boolean (True of False) instead of 1 ou 0.
I know that my validation function is call. The problem is that it's always show the error message even if the user doesn't exists. I try to put an alert message before the return true to see if it's reach, and it is. So I don't get, why it's doesn't work...
quite easy and it's a nice thcnique that I apply a lot over my projects
1 - create an aspx page called verifyUserAvailability.aspx with code-behind file
2 - delete all lines except the first in the aspx file
3 - in the code-behind file inside the Page_Load event call your database like
protected void Page_Load(object sender, EventArgs e) {
string username = Request["usr"];
int r = 0;
if(!String.IsNullOrEmpty(username))
if( yourDAL.getUserAvailability(username) )
// your method would send true if user is available to be used
r = 1;
Response.Clear();
Response.Write(r);
Response.Flush();
}
4 - now in your form page, create a button like
<input id="btnCheckAvailability" type="button"
value="Check availability"
onclick="javascript:checkAvailability();" />
5 - create the checkAvailability() method
<script type="text/language">
function checkAvailability() {
var $user = $("#UsernameInputBox");
$.get("verifyUserAvailability.aspx?usr=" + $user.val(), function(data) {
// this will call the page passing the username and return 1 or 0
if( data == "1" )
$user.css("background-color", "green");
else
$user.css("background-color", "red");
});
}
</script>
This should do the trick...
http://riderdesign.com/articles/Check-username-availability-with-JQuery-and-ASP.NET.aspx
OR...
One answer shows how to call a service & the second shows how to call a page method.
Calling an ASP.NET server side method via jQuery

Categories

Resources