How to debug a new Thread in VS2015? - multithreading

I have this code in a WebForm project in VS Community 2015:
var th = new Thread(() => {
var wb = new WebBrowser();
wb.DocumentCompleted += wb_DocumentCompleted;
wb.AllowNavigation = true;
wb.Navigate("https://www.ovo.com.au/login");
Application.Run();
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
This is the DocumentCompleted handler, which runs ok, but I cannot debug it
private async void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser wb = (WebBrowser)sender;
System.Diagnostics.Debug.WriteLine(wb.Url);
}
I get this in the Watch window when I put a breakpoint:
error CS0103: The name 'wb' does not exist in the current context
Edit / Solution
The solution was to enable "Use Managed Compatibility Mode" (in Tools > Options > Debugging > General)

Related

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

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++;
}

iText7 for .NET - error while merging files

I've created simple method that allows me to merge multiple PDF files.
Below is my code:
private void Merge(List<string> src, string dest)
{
Stopwatch sw = new Stopwatch();
sw.Start();
PdfDocument pdfDocument1 = new PdfDocument(new PdfReader(src[0]), new PdfWriter(dest));
for (int i = 1,max=src.Count; i < max; i++)
{
PdfDocument pdfDocument2 = new PdfDocument(new PdfReader(src[i]));
var pagesCount = pdfDocument2.GetNumberOfPages();
pdfDocument2.CopyPagesTo(1, pagesCount, pdfDocument1);
pdfDocument2.Close();
}
pdfDocument1.Close();
sw.Stop();
Debug.WriteLine(sw.Elapsed);
}
I've based my code on example from iText book: http://developers.itextpdf.com/examples/merging-pdf-documents/clone-merging-documents-bookmarks
For test purpose I've attached that method to button and I'm caling it like this:
private void button1_Click(object sender, EventArgs e)
{
try
{
string dest = #"E:\final.pdf";
var files = Directory.GetFiles(#"E:\PDFS", "*.pdf").Take(100).ToList();
Merge(files,dest);
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
From time to time (after n'th click on that button) I get exception saying:
Cant cast from 'iText.Kernel.Pdf.PdfNumber' to
'iText.Kernel.Pdf.PdfStream'.
Also first time I click my application takes about 100MB of memory, next time I click it increase to 150MB, next click and I get 230MB of memory used, so it look like it isn't releasing memory.
Is there a better way to merge multiple PDF's into one using iTextSharp 7?
As per request I'm adding StackTrace:
w iText.Kernel.Pdf.PdfPage.GetContentStream(Int32 index)
w iText.Kernel.Pdf.PdfPage.Flush(Boolean flushXObjects)
w iText.Kernel.Pdf.PdfPage.Flush()
w iText.Kernel.Pdf.PdfDocument.Close()
w iTextSharp7_Merge.Form1.Merge(List`1 src, String dest)
w c:\Users\Misiu\Documents\Visual Studio 2013\Projects\iTextSharp7_Merge\Form1.cs:wiersz 75
And here are exception details:
EDIT:
I've changed button click function so now it loads 100 file names from directory and calls Merge method 10 times with same list:
private void button1_Click(object sender, EventArgs e)
{
try
{
string dest = #"E:\final.pdf";
var files = Directory.GetFiles(#"E:\PDFS", "*.pdf").OrderBy(x => x).Skip(0).Take(100).ToList();
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 1; i <= 10; i++)
{
Debug.WriteLine(i);
Merge(files, dest1);
}
sw.Stop();
Debug.WriteLine(sw.Elapsed);
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
This way I've excluded random sort of Directory.GetFiles.
Here is sample output that comes from Visual Studio:
'iTextSharp7_Merge.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll'
1
'iTextSharp7_Merge.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Users\Misiu\documents\visual studio 2013\Projects\iTextSharp7_Merge\bin\Debug\itext.kernel.dll'
'iTextSharp7_Merge.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Users\Misiu\documents\visual studio 2013\Projects\iTextSharp7_Merge\bin\Debug\itext.io.dll'
A first chance exception of type 'System.NullReferenceException' occurred in itext.kernel.dll
2
3
The thread '<No Name>' (0x2dd0) has exited with code 0 (0x0).
4
5
A first chance exception of type 'System.InvalidCastException' occurred in itext.kernel.dll

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.

Multiple Backgroundworker threads in a single Backgroundworker thread

I have an issue here with multi-threading. Tried using both backgroundworker and threads.
Objective: Select an item from a combo-box and click a button to trigger multiple backup file restores into the MSSQL Server. The intention is to popup as many popups as there are Backup files to restore. The main window starts a backgroundworker, showing the overall progress, while the child threads result in non-modal child popups representing each restoration process with progress. This works fine if run serially (without threads/backgroundworker). My intention is to run a bunch of parallel popups, so that the restoration is much more quick.
Problem Statement: My intention is to run a bunch of parallel popups, so that the restoration is much more quick instead of running serially. While trying to debug, its a chaotic break-point show that the Visual Studio shows up (perhaps to represent multiple threads in parallel). But the ultimate goal is not being achieved. Can anybody help me in this regard?
- Code Extracts
Here is the code extract, which I've done and this works in a serial fashion. But as soon as I put the code for multi-threading, nothing works. Only the popups appear, but no processing happens.
This is the button click event, which starts the whole process
private void btnSnapshot_Click(object sender, EventArgs e)
{
this.SetPanelEnabledProperty(false); // Disable All Controls on the main window
// Select the text against which the DATABASE Backup Files are to be picked
// Start the main background worker process, which in turn will trigger few other child threads
BGWrk.RunWorkerAsync(2000);
BGWrk.DoWork += new DoWorkEventHandler(BGWrk_DoWork);
BGWrk.ProgressChanged += new ProgressChangedEventHandler(BGWrk_ProgressChanged);
BGWrk.RunWorkerCompleted += new RunWorkerCompletedEventHandler
(BGWrk_RunWorkerCompleted);
BackgroundWorker helperBW = sender as BackgroundWorker;
BGWrk.WorkerReportsProgress = true;
BGWrk.WorkerSupportsCancellation = true;
}
private void BGWrk_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker helperBW = sender as BackgroundWorker;
int arg = (int)e.Argument;
//Call the method that invokes the popup window instances in a loop, for each file found for the SnapShotName selected in the combobox
ParallelRestoreSnapshot();
if (helperBW.CancellationPending)
{
e.Cancel = true;
}
}
// This method will create backgroundworker instances and in turn the Do_Work events of those backgroundworkers will call the popup against each backup file.
private bool ParallelRestoreSnapshot()
{
FileOperations FIO = new FileOperations();
if (SelectedSnapShot != null && SelectedSnapShot != "None")
{
string[] sBakFiles;
sBakFiles = FIO.GetListOfBackupFiles(sEntireBackupFilePath);
try
{
progressPopupsList = new List<FrmProgressPopup>();
for (int aIndex = 0; aIndex < sBakFiles.Length; aIndex++)
{
BackgroundWorker bgPopups = new BackgroundWorker();
BAKFileName = sBakFiles[aIndex];
bgPopups.RunWorkerAsync(2000);
bgPopups.DoWork += new DoWorkEventHandler(bgPopups_DoWork);
bgPopups.ProgressChanged += new ProgressChangedEventHandler(bgPopups_ProgressChanged);
bgPopups.RunWorkerCompleted += new RunWorkerCompletedEventHandler
(bgPopups_RunWorkerCompleted);
bgPopups.WorkerReportsProgress = true;
bgPopups.WorkerSupportsCancellation = true;
}
retVal = true;
}
catch (Exception exc)
{
MessageBox.Show("Error while Restoring: " + exc.Message, "Exception encountered", MessageBoxButtons.OK, MessageBoxIcon.Error);
//goto NextDB;
return false;
}
}
FIO = null;
return retVal;
}
// This DoWork event calls a method GeneratePopupInstances which makes copies of a window, which is shown as non-modal
private void bgPopups_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker helperBW = sender as BackgroundWorker;
int arg = (int)e.Argument;
//BackgroundProcessLogicMethod(helperBW, arg);
GeneratePopupInstances();
if (helperBW.CancellationPending)
{
e.Cancel = true;
}
}

Giving the editor focus with visual studio addin code

I have the following code which opens a visual studio ProjectItem node programatically as a code editor view.
void Commit(object sender, KeyPressEventArgs args)
{
if (args.KeyChar == (char)Keys.Return)
{
Close();
var selected = _FilteredList.FirstOrDefault();
if (selected != ""){
var item = _Items.Where(x => x.Name == selected).First();
if (item!=null)
{
Window win = item.Open(Constants.vsViewKindCode);
win.Visible = true;
win.SetFocus();
}
}
}
}
The problem is that the editor belonging to the window win is brought
to the top of the tab stack but the cursor doesn't give the editor focus.
Any trick to move the cursor focus to the editor?
This is worked for me:
Project activeProject = _applicationObject.Solution.Projects.Item(1);
ProjectItem a = activeProject.ProjectItems.Cast<ProjectItem>().FirstOrDefault(item => item.Name.EndsWith(".cs"));
Window win = a.Open();
win.Activate();
_applicationObject.ExecuteCommand("Edit.GoTo", String.Format("{0}", 2));
_applicationObject.ExecuteCommand("Edit.CharRight");
You can move the cursor to the required line with the "Edit.GoTo" command.
If you need to edit the code maybe an EditPoint is a better choice:
TextSelection ts;
ts = (TextSelection)_applicationObject.ActiveDocument.Selection;
EditPoint ep = (ts.ActivePoint).CreateEditPoint();
ep.StartOfDocument();

Resources