Gecko WebBrowser unable to open a specific link first time after Restart machine - browser

I am new in C# . I have developed own webbrowser with Gecko webBrowser control. But I'm unable to open a particular link for first time, and it return alert for timeout. I handled timeout alert messagebox too.
When I have implemented
private void gWebBrowser_DocumentCompleted(object sender, Gecko.Events.GeckoDocumentCompletedEventArgs e)
I found out that first time page was not properly loaded.
How can i use auto Reload or timer in it?
My code is:
public partial class Embedded_Browser : Form
{
public Embedded_Browser()
{
string GeminiURL = "NA";
InitializeComponent();
Xpcom.Initialize("Firefox");
GeckoPreferences.User["dom.max_script_run_time"] = 0; //let js run as long as it needs to; prevents timeout errors
GeckoPreferences.User["security.warn_viewing_mixed"] = false;
GeckoPreferences.User["browser.download.manager.showAlertOnComplete"] = false;
GeckoPreferences.User["privacy.popups.showBrowserMessage"] = false;
GeckoPreferences.User["browser.xul.error_pages.enabled"] = false;
GeckoPreferences.User["browser.cache.memory.enable"] = false;
gWebBrowser.NSSError += new EventHandler<GeckoNSSErrorEventArgs>(gWebBrowser_NSSError); //Bypass SSL certificate issues
gWebBrowser.NavigationError += new EventHandler<GeckoNavigationErrorEventArgs>(gWebBrowser_NavigationError); //If there are any issues encountered during page loads
gWebBrowser.Navigated += new EventHandler<GeckoNavigatedEventArgs>(gWebBrowser_Navigated); //React appropriately to URL navigation
string sUserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; pl; rv:1.9.1) Gecko/20090624 Firefox/3.5 (.NET CLR 3.5.30729)";
Gecko.GeckoPreferences.User["general.useragent.override"] = sUserAgent;
var observerService = Xpcom.GetService<nsIObserverService>("#mozilla.org/observer-service;1");
observerService.AddObserver(new Observer(), "http-on-modify-request", false);
if (Environment.Is64BitOperatingSystem)
{
RegistryKey MyReg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Wow6432Node\\Jekson\\AppConfig", true);
GeminiURL = (string)MyReg.GetValue("Browse_URL", "NA");
}
else
{
RegistryKey MyReg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Jekson\\AppConfig", true);
GeminiURL = (string)MyReg.GetValue("Browse_URL", "NA");
}
gWebBrowser.Navigate(GeminiURL);
textBox1.Text = GeminiURL;
PromptFactory.PromptServiceCreator = () => new NoPromptService();
// System.Threading.Thread.Sleep(5000);
if(NoPromptService.isPrompt == 1){
gWebBrowser.Reload();
gWebBrowser.Navigate(GeminiURL);
MessageBox.Show("Hello!");
}
}
Please Help me. thanks in advance

I have used timer control for making Web browser auto refresh for first time.
After 5ms web browser auto refresh once.
My code is:
private void timer1_Tick(object sender, EventArgs e)
{
gWebBrowser.Navigate("google.com"); //You can pass any url here which you want to load
if (count == 0)
{
timer1.Enabled = false;
}
count++;
}

Related

C# Win Form - Main thread not responding when using background worker

I have a datagridview which is being populated by a DataTable through DataSource and i am using a backgroundworker for formatting of cells (back color and forecolor of cells) in datagridview.
BackgroundWorker bw = new BackgroundWorker();
private void Frm_Find_Load(object sender, EventArgs e)
{
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
CheckForValidValues();
}
public bool CheckForValidValues()
{
dgv.Invoke((MethodInvoker)delegate()
{
for (int i = 0; i < Dt.Rows.Count; i++)
{
if (Dt.Rows[0]["Name"].ToString() == Value)
{
dgv.Rows[i].Cells["Name"].Style.BackColor = Color.FromArgb(255, 192, 192);
}
else
{
dgv.Rows[i].Cells["Name"].Style.BackColor = Color.White;
}
progressBar1.Invoke((MethodInvoker)(() => progressBar1.Value++));
}
});
this.Invoke((MethodInvoker)delegate()
{
BtnShow.Enabled = true;
dgv.Enabled = true;
});
}
private void btnSave_Click(object sender, EventArgs e)
{
if (bw.IsBusy == false)
{
progressBar1.Visible = true;
progressBar1.Value = 0;
BtnShow.Enabled = false;
dgv.Enabled = false;
progressBar1.Maximum = dgv.Rows.Count;
bw.RunWorkerAsync();
}
}
while the whole process goes down the DataGridView remains Enabled=false so that user cant change any values in datagridview.
There is usually 15,000 rows in the datagridview and that many rows to format, this takes time that is why I use a backgroundworker for it and it works perfectly fine BUT when the user tries to press the enabled false datagridview couple of times, the main thread becomes unresponsive and the progressbar freezes.
Can anyone guide me how to deal with it?
You are running the whole code using Invoke. It means you are switching to UI thread and the code is running in UI thread. Since the code is a time-consuming for loop, then it's blocking UI thread.
Instead of using a BackgroundWorker, to format cells, it's better to use CellFormatting event:
private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
//If this is header cell or new row, do nothing
if (e.RowIndex < 0 || e.ColumnIndex < 0 || e.RowIndex == dgv.NewRowIndex)
return;
//If formatting your desired column, perform validation
if (e.ColumnIndex == dgv.Columns["Name"].Index)
{
// Perform validation and change cell back color here.
}
}
Maybe try to disable the Button when it get clicked until the job done?.
Lets say your Button name is Button1,
when the user click on the Enabled false data grid view, use Button.enabled=false, then when the job is done use Button.enabled=true
hope that helps!

