I want to do something a simple as loading a webpage. For some reason Awesomium is not updating properties such as IsLoading, or triggering events such as DocumentReady or LoadingFrameComplete and I have no idea why, can anyone help me out?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Awesomium.Core;
namespace DownloaderTest
{
class ParsingHelper
{
WebView wv;
public ParsingHelper(WebView web)
{
this.wv = web;
}
public void ParsingInitiation(string link)
{
wv.LoadingFrameComplete +=wv_LoadingFrameComplete;
wv.Source = new Uri(link);
}
void wv_LoadingFrameComplete(object sender, FrameEventArgs e)
{
if(e.IsMainFrame)
{
//BeginParsing
((WebView)sender).LoadingFrameComplete -= wv_LoadingFrameComplete;
}
}
}
class Teste
{
WebView MainWeb = WebCore.CreateWebView(1024,768);
public object[] ObtainInformation(int id)
{
ParsingHelper ph = new ParsingHelper(MainWeb);
ph.ParsingInitiation("http://www.google.com");
//More code
return new object[] {};
}
}
}
If I run something like...
Teste t = new Teste();
t.ObtainInformation(1);
wv_LoadingFrameComplete is never triggered and I have no idea why.
try this code to detect page loaded completely
loadingFrameCompete event + IsLoading property
private void Awesomium_Windows_Forms_WebControl_LoadingFrameComplete(object sender, Awesomium.Core.FrameEventArgs e)
{
if (!webControl1.IsLoading)
MessageBox.Show("Page Loaded Completely");
}
Answered here: http://answers.awesomium.com/questions/2260/awesomium-not-loading-page-or-triggering-any-event.html
You are either using Awesomium in non UI environment (not WPF/WinForms control) and must call WebCore.Update() implicitly or you just blocking the same thread so it can't fire events.
Related
I am trying to get long touch gestures into my xamarin app. I have a view where a tap brings you to an edit screen & a long touch reveals an options menu. I followed this guide on SO about implementing such a thing. The item I want to be long touchable is a Frame, so I wrote an extension for Frame. Here is this class:
public class FrameWithLongTouchGesture : Frame
{
public FrameWithLongTouchGesture()
{
}
public EventHandler LongPressActivated;
public void HandleLongPress(object sender, EventArgs e)
{
//Handle LongPressActivated Event
EventHandler eventHandler = this.LongPressActivated;
eventHandler?.Invoke((object)this, EventArgs.Empty);
}
}
As you can see I have added an event handler to this object. Now I then went about implementing a custom renderer for each platform, I started with iOS (since I am an iOS dev). Worked absolutely no problem, took 5 minutes to get working. So now I've come round to android, this should be even easier since the post I linked earlier shows you how to implement the renderer in android... great!....
Not so great :( No long touch event is handled AT ALL with the exact code in the post. I have set breakpoints, tried to write to the console but the gesture event handler is never fired. I can even see that the phone receives a touch down event because it prints to the console when I run it on my test device. I have absolutely no idea why android isn't letting me recognise this gesture, I have also played around with androids GestureDetector but that never fired either. Here is my android renderer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Diagnostics;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Android.Content;
using Android.Views;
using Android.Widget;
using LongTouchGestureDemo;
using LongTouchGestureDemo.Droid;
[assembly: ExportRenderer(typeof(FrameWithLongTouchGesture), typeof(FrameWithLongTouchGestureRenderer))]
namespace LongTouchGestureDemo.Droid
{
public class FrameWithLongTouchGestureRenderer : FrameRenderer
{
FrameWithLongTouchGesture view;
//GestureDetector gesture;
public FrameWithLongTouchGestureRenderer(Context context) : base(context)
{
//gesture = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener());
this.LongClick += (object sender, LongClickEventArgs e) => {
view.HandleLongPress(sender, e);
};
}
protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
view = e.NewElement as FrameWithLongTouchGesture;
}
}
}
}
This is really frustrating because I cannot seem to implement core functionality into the android app. It doesn't help that I have no experience developing android, it doesnt seem as easy to implement gestures in droid as it does in iOS unfortunately :/
All help and suggestions are welcomed!
Thanks
You need a custom Gesture Listener to manage the long press. Here is the basic structure:
public class FrameWithLongTouchGestureRenderer : FrameRenderer
{
FrameWithLongTouchGesture view;
readonly MyGestureListener _listener;
readonly Android.Views.GestureDetector _detector;
public FrameWithLongTouchGestureRenderer()
{
_listener = new MyGestureListener();
_detector = new GestureDetector(_listener);
}
protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
view = e.NewElement as FrameWithLongTouchGesture;
UpdateEventHandlers();
}
}
private void UpdateEventHandlers()
{
_listener.MyFrame = view;
GenericMotion += (s, a) => _detector.OnTouchEvent(a.Event);
Touch += (s, a) => _detector.OnTouchEvent(a.Event);
}
}
And then your Gesture Listener:
internal class MyGestureListener : GestureDetector.SimpleOnGestureListener
{
public FrameWithLongTouchGesture MyFrame { private get; set; }
public override void OnLongPress(MotionEvent e)
{
base.OnLongPress(e);
if (MyFrame != null)
{
MyFrame.HandleLongPress(this, new System.EventArgs());
}
}
}
I'm wondering for a few days what's going on. I'm writing an app for Windows Phone 8.1 that uses HttpClient to download json string from Internet. It works fine BUT only once after running the app (in OnNavigatedTo event). Later, smashing 'Refresh' button that is supposed to download string again doesn't work. It's still the same string value that has been download as first. On server, this string changes and I can confirm that by looking at it in browser on PC.
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace WP8App
{
public sealed partial class MainPage : Page
{
private readonly Uri Website = new Uri("https://some-website.com/files/status.json");
private HttpClient http = new HttpClient();
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Refresh();
}
private async void Button_Refresh_Click(object sender, RoutedEventArgs e)
{
Refresh();
}
private async void Refresh()
{
var response = await http.GetStringAsync(Website);
JsonObject api = JsonConvert.DeserializeObject<JsonObject>(response);
TextBox_A.Text = api.value;
TextBox_B.Text = api.length;
TextBox_C.Text = api.size;
TextBox_F.Text = api.volume;
}
private async void ShowDialog(string value)
{
MessageDialog box = new MessageDialog(value);
await box.ShowAsync();
}
}
}
I'm not a master at async, so I count on your eagle eyes xD Thanks
Requests caching is very aggressive on Windows Phone. The easiest way to bypass it is adding a random parameter at the end of the URL. Something like:
private readonly string Website = "https://some-website.com/files/status.json?nocache={0}";
Then change the value every time you use it. Using the current timestamp is a good and cheap way to ensure that the URL will always be different:
var response = await http.GetStringAsync(new Uri(string.Format(Website, DateTime.UtcNow.Ticks));
I'm creating a checkout system for a supermarket. It consists of a checkout, server and MIS program an operates WCF services between them. The problem I have is that the checkout program, which is a windows form, does a few neccessaries in it's application_load method and then just quits.
Here's the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CheckoutLibrary;
using Checkout.ServerLibraryService;
using Checkout.MarketService;
namespace Checkout
{
public partial class theForm : Form
{
private static int checkoutID = 3;
private Product[] allProducts;
public theForm()
{
InitializeComponent();
}
private void theForm_Load(object sender, EventArgs e)
{
// First cache all products
SupermarketServiceSoapClient marketService = new SupermarketServiceSoapClient();
allProducts = marketService.GetAllProducts();
// Load the service provided by the server
ServiceClient serverService = new ServiceClient();
// Load the event handlers for the bar code scanner
BarcodeScanner scanner = new BarcodeScanner();
scanner.ItemScanned += new BarcodeScanner.ItemScannedHandler(scanner_ItemScanned);
scanner.AllItemsScanned += new BarcodeScanner.AllItemsScannedHandler(scanner_AllItemsScanned);
scanner.Start(checkoutID);
}
void scanner_AllItemsScanned(EventArgs args)
{
throw new NotImplementedException();
}
void scanner_ItemScanned(ScanEventArgs args)
{
itemTextBox.Text = "Scanned " + GetItemName(args.Barcode);
}
private void scanItemButton_Click(object sender, EventArgs e)
{
scanner_ItemScanned(new ScanEventArgs(GetRandBarcode()));
}
// A barcode -> product name look up method
public string GetItemName(int barcode)
{
return allProducts[barcode].Description + " # " + allProducts[barcode].Price;
}
// Method to grab a random barcode for simulation
private int GetRandBarcode()
{
Random rand = new Random();
return rand.Next(0,500);
}
}
}
And program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace Checkout
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new theForm());
}
}
}
Thanks for any insight.
In WinForms, if your form_load throws an exception, it quits without displaying anything. Annoying, but I'm guessing that's the problem.
You can try a try/catch, or you can hit CTRL+ALT+E and check the Thrown Column for Common Language Runtime Exceptions to see the error.
UPDATE:
Based on comments, here's a sample way to execute something on another thread.
ThreadStart ts = new ThreadStart(() => {
try {
scanner.Start(checkoutID);
} catch {
// Log error
}
});
Thread t = new Thread(ts);
t.Start();
I'm creating a custom C# control (form's title bar). One form can have only one title bar, and that's why i'm wondering something: When user (programmer) adds my title bar to his form, is there ANY way i can check if ParentForm already contains my title bar, and if so can i cancel adding another instance of my control?
I know how to perform check to see types of controls ParentForm contains, but what event is raised when my control is dropped from toolbox to form, and how to "cancel" layout of my control if necessary?
You should read in-depth about the designer technologies available in .NET, because these are not what I would call production-ready examples. However, this gives you a solid start and both code snippets do what you are asking.
For design time, you can override the designer site in your control and do the following:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel.Design;
using System.Diagnostics;
namespace WindowsFormsControlLibrary1 {
public partial class DebugControl : UserControl {
public DebugControl() {
InitializeComponent();
}
public override ISite Site
{
get
{
return base.Site;
}
set
{
base.Site = value;
IComponentChangeService service = (IComponentChangeService)GetService(typeof(IComponentChangeService));
service.ComponentAdding += (sender, e) => {
IDesignerHost host = (IDesignerHost)value.Container;
Component component = (Component)host.RootComponent;
if (component as Form != null)
{
Form form = (Form)component;
foreach (Control c in form.Controls)
{
if (c.GetType() == this.GetType())
{
throw new System.ArgumentException("You cannot add two of these controls to a form!");
}
}
}
};
}
}
}
}
For runtime in your form you can override OnControlAdded and do the following:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using WindowsFormsControlLibrary1;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
protected override void OnShown(EventArgs e)
{
Controls.Add(new DebugControl());
}
protected override void OnControlAdded(ControlEventArgs e)
{
base.OnControlAdded(e);
if (e.Control.GetType() == typeof(DebugControl))
{
int count = 0;
foreach (Control c in Controls)
{
if (c is DebugControl)
{
count++;
}
}
if (count > 1)
{
Controls.Remove(e.Control);
Debug.Assert(false, "Cannot add two of these controls!");
}
}
}
}
}
There are more than one way to do this, but these are rough examples, mind you. Read up on design-time support that the .NET framework, it is very rich and there are extensive documentation on it. Another method is to implement custom designers and implement CanBeParentedTo and CanParent, but mind you CanBeParentedTo is not called when your control is drug from the ToolBox to your form.
You may use Controls collection of the active form.
Handle the ParentChanged event, check the parent's Controls, and throw an exception if necessary.
I am rewriting my last question, just because I am trying to attack the problem from differente angles..
The problem is this. I have a class written in C#, with two public methods, and an eventhandler that triggers everytime any of the methods is completed.
I created this class adapting the code from a Form.
Now, if I reference this class from a Windows Process project written in VB.Net, and I call any of the two methods, the EventHandler will NOT trigger
Could this problem be related to EventHandler's scope or anything like that?
If necessary, I can post code
Thanks
++++++++++++++++++++++++
UPDATE
++++++++++++++++++++++++
Ok.. here is the code. Originally I was calling the methods from a class, but I modified the whole project just to see if the problem had to do with trying to raise the event from the class... So I have this c# webserver listening on port 8080, and upon http request calls ENROLL or IDENTIFY according to URL parameters.
Just to clarify a bit. This is a webserver that will run in a computer which has a USB fingerprint scanner connected. Then, the web application will do an http request to that computer in order to execute an IDENTIFICATION or ENROLLMENT, actions which are programmed inside the webserver, manipulating the methods included in the scanner's driver which I got with the SDK.
In have a C# demo project which came with the driver's SDK, a simple form with buttons calling ENROLL or IDENTIFY methods from the CLICK event. After the CLICK event is finished (inside of which is executed the ENROLL or IDENTIFY methods) then the Event is triggered and the EventHandler executes.
So now I have all the code in the same project, but it is still behaving the same way... it goes into the ENROLL method which executes the StartEnroll method from the WisSensorNLibLib class, but the event is not triggered nor captured by the class' custom Event Handler...
Maybe I am misplacing the definitions or the instantiations... I don't know. But the event is not triggered...
So here is the code... (and below I will paste the original Demo program code, so maybe by comparison someone can find out what the problem could be)
namespace WinServer
{
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
//************************************
//This is the class that belongs to the Fingerprint Scanner
//************************************
using WisSensorNLibLib;
class WinServer
{
private TcpListener myListener ;
private int port = 8080 ; // Select any free port you wish
private Int16 id;
private string indx;
//************************************
//Create instance of WisSensorN
//************************************
WisSensorN WisObj = new WisSensorN();
private String mod;
private Int32 Rows;
public WinServer()
{
try
{
myListener = new TcpListener(IPAddress.Any, port) ;
myListener.Start();
Thread th = new Thread(new ThreadStart(StartListen));
th.Start() ;
}
catch(Exception e)
{
Console.WriteLine("An Exception Occurred while Listening :" +e.ToString());
}
}
public void SendHeader(string sHttpVersion, string sMIMEHeader, int iTotBytes, string sStatusCode, ref Socket mySocket)
{
//************************************
//Code not related to understand specific problem was removed
//************************************
}
public void SendToBrowser(String sData, ref Socket mySocket)
{
//************************************
//Code not related to understand specific problem was removed
//************************************
}
public void SendToBrowser(Byte[] bSendData, ref Socket mySocket)
{
//************************************
//Code not related to understand specific problem was removed
//************************************
}
// Application Starts Here..
public static void Main()
{
WinServer MWS = new WinServer();
}
public void StartListen()
{
//Call ENROLL method
Enroll();
mySocket.Close();
}
//**********************************
//EVENT CAPTURE
//**********************************
public void WisObj_DataEvent(WisSensorNLibLib.DATA data, string str)
{
switch (data)
{
//ENROLL
case DATA.DATA_ENROLL:
try
{
Console.WriteLine("success");
}
catch (Exception ee)
{
Console.WriteLine(ee.Message);
}
break;
//IDENTIFY
case DATA.DATA_IDENTIFY_CAPTURE:
try
{
Console.WriteLine("Success");
}
catch (Exception ee)
{
Console.WriteLine(ee.Message);
}
break;
}
}
//**********************************
//ENROLL
//After this method ends, WisObj_DataEvent should capture the event
//**********************************
public void Enroll()
{
try
{
WisObj.Open();
WisObj.DataEvent += new _IWisSensorNEvents_DataEventEventHandler(WisObj_DataEvent);
WisObj.StartEnroll();
}
catch
{
Console.WriteLine(ee.Message);
}
}
//**********************************
//IDENTIFY
//After this method ends, WisObj_DataEvent should capture the event
//**********************************
public void Identify()
{
try
{
WisObj.Open();
WisObj.DataEvent += new _IWisSensorNEvents_DataEventEventHandler(WisObj_DataEvent);
WisObj.IdentifyCapture();
}
catch
{
Console.WriteLine(ee.Message);
}
}
public void WisClose()
{
WisObj.Close();
}
}
}
Original Demo program code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WisSensorNLibLib;
namespace OR200N_Demo
{
public partial class Form1 : Form
{
private const int MaxUser = 10;
WisSensorN WisObj = new WisSensorN();
string[] DB = new string[MaxUser];
int nEnrolled = 0;
string indx;
string msg;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show("Please make sure the scanner is plugged!!");
WisObj.Open();
WisObj.DataEvent += new _IWisSensorNEvents_DataEventEventHandler(WisObj_DataEvent);
WisObj.SetDisplay((int)FingerPic.Handle);
}
private delegate void CompleteHandler(string bir);
private void Complete(string str)
{
Status.Text = str;
}
private void WisObj_DataEvent(WisSensorNLibLib.DATA data, string str)
{
switch (data)
{
case DATA.DATA_ENROLL:
indx = nEnrolled.ToString();
msg = "User #" + indx + " is enrolled successfully!!";
this.Invoke(new CompleteHandler(Complete), new object[] { msg });
DB[nEnrolled] = string.Copy(str);
nEnrolled++;
break;
case DATA.DATA_IDENTIFY_CAPTURE:
int nMatched;
nMatched = WisObj.Identify(str, DB);
if (nMatched < 0)
{
msg = "No valid finger matched!!";
this.Invoke(new CompleteHandler(Complete), new object[] { msg });
}
else
{
indx = nMatched.ToString();
msg = "User #" + indx + " is matched!!";
this.Invoke(new CompleteHandler(Complete), new object[] { msg });
}
break;
case DATA.DATA_VERIFY_CAPTURE:
break;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
WisObj.Close();
}
private void Enroll_Click(object sender, EventArgs e)
{
if (nEnrolled >= MaxUser)
{
MessageBox.Show("Exceed maximum enrolled number (10)!!");
}
else
{
Status.Text = "Please put your finger on the scanner!!";
WisObj.StartEnroll();
}
}
private void Identify_Click(object sender, EventArgs e)
{
Status.Text = "Please put your finger on the scanner!!";
WisObj.IdentifyCapture();
}
}
}
Firstly, it is event, not event handler, which is being raised.
Event handler is a method that subsribes to a given event.
Secondly, scope only governs member visibility at compile time and does not affect event subscriptions. If event is visible, it works.
From what you posted, one may only conclude that:
You may not subscribe to event in VB .NET code or may handle it incorrectly;
When called from VB .NET code, these methods may act differently (different parameters being passed? exeptions thrown?) and may not raise the event.
So far, this is all I can say until I see the code.
Can you trim it down to simplest reproducible case?