Detect If Offline - in C# WebBrowser component? - c#

We're working on a wrapped WebBrowser component. We'd like to display one page (e.g. oursite.com/thispage.html) if the user is online and another page (e.g. C:\somewhere\thispage_offline.html) if the user is offline. I'm able to to properly display both pages, but my issue is detecting the online/offline status.
I tried
WebBrowser.IsOffline; however it seems that only relays the Offline Mode status, not whether or not the computer is actually able to reach the internet.
Is there a way to detect this from the WebBrowser component? Is there a way at all?
Thanks for all your help!

The simplest way to check for internet connectivity is to ping your server.
Try this code:
public static bool IsOnline() {
var pinger = new Ping();
try {
return pinger.Send("oursite.com").Status == IPStatus.Success;
} catch(SocketException) { return false; } catch(PingException) { return false; }
}
Alternatively, you can try using the WebRequest class to send a request to a simple page on your site and see whether it succeeds. This is a better option because it will also make sure that IIS (or Apache) is running on the server.

What if you just used the Ping class to see if the site is available?

Related

Uniquely identify machine in web application using asp.net c#

I have one login page, user can use any machine while login into that page for the first time. once the user logged in for the first time, i need to restrict that user to not login into another machine. So user need to use only one machine that's used for the first time login.
I tried to get the client side mac address, but i can't able to get client side mac address in my website. Is there any other way to identity a machine uniquely?
For asp.net it's not possible to get the mac address of the client. You need to have some kind of windows application for that, that runs on the user's system.
A permanent cookie with a with a GUID might also be a solution.
Another solution might be to look up the servervariables when they make a request you will have Request.ServerVariables["REMOTE_ADDR"]; which would probably be the internal IP if the app is internal/intranet. There is also REMOTE_HOST. Sometimes these are filtered off by proxies/firewalls/nat but hopefully not in your situation.
Hope it helps!
if its intranet webapp, then you can enforce windows authentication - and keep a list of logged in users, in the database, with a timestamp of when the logged in user will automatically logout after the timestamp period.
Alternatively, use a cookie in forms authentication to do just that. But in any case, you will need the list of logged in users, and automatically log the user off, if he is on another machine.
More so, you can get the client's IP address and go from there, but its not reliable as it could be of an ISP. Its tricky, but cookies seems to be the simplest way of doing this.
However, a good solution would be to do it like IRC does, to keep track of logged in users. It sends a PING to the client, and expects the client to return a PONG, at different intervals of time. If the PONG is not received by the client, the IRC server automatically disconnects the user. Try this with something like SignalR. The downside of this is, if the user closes the browser and a PING request comes in, it will bounce back and the client will be disconnected as he/she will not be able to send a PONG request back.
I believe you want a user logged in on the website only in one session at any given time. Problem is that you can't know for sure when the user leaves, if he doesn't logout using the logout button.To fix this you have to have a timeout. I used a text file on the server in an application and it works.
Login button:
protected void btLogin_Click(object sender, EventArgs e)
{
if (check(txtPass.Text) && check(txtUser.Text))
{
var user = new UserManager().login(txtUser.Text, txtPass.Text);
if (user != null)
{
// this is the test you're looking for, the rest is only context
if (!FileManager.alreadyLoggedIn(user.email))
{
FormsAuthentication.SetAuthCookie(user.email, false);
}
else
{
//throw error that it is already connected in some other place
}
}
else
{
//throw error that login details are not OK
}
}
}
In a class two static methods:
//you have to call this function at every request a user makes
internal static void saveUserSessionID(string email)//email or any unique string to user
{
var dir = HostingEnvironment.MapPath("~/temp/UserSession/");// a folder you choose
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string path = dir + email + ".txt";
File.WriteAllText(path, HttpContext.Current.Session.SessionID);
}
// if a request has not been made in tha last 4 minutes, the user left, closed the browser
// the test checks this only on a real server, localhost is not tested to be easy for the developer
internal static bool alreadyLoggedIn(string email)
{
var file = HostingEnvironment.MapPath("~/temp/UserSession/" + email + ".txt");
return File.Exists(file) && File.GetLastWriteTime(file).AddMinutes(4) > DateTime.Now && !HttpContext.Current.Request.IsLocal;
}
Obviously this is from another application, you can only take the idea and implement it in your own application. You can't just copy paste it.

How do I check the network connection win the fatest way?

I'm developing an application for Honeywell Dolphin 6100, a mobile computer with a barcode scanner that uses Windows CE 5.0 like OS.
I want to use a function which can check the network connection existence, I tried to use the code below but its too slow.
public static bool CheckForInternetConnection()
{
string url = "http://www.Microsoft.com/";
try
{
System.Net.WebRequest myRequest = System.Net.WebRequest.Create(url);
System.Net.WebResponse myResponse = myRequest.GetResponse();
}
catch (System.Net.WebException)
{
return false;
}
return true;
}
Any one have an idea for a faster way to do that. I mention that I'm working with VS2008 on win7
Since you're not doing anything with the content of the response, there's really no reason to request it, and wait for the network transfer of all that data. You might try setting myRequest.Method = "HEAD", which will just return headers (assuming the web server supports it), but obviously still verify that you can communicate with the remote web server.
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.method.aspx
Assuming availability on your version of the .net runtime, you can call the static System.Net.NetworkInformation.GetIsNetworkAvailable() method. There are scenarios where that'll return true and you won't be able to route to the outside world, but it'll tell you whether your device has a network interface that's marked as being up.

Best way to implement a flash website banner