ZXing.Net.Mobile Sample.WindowsUniversal Sample Not Scanning

Testing this to incorporate into Win 10 UWP app to scan 1D barcodes (format 39 & 128). I have updated latest through nuget 2.0.4.46. Referenced post at http://www.yortondotnet.com/2015/07/mobile-barcode-scanning-with-zxingnet.html regarding some options setting prior to scan() with no luck. The scanner (camera) opens but never recognizes a barcode scan successfully - or failure for that matter. It seems nothing is happening whatsoever. I have included straight, pertinent sample code with some options modifications for review. I have gotten Scandit API to work and was going to try Manateeworks but both are really costly and not an option. I am developing on Surface Pro 3 (Win 10) and that build will also be target machines when complete.
public sealed partial class MainPage : Page
{
UIElement customOverlayElement = null;
MobileBarcodeScanner scanner;
public MainPage()
{
this.InitializeComponent();
//Create a new instance of our scanner
scanner = new MobileBarcodeScanner(this.Dispatcher);
scanner.Dispatcher = this.Dispatcher;
}
private void buttonScanDefault_Click(object sender, RoutedEventArgs e)
{
//Tell our scanner to use the default overlay
scanner.UseCustomOverlay = false;
//We can customize the top and bottom text of our default overlay
scanner.TopText = "Hold camera up to barcode";
scanner.BottomText = "Camera will automatically scan barcode\r\n\r\nPress the 'Back' button to Cancel";
// GWS Set Options
var options = new MobileBarcodeScanningOptions();
options.PossibleFormats = new List<ZXing.BarcodeFormat>() {
ZXing.BarcodeFormat.CODE_39, ZXing.BarcodeFormat.CODE_128
};
options.AutoRotate = false;
options.TryHarder = false;
options.TryInverted = false;
//Start scanning
scanner.Scan(options).ContinueWith(t =>
{
if (t.Result != null)
HandleScanResult(t.Result);
});
}
private void buttonScanContinuously_Click(object sender, RoutedEventArgs e)
{
//Tell our scanner to use the default overlay
scanner.UseCustomOverlay = false;
//We can customize the top and bottom text of our default overlay
scanner.TopText = "Hold camera up to barcode";
scanner.BottomText = "Camera will automatically scan barcode\r\n\r\nPress the 'Back' button to Cancel";
// GWS Set Options
var options = new MobileBarcodeScanningOptions();
options.PossibleFormats = new List<ZXing.BarcodeFormat>() {
ZXing.BarcodeFormat.CODE_39, ZXing.BarcodeFormat.CODE_128
};
options.AutoRotate = false;
options.TryHarder = false;
options.TryInverted = false;
//Start scanning
scanner.ScanContinuously(options, async (result) =>
{
var msg = "Found Barcode: " + result.Text;
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
await MessageBox(msg);
});
});
}
async void HandleScanResult(ZXing.Result result)
{
string msg = "";
if (result != null && !string.IsNullOrEmpty(result.Text))
msg = "Found Barcode: " + result.Text;
else
msg = "Scanning Canceled!";
await MessageBox(msg);
}
}
Simon,
I have the exact same problem. I tested your code with the latest nuget 2.1.47, the problem still exists.
You need to download the latest from Github and add the following projects (or DLLs) to your project:
ZXing.Net (project: zxing.portable.csproj)
ZXing.Net.Mobile.Core
ZXing.Net.Mobile.WindowsUniversal
I have tested your code and it works fine. I hope this help.
Cheers,
Sam
I think that the problem in the hardware you are testing with. Surface Pro 3 (Win 10) does not have an auto focus camera. I've never succeed to scan with ZXing using my Surface Pro 3, while the same application is working fine with my other windows 10 device.

MediaCapture.CapturePhotoToStreamAsync() and MediaCapture.CapturePhotoToStorageFileAsync() throw Argument exception

