I want to make a program that checks if the computer is connected to the internet when i start the application.
This is my Form
And this is my Code:
private bool checkinternet()
{
WebRequest request = WebRequest.Create("http://www.google.com");
WebResponse response;
try
{
response = request.GetResponse();
response.Close();
request = null;
return true;
}
catch(Exception)
{
request = null;
return false;
}
}
private void pictureBox1_Click_1(object sender, EvenArgs e)
{
bool checkinternet = false;
{
}
}
The code to check the internet connection works. I tried using buttons, but i want to display an image in imagebox1 if the computer has internet, or display another image if it is not connected.
You need to do the operation in your form load event:
private void Form1_Load(object sender, System.EventArgs e)
{
if (CheckInternet()) // change to upper case (convention for methods)
{
imagebox1.Image = Image.FromFile("p://ath/to/online/image.jpg");
}
else
{
imagebox1.Image = Image.FromFile("p://ath/to/offline/image.jpg");
}
}
The above code is calling your CheckInternet method that returns a bool value whenever there is an internet connection or not.
According to the returned value, you need to set the correct image.
You need to provide the full image path name as parameter to the Image.FromFile method.
First of all you should use a using-directive to automatically dispose your WebRequest:
private bool checkinternet()
{
using(WebRequest request = WebRequest.Create("http://www.google.com"))
{
WebResponse response;
try
{
response = request.GetResponse();
response.Close();
return true;
}
catch(Exception)
{
return false;
}
}
}
Also you need to call your method using braces in an if-statement where you need ==to check for a value:
private void pictureBox1_Click_1(object sender, EvenArgs e)
{
if(checkinternet() == false)
{
//no internet
}
if(checkinternet())
{
//internet
}
if(!checkinternet())
{
//no internet
}
}
Finally, as stated in the answer from ehh you can use the Load event to execute the code when the Form opens:
private void Form1_Load(object sender, System.EventArgs e)
{
if (checkinternet())
{
imagebox1.Image = Image.FromFile("p://ath/to/online/image.jpg");
}
else
{
imagebox1.Image = Image.FromFile("p://ath/to/offline/image.jpg");
}
}
Related
I have an application where user can click on a Scan button to scan the image to preview in the application. When user clicks, usually a "Preparing to scan" message will be shown and goes away when the scan is 100% complete.
The scan works fine. The problem if I stress test it by pressing the scan button many times while it's doing it's work, the application completely hangs and the message just stays there and I had to restart my whole application.
The code: It's just a small section
private void ScanStripButton_Click(object sender, EventArgs e)
{
if (SCAN_INTO_BATCH)
{
GENERATE_BATCH_FOLDER = true;
StartTwainScan();
}
}
Any idea on how to prevent this issue?
Appreciate the help
EDIT:
public void StartTwainScan()
{
Boolean EnableUI = false;
Boolean ADF = false;
Boolean EnableDuplex = false;
if (Properties.Settings.Default.TwainShow.Equals("1"))
{
EnableUI = true;
}
if (Properties.Settings.Default.ScanType.Equals("2"))
{
ADF = true;
}
if (Properties.Settings.Default.DuplexEnable.Equals("1"))
{
EnableDuplex = true;
}
var rs = new ResolutionSettings
{
Dpi = GetResolution(),
ColourSetting = GetColorType()
};
var pg = new PageSettings()
{
Size = GetPageSize()
};
var settings = new ScanSettings
{
UseDocumentFeeder = ADF,
ShowTwainUI = EnableUI,
ShowProgressIndicatorUI = true,
UseDuplex = EnableDuplex,
Resolution = rs,
Page = pg
};
try
{
TwainHandler.StartScanning(settings);
}
catch (TwainException ex)
{
MessageBox.Show(ex.Message);
//Enabled = true;
//BringToFront();
}
}
This isn't going to be the correct answer, but you haven't shown enough code to give you the right code. It should point you in the right direction.
private void ScanStripButton_Click(object sender, EventArgs e)
{
ScanStripButton.Enabled = false;
if (SCAN_INTO_BATCH)
{
GENERATE_BATCH_FOLDER = true;
StartTwainScan();
}
ScanStripButton.Enabled = true;
}
Basically you disable the button when the scan starts and enable it when it finishes.
private async void ScanStripButton_Click(object sender, EventArgs e)
{
await Task.Run(() =>
{
if (SCAN_INTO_BATCH)
{
GENERATE_BATCH_FOLDER = true;
StartTwainScan();
}
});
}
or
private bool clicked = false;
private void ScanStripButton_Click(object sender, EventArgs e)
{
try
{
if(clicked)
return;
clicked = true;
if (SCAN_INTO_BATCH)
{
GENERATE_BATCH_FOLDER = true;
StartTwainScan();
}
}
finally
{
clicked = false;
}
}
I am facing trouble in calling events in Zkemkeeper.dll. I have succesfully established the connection however on putting the finger on sensor no event is fired. Infact no realtime event is being triggered.
Any help would be appreciated following is my code;
private void button2_Click(object sender, EventArgs e)
{
string s = "";
int Val = 0;
bool bIsConnected = false;
try {
//zkemkeeper.CZKEMClass axczkem1 = new zkemkeeper.CZKEMClass();
// bIsConnected = axczkem1.Connect_USB(1);
bIsConnected = axczkem1.Connect_Com(6,1,115200);
if(bIsConnected==true){
Cursor = Cursors.Default;
bool asa= axczkem1.EnableDevice(1, true);
if (axczkem1.RegEvent(1, 65535))
{
axczkem1.OnFinger += new zkemkeeper._IZKEMEvents_OnFingerEventHandler(axczkem1_OnFinger);
axczkem1.OnKeyPress += new zkemkeeper._IZKEMEvents_OnKeyPressEventHandler(axczkem1_OnKeyPress);
axczkem1.OnConnected += new _IZKEMEvents_OnConnectedEventHandler(axCZKEM1_OnConnected);
axczkem1.OnVerify += new zkemkeeper._IZKEMEvents_OnVerifyEventHandler(axCZKEM1_OnVerify);
}
MessageBox.Show("Connection established!!!");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
And following are the event methods:
private void axCZKEM1_OnVerify(int UserID)
{
label2.Text = "Verify";
}
private void axCZKEM1_OnConnected()
{
label1.Text = "Connected";
}
private void axczkem1_OnKeyPress(int Key)
{
MessageBox.Show(Key.ToString());
}
private void axczkem1_OnFinger()
{
MessageBox.Show("Connection");
}
if this is a windows form application . If program have long running process event doesn't work . For example loop (while,for) . And also Thread.sleep() .
If you want to trigger work your program do nothing .
If this is not a windows form see this link enter link description here
So basically I have a button. when I click it, two things must occur.
1) a web request to get the data
2) navigate to the other page and populate the data
the problem is that when the app navigates to page2, App.mydirectories gives a nullreferenceException...
How can I make sure App.mydirectories isn't null and wait before populating data to the new page.
private void Button_Click(object sender, RoutedEventArgs e)
{
makeEventwebRequest(number.Text,date.Text);
NavigationService.Navigate(new Uri("/page2.xaml", UriKind.Relative));
}
public void makeEventwebRequest(string numb, string date)
{
string requesturi = string.Format(baseUri, numb, date);
try
{
WebClient client = new WebClient();
client.DownloadStringCompleted +=
new DownloadStringCompletedEventHandler(directories_DownloadStringCallback);
client.DownloadStringAsync(new Uri(requesturi));
}
catch (Exception e)
{
}
}
private void directories_DownloadStringCallback(object sender, DownloadStringCompletedEventArgs e)
{
App.mydirectories = JsonConvert.DeserializeObject<directoriescs>(e.Result);
}
This error occurs because your code to do the WebRequest is async. When you navigate to page2.xaml your data isn't downloaded yet.
This is an example on how you could do your code:
private async void Button_Click(object sender, RoutedEventArgs e)
{
await makeEventwebRequest(number.Text,date.Text);
NavigationService.Navigate(new Uri("/page2.xaml", UriKind.Relative));
}
public async void makeEventwebRequest(string numb, string date)
{
string requesturi = string.Format(baseUri, numb, date);
var request = (HttpWebRequest)WebRequest.Create(requesturi );
var result = await GetHttpResponse(request);
App.mydirectories = JsonConvert.DeserializeObject<directoriescs>(result);
}
// Method helper to Http async request
public static async Task<String> GetHttpResponse(HttpWebRequest request)
{
String received = null;
try
{
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
using (var responseStream = response.GetResponseStream())
{
using (var sr = new StreamReader(responseStream))
{
received = await sr.ReadToEndAsync();
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
return received;
}
You should read an article on async/await methods like http://msdn.microsoft.com/en-us/library/hh191443.aspx so you can better understand what is different from your code to mine.
The baseline is that you navigated to page2 while the webrequest was still being made, while in the code I posted above, the execution waits for the web request to complete and then navigates to page2.
I need to browse a set of url adresses (yes another web scraper..).
I want to use tasks. But I have problem returning AFTER the browser is finished.
To be sure the site is fully loaded I have to jump to document_completed and from there I call the Navigate method with another url.
Something like this:
private WebBrowser browser;
private List<string> urlsToVisit;
int urlCounter = 0;
public PageBrowser(List<string> urls) //constructor
{
urlCounter = 0;
urlsToVisit = urls;
browser = new WebBrowser(); //one instance of browser for all urls
browser.ScriptErrorsSuppressed = true;
browser.DocumentCompleted += browser_DocumentCompleted;
}
//this I want to call from somewhere else and return true AFTER it opens all sites
public bool Run()
{
VisitPages();
return true;
}
private void VisitPages()
{
if (urlCounter < urlsToVisit.Count)
{
browser.Navigate(urlsToVisit[urlCounter]);
urlCounter++;
}
else
{
browser.Dispose();
}
}
private void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (e.Url.AbsolutePath != (sender as WebBrowser).Url.AbsolutePath) return;
System.Threading.Thread.Sleep(3000); //random interval between requests
VisitPages();
}
I am pretty sure, the solution is very simple but I just don't see it..
Thank you
Petr
I would suggest you to use a WebClient instead of a WebBrowser UI component since you don't seem to need to render anything. It seems as you just want to send requests to your list of urls and return true if everything went well, and return false if any type of problem occured.
private async Task<bool> VisitUrls()
{
var urls = new List<string>
{
"http://stackoverflow.com",
"http://serverfault.com/",
"http://superuser.com/"
};
var success = await BrowseUrls(urls);
return success;
}
private async Task<bool> BrowseUrls(IEnumerable<string> urls)
{
var timeoutWebClient = new WebClient();
foreach (var url in urls)
{
try
{
var data = await timeoutWebClient.DownloadDataTaskAsync(url);
if (data.Length == 0) return false;
}
catch (Exception ex)
{
return false;
}
}
//Everything went well, returning true
return true;
}
I have a test web connection form in c#. I want to show a loading window while my connection is being checked, and then show the result of checking.
This is my code for testing the web connection:
public bool ConnectionAvailable(string strServer)
{
try
{
HttpWebRequest reqFP = (HttpWebRequest)HttpWebRequest.Create(strServer);
HttpWebResponse rspFP = (HttpWebResponse)reqFP.GetResponse();
if (HttpStatusCode.OK == rspFP.StatusCode)
{
// HTTP = 200 - Internet connection available, server online
rspFP.Close();
return true;
}
else
{
// Other status - Server or connection not available
rspFP.Close();
return false;
}
}
catch (WebException)
{
// Exception - connection not available
return false;
}
}
And this:
private void button1_Click(object sender, EventArgs e)
{
string url = "Web-url";
label1.Text = "Checking ...";
button1.Enabled = false;
if (ConnectionAvailable(url))
{
WebClient w = new WebClient();
w.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
label1.Text = w.UploadString(url, "post", "SN=" + textBox1.Text);
button1.Enabled = true;
}
else
{
label1.Text = "Conntion fail";
button1.Enabled = true;
}
}
On a windows forms application the user interface runs on one thread, if you try to run a long running process, which checking the web connection might end up being this will cause the form to freeze until it completes the work.
So, I'd start a new thread that does the check. then raise an event to return the result. while all that's happening you can do what you like with the user interface, such as a loading graphic, or even allow the user to continue using features that don't require the internet connection.
Create EventArgs class of your own so you can pass back the result:
public class ConnectionResultEventArgs : EventArgs
{
public bool Available { get; set; }
}
Then in your form class, create your event, handlers and the method to action when the event arrives
//Create Event and Handler
public delegate void ConnectionResultEventHandler(object sender, ConnectionResultEventArgs e);
public event ConnectionResultEventHandler ConnectionResultEvent;
//Method to run when the event has been receieved, include a delegate in case you try to interact with the UI thread
delegate void ConnectionResultDelegate(object sender, ConnectionResultEventArgs e);
void ConnectionResultReceived(object sender, ConnectionResultEventArgs e)
{
//Check if the request has come from a seperate thread, if so this will raise an exception unless you invoke.
if (InvokeRequired)
{
BeginInvoke(new ConnectionResultDelegate(ConnectionResultReceived), new object[] { this, e });
return;
}
//Do Stuff
if (e.Available)
{
label1.Text = "Connection Good!";
return;
}
label1.Text = "Connection Bad";
}
Subscribe to the event when your form loads:
private void Form1_Load(object sender, EventArgs e)
{
//Subscribe to the the results event.
ConnectionResultEvent += ConnectionResultReceived;
}
and then setup the worker thread:
//Check the connection
void BeginCheck()
{
try
{
HttpWebRequest reqFP = (HttpWebRequest)HttpWebRequest.Create("http://google.co.uk");
HttpWebResponse rspFP = (HttpWebResponse)reqFP.GetResponse();
if (HttpStatusCode.OK == rspFP.StatusCode)
{
// HTTP = 200 - Internet connection available, server online
rspFP.Close();
ConnectionResultEvent(this, new ConnectionResultEventArgs {Available = true});
}
else
{
// Other status - Server or connection not available
rspFP.Close();
ConnectionResultEvent(this, new ConnectionResultEventArgs { Available = false });
}
}
catch (WebException)
{
// Exception - connection not available
//Raise the Event - Connection False
ConnectionResultEvent(this, new ConnectionResultEventArgs { Available = false });
}
}
private void button1_Click(object sender, EventArgs e)
{
//loading graphic, screen or whatever
label1.Text = "Checking Connection...";
//Begin the checks - Start this in a new thread
Thread t = new Thread(BeginCheck);
t.Start();
}
I am thinking of threading! One thread checks the connection while the other one is showing the loading window. If for example the connection has been established you can notify the other thread and show the result.