I am a c# asp.net developer and need to implement a number of flash website banners. Previously for static image banners I have implemented on_click code behind or javascript to log the banner has been clicked back to a database and process the re-direction.
I don't have much knowledge of flash other than I know that a flash program can handle on-click events of the program.
Therefore, can somebody suggest the best solution for capturing and processing on-click events of a flash object on a webpage.
Many thanks,
Adam
You can talk to Flash objects with JavaScript via Mootools' Swiff component:
http://mootools.net/blog/2008/02/12/whats-new-in-12-swiff/
http://mootools.net/docs/core/Utilities/Swiff
However, for simple things like clickable banners, all you may need is swfobject:
http://code.google.com/p/swfobject/
A decent but simple XML driven Flash banner rotator can be had for free here:
http://www.weberdesignlabs.com/blog/2008/06/open-source-xml-free-flash-banner/
Hope that helps!
You can communicate in multiple ways with Flash and your Server Side Code.
1.) Use JavaScript to communicate to/from your SWF file and the page it is embedded in.
http://kb2.adobe.com/cps/156/tn_15683.html
This can be combined with AJAX to send data to the server.
2.) Directly send variables to a Server Side File (using GET or POST) within Flash
http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001790.html
var submitListener:Object = new Object();
submitListener.click = function(evt:Object) {
var result_lv:LoadVars = new LoadVars();
result_lv.onLoad = function(success:Boolean) {
if (success) {
result_ta.text = result_lv.welcomeMessage;
} else {
result_ta.text = "Error connecting to server.";
}
};
var send_lv:LoadVars = new LoadVars();
send_lv.name = name_ti.text;
send_lv.sendAndLoad("http://www.flash-mx.com/mm/greeting.cfm", result_lv, "POST");
};
submit_button.addEventListener("click", submitListener);
You can have a Server Side Page (ASP.NET, PHP, etc...) to increment the Database hit count.

Automate login to a site and click a button

To need to login to a site, go to a particular page (eg. local router page) and click a button to do an operation(eg Connect). Since I do it almost everyday, I thought of automating it through small C# application. I don't have any idea how to do it.Any pointers?
Why code C# for one click? Try AutoIt.
Here is a starter tutorial. This will help you to quickly automate clicking on the default buttons of an application. Some more tricks from AutoIt and you will be able to do almost anything you can tell someone over the phone to do on the GUI.
AutoIt is a useful tool to keep handy if you are working with GUI testing or were dreaming of scripting a lot of routine GUI activity.
Capture the content of the HTTP-request using a tool like Fiddler. With this information you can build an application that executes these HTTP-requests.
Trace the HTTP requests your sending using
a browser plugin (Firebug, httpwatch, tamperdata, etc.)
a web debugging proxy (fiddler, charles, etc.)
a packet sniffer (wireshark, etc.)
And then use the classes in the System.Net namespace (e.g. WebClient) to execute the same requests.
You can also use the Selenium IDE, which is a FireFox plugin that allows you to record macro like scripts for playback in the browser. It is designed for automated testing of web pages, but you can export the script in C#, which can in turn be run from a console app.
If you plan to run it as a C# app, you will also need to look at Selenium RC.
Happy scripting :)
I have created app in C# which uses the WebBrowser control provided by Microsoft
and used it to ope a website and tried to manipulate it's html and tried to put values in
some text boxes and tried to hit the button it works for me ,hope it's helps for you as well
Sample code is as follow
internal void LoginToSite()
{
WebBrowser.Navigate("some site login Page");
_Processing = true;
var username = ConfigurationManager.AppSettings["username"];
var password = ConfigurationManager.AppSettings["password"];
while (_Processing)
{
Application.DoEvents();
if (WebBrowser.ReadyState == WebBrowserReadyState.Complete || WebBrowser.ReadyState == WebBrowserReadyState.Interactive)
{
var htmlDocument = this.WebBrowser.Document;
if (htmlDocument != null)
{
foreach (HtmlElement tag in htmlDocument.GetElementsByTagName("input"))
{
switch (tag.Name)
{
case "username":
tag.InnerText = username;
break;
case "password":
tag.InnerText = password;
break;
case "cmdlogin":
tag.RaiseEvent("onclick");
tag.InvokeMember("Click");
break;
}
}
}
_Processing = false;
}
}
}

Check if website is online with ASP.NET C#?

I would like to know how to check if a website is offline or online using C#?
Try to hit the URL using HttpWebClient over an HTTP-GET Request. Call GetResponse() method for the HttpWebClient which you just created. Check for the HTTP-Status codes in the Response.
Here you will find the list of all HTTP status codes. If your request status code is statrting from 5 [5xx] which means the site is offline. There are other codes that can also tell you if the site is offline or unavailable.You can compare the codes against your preferred ones from the entire List.
//Code Example
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create("http://www.stackoverflow.com");
httpReq.AllowAutoRedirect = false;
HttpWebResponse httpRes = (HttpWebResponse)httpReq.GetResponse();
if (httpRes.StatusCode==HttpStatusCode.NotFound)
{
// Code for NotFound resources goes here.
}
// Close the response.
httpRes.Close();
First off, define "online" and "offline". However, if your codebehind code is running, your site is online.
For my web apps, I use a setting called Offline, which admin can set on/off.
Then I can check that setting programmatically.
I use this Offline setting, to show friendly maintenance message to my users.
Additionally you can use App_Offline.htm,
reference :
http://www.15seconds.com/issue/061207.htm
http://weblogs.asp.net/scottgu/archive/2005/10/06/426755.aspx
If you mean online/offline state that controls IIS, then you can control this, with custom Web Events (Application Lifetime Events)
http://support.microsoft.com/kb/893664
http://msdn.microsoft.com/en-us/library/aa479026.aspx
You can use Pingdom.com and its API's. Check the source code of the 'Alerter for Pingdom API' at the bottom of this page

Categories

Resources