I'm trying to create an app that can use the camera for Windows Phone 8.1, using the Windows RT/XAML development model.
When I try to call either of the capture methods off of the MediaCapture class I get an ArgumentException with the message "The parameter is incorrect." Here is my code
private async Task Initialize()
{
if (!DesignMode.DesignModeEnabled)
{
await _mediaCaptureMgr.InitializeAsync();
ViewFinder.Source = _mediaCaptureMgr;
await _mediaCaptureMgr.StartPreviewAsync();
}
}
private async void ViewFinder_OnTapped(object sender, TappedRoutedEventArgs e)
{
ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
var stream = new InMemoryRandomAccessStream();
await _mediaCaptureMgr.CapturePhotoToStreamAsync(imageProperties, stream);
_bitmap = new WriteableBitmap((int) ViewFinder.ActualWidth, (int) ViewFinder.ActualHeight);
stream.Seek(0);
await _bitmap.SetSourceAsync(stream);
PreviewImage.Source = _bitmap;
PreviewElements.Visibility = Visibility.Visible;
ViewFinder.Visibility = Visibility.Collapsed;
Buttons.Visibility = Visibility.Visible;
Message.Visibility = Visibility.Collapsed;
stream.Seek(0);
var buffer = new global::Windows.Storage.Streams.Buffer((uint) stream.Size);
stream.ReadAsync(buffer, (uint) stream.Size, InputStreamOptions.None);
DataContext = buffer.ToArray();
if (PhotoCaptured != null)
PhotoCaptured(this, null);
}
The initialize method is called on page load, and the viewfinder_ontapped is called when they tap the CaptureElement I have in the xaml. The error is thrown on
await _mediaCaptureMgr.CapturePhotoToStreamAsync(imageProperties, stream);
What's really bizarre is that I downloaded the latest source for the winrt xaml toolkit http://winrtxamltoolkit.codeplex.com/ and tried their sample camera app, which uses similar code. It throws the same error on MediaCapture.CapturePhotoToStorageFileAsync(). Can anyone help me identify why?

Windows Phone C#, UnauthorizedAccessException when creating BitmapImage

I am trying to download image from Internet using async call like this:
private void DoGetAlbumart(object sender, DoWorkEventArgs e)
{
string req = (string)e.Argument;
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(ReadWebRequestCallback);
wc.OpenReadAsync(new Uri(req));
}
void ReadWebRequestCallback( object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null && !e.Cancelled)
{
try
{
BitmapImage image = new BitmapImage();
image.SetSource(e.Result);
SecondTile.Source = image;
}
catch (Exception ex)
{
}
}
else
{
}
}
It seems that when breakpoint hits at BitmapImage image = new BitmapImage(), I got the following exception:
ex = {System.UnauthorizedAccessException: Invalid cross-thread access.
at MS.Internal.XcpImports.CheckThread()
at System.Windows.DependencyObject..ctor(UInt32 nativeTypeIndex, IntPtr constructDO)
at System.Windows.Media.Imaging.BitmapImage..ctor()
What else can I try to get rid of this error?
Callback methods run in background threads, not the UI thread. Unfortunately, BitmapImages can only be instantiated in the UI thread. If you need to access the UI thread from a callback, try the following:
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
BitmapImage image = new BitmapImage();
image.SetSource(e.Result);
SecondTile.Source = image;
});

Got a SIGSEGV while setting the Text of my TextField from a ABPeoplePickerModule

In my App the User needs to type in some Address Information.
I provide an Addressbook Button for that since Version 1.0.
That worked fine in my previous tests, but now I get a SIGSEGV when I try to set my UITextField.Text property. This error occurs everytime when I try to Pick an Address from the PeoplePicker in MonoTouches Debug mode, when I try that on my iPhone the eror occurs randomly between setting the TextFields and pushing the next ViewController.
Is There anything wrong in my Code or is it a bug?
//AB Button Event
addressBook.TouchUpInside += delegate {
//Create new Picker
ABPeoplePickerNavigationController PP = new ABPeoplePickerNavigationController();
//Cancel Event
PP.Cancelled += delegate {
NavigationController.DismissViewController(true, null);
};
//Select Event
PP.SelectPerson += delegate(object sender, ABPeoplePickerSelectPersonEventArgs e) {
//Detailed Person View
ABPersonViewController pv = new ABPersonViewController();
//Action when clicked on a Property
pv.PerformDefaultAction += delegate(object person, ABPersonViewPerformDefaultActionEventArgs ev) {
//If the Property was an Address
if(ev.Property.ToString() == "Address"){
string lands = "", orts = "", plzs = "";
try{
//Read the Detailed Address Data from the clicked property
ABMultiValue<PersonAddress> addresses = ev.Person.GetAllAddresses();
PersonAddress[] values = addresses.GetValues();
lands = values[ev.Identifier.Value].Country.ToString();
orts = values[ev.Identifier.Value].City.ToString();
plzs = values[ev.Identifier.Value].Zip.ToString();
}catch{
Console.WriteLine("Fehlerhafte Addresse");
}
//Set the Textfield with the new information
//iPhone Simulator in Debugmode crashes here everytime
land.Text = lands;
ort.Text = orts;
plz.Text = plzs;
//Close the Module
NavigationController.DismissViewController(true, null);
}
};
//Set selected Person for the person View
pv.DisplayedPerson = e.Person;
//Open Person View with navigation from the PeoplePicker Controller
PP.PushViewController(pv, true);
};
//Open PeoplePicker Controller Module
NavigationController.PresentViewController(PP, true, null);
};
Thanks in advance!
The just released MonoTouch 6.0.5 has a fix for a similar issue.

Resources