I am trying to make an application with 5 virtual(hidden) Gecko(Xulrunner) Browser. But when I try to create one browser in Threading its return error at GeckoPreferences I am totally confused with it!
Here code Sample:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Skybound.Gecko;
using System.Threading;
namespace Gekco_Test
{
public partial class Main : DevExpress.XtraEditors.XtraForm
{
public Main()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
private void Main_Load(object sender, EventArgs e)
{
}
private void simpleButton1_Click(object sender, EventArgs e)
{
Thread th = new Thread(webControllerFunc);
th.SetApartmentState(ApartmentState.STA);
th.Start();
}
void webControllerFunc()
{
geckoWebControl gControll = new geckoWebControl();
gControll.webBrowserAccess("91.213.108.178", 80);
}
}
class geckoWebControl
{
bool readyState;
GeckoWebBrowser wb = new GeckoWebBrowser();
public string webBrowserAccess(string host,int port)
{
Skybound.Gecko.Xpcom.Initialize(Application.StartupPath + "\\xulrunner\\");
readyState = false;
Form form = new Form();
GeckoPreferences.User["network.proxy.http"] = host;
GeckoPreferences.User["network.proxy.http_port"] = port;
GeckoPreferences.User["network.proxy.type"] = 1;
wb.Navigate("about:blank");
wb.DocumentCompleted += wb_DocumentCompleted;
while (!readyState)
Application.DoEvents();
return wb.Document.TextContent;
}
void wb_DocumentCompleted(object sender, EventArgs e)
{
readyState = true;
}
}
}
Error:
{"Unable to cast COM object of type 'System.__ComObject' to interface type 'Skybound.Gecko.nsIServiceManager'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{8BB35ED9-E332-462D-9155-4A002AB5C958}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE))."}
Thanks!
Gecko Doesn't support multithreading. So you can use it following code to use it in the threads.
this.BeginInvoke(new Action(() => {
//What you want gecko browser to do! Like:
geckoBrowser.navigate("http://somewhere.com");
}));
Related
I am using Gma.System.MouseKeyHook and getting the following exception:
Managed Debugging Assistant 'CallbackOnCollectedDelegate'
Message=Managed Debugging Assistant 'CallbackOnCollectedDelegate' : 'A callback was made on a garbage collected delegate of type 'Gma.System.MouseKeyHook!Gma.System.MouseKeyHook.WinApi.HookProcedure::Invoke'. This may cause application crashes, corruption and data loss. When passing delegates to unmanaged code, they must be kept alive by the managed application until it is guaranteed that they will never be called.'
I've tried to handle the function calls and subscription. However, the issue still persists. Also I try to run it many times, occasionally it gives a 'NullReferenceException' as well. It also confused me a lot, maybe those issues are correlated.
using Gma.System.MouseKeyHook;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
// Uses a MouseKeyHook Library license at
https://github.com/gmamaladze/globalmousekeyhook/blob/master/LICENSE.txt
namespace TransparentClickTest {
public partial class Form1 : Form {
public Form1() {
//GC.TryStartNoGCRegion(100);
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
BackColor = Color.Red;
TransparencyKey = Color.Red;
InitializeComponent();
OnDown();
}
protected virtual void OnUp() {
Hook.GlobalEvents().MouseUp += (sender, e) => {
try {
label1.Text = "Mouse Up!!!";
Hook.GlobalEvents().Dispose();
OnDown();
}
catch(Exception e2) {
Hook.GlobalEvents().Dispose();
OnDown();
}
};
}
protected virtual void OnDown() {
Hook.GlobalEvents().MouseDown += (sender, e) => {
try {
label1.Text = $"Mouse {e.Button} Down at {e.X}, {e.Y}";
Opacity = 1;
Hook.GlobalEvents().Dispose();
OnUp();
}
catch(Exception e1) {
Hook.GlobalEvents().Dispose();
OnUp();
}
};
}
private void PictureBox1_Click(object sender, EventArgs e) {
}
private void Label1_Click(object sender, EventArgs e) {
}
}
}
add this: private static IKeyboardMouseEvents HookEvents = null;
use HookEvents.MouseDown replace Hook.GlobalEvents().MouseDown
The code is as follows:
The ServerForm Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SimpleTCP;
namespace TCPIP
{
public partial class ServerForm : Form
{
public ServerForm()
{
InitializeComponent();
}
SimpleTcpServer server;
private void Form1_Load(object sender, EventArgs e)
{
server = new SimpleTcpServer();
server.Delimiter = 0x13; //enter
server.StringEncoder = Encoding.UTF8;
server.DataReceived += Server_DataReceived;
}
private void Server_DataReceived(object sender, SimpleTCP.Message e)
{
StatusText.Invoke((MethodInvoker)delegate ()
{
StatusText.Text = e.MessageString;
e.ReplyLine(string.Format("You said: {0}",e.MessageString));
});
// throw new NotImplementedException();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void StartButton_Click(object sender, EventArgs e)
{
StatusText.Text += "Server Starting !";
System.Net.IPAddress ip = new System.Net.IPAddress(long.Parse(HostText.Text)); //error here
server.Start(ip,Convert.ToInt32(PortText.Text));
}
private void StopButton_Click(object sender, EventArgs e)
{
if(server.IsStarted)
{
server.Stop();
}
}
}
}
The Code of the ClientForm is as follows:
using SimpleTCP;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Client
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SimpleTcpClient client;
private void ConnectButton_Click(object sender, EventArgs e)
{
ConnectButton.Enabled = false;
}
private void Form1_Load(object sender, EventArgs e)
{
client = new SimpleTcpClient();
client.StringEncoder = Encoding.UTF8;
client.DataReceived += Client_DataReceived;
}
private void Client_DataReceived(object sender, SimpleTCP.Message e)
{
StatusText.Invoke((MethodInvoker)delegate ()
{
StatusText.Text = e.MessageString;
//...
});
//throw new NotImplementedException();
}
private void SendButton_Click(object sender, EventArgs e)
{
client.WriteLineAndGetReply(TextMessage.Text, TimeSpan.FromSeconds(4));
}
}
}
The issue in the above code is that it is 'build'ing correctly and even when I am debug it with the new instance, the code is running fine, but will I debug, as soon as I press the "start" button in the Server form it shows the error in line :
System.Net.IPAddress ip = new System.Net.IPAddress(long.Parse(HostText.Text));
The error is: System.FormatException: 'Input string was not in a correct format.'
Please refer the Screenshot for details and suggest a potential fix to the issue.Image of Screenshot of Error inLine
Clearly HostText.Text is returning a value that can't be parsed into a long.
This exception is coming from long.Parse, which is really a language shortcut for Int64.Parse, whose documentation states that it will throw this exception if the input string is not formatted correctly.
Trying to receive data, from mk, using DataReceived and handler event, what i do is -
push a button on a program (code is below) then LED on mk will turn on, then the data should be sent back to program (expecting 1, on byte value, but also tried string value, doesn't work). Sending side is working, but receiving....not
seems like i'm missing something. Any help apreciate it. Thx in Further
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
namespace WindowsFormsApplication11
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) // As i understood, here we configure where i data will be shown,
// trying to get it on TextBox1
{
SerialPort sp = (SerialPort)sender;
richTextBox1.Text += sp.ReadExisting() + "\n";
}
private void button1_Click(object sender, EventArgs e) // There are a main actions, first i receive data then send data by a click.
{
serialPort1.Write("\u0001");
serialPort1.Close();
System.ComponentModel.IContainer components = new System.ComponentModel.Container(); //
serialPort1 = new System.IO.Ports.SerialPort(components);
serialPort1.PortName = "COM4";
serialPort1.BaudRate = 9600;
serialPort1.DtrEnable = true;
serialPort1.Open();
serialPort1.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
}
}
}
The serial port is on a different thread than the UI. So when you receive a character, as you haven't invoked the UI, you get an exception and the UI is not updated.
Invoke the UI first in your DataReceivedHandler. You could do something like that:
public static class ControlExt
{
public static void InvokeChecked(this Control control, Action method)
{
try
{
if (control.InvokeRequired)
{
control.Invoke(method);
}
else
{
method();
}
}
catch { }
}
}
public partial class Form1 : Form
{
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
this.InvokeChecked(delegate
{
richTextBox1.Text += serialPort1.ReadExisting() + "\n";
richTextBox1.SelectionStart = Text.Length;
richTextBox1.ScrollToCaret();
});
}
}
I'm trying to show online/offline contacts from Skype, but I get an error:
An unhandled exception of type
'System.Runtime.InteropServices.COMException' occurred in
WindowsFormsApplication2.exe
Additional information: Retrieving the COM class factory for component
with CLSID {830690FC-BF2F-47A6-AC2D-330BCB402664} failed due to the
following error: 80040154.
Debugger says that an error is in: Skype skype = new Skype();
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 SKYPE4COMLib;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
Skype skype = new Skype();
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(loadContacts));
thread.IsBackground = true;
thread.Priority = System.Threading.ThreadPriority.AboveNormal;
thread.Name = "Load Skype Contacts";
thread.Start();
}
private void button1_Click(object sender, EventArgs e)
{
}
List<string> contacts = new List<string>();
public void loadContacts()
{
contacts.Clear();
if (radioButton1.Checked)
{
foreach(User user in skype.Friends)
{
contacts.Add(user.Handle);
}
}
else if (radioButton2.Checked)
{
foreach (User user in skype.Friends)
{
if (user.OnlineStatus == TOnlineStatus.olsOnline | user.OnlineStatus == TOnlineStatus.olsNotAvailable | user.OnlineStatus == TOnlineStatus.olsDoNotDisturb | user.OnlineStatus == TOnlineStatus.olsAway)
{
contacts.Add(user.Handle);
}
}
}
MethodInvoker lvUpdate = delegate
{
listView1.Items.Clear();
foreach (var user in contacts)
{
listView1.Items.Add(user);
}
listView1.Sorting = SortOrder.Ascending;
if (radioButton1.Checked)
{
radioButton1.Text = String.Format("Online ({0})", listView1.Items.Count);
}
else if (radioButton2.Checked)
{
radioButton2.Text = String.Format("All contacts ({0})", listView1.Items.Count);
}
};
Invoke(lvUpdate);
}
}
}
I found the solution.
Build -> Configuration Manager -> Acitve solution platform -> New -> x86 (instead of x64)
This helped.
my code is working fine but also I am receiving lot of WSAECONNRESET An existing connection was forcibly closed by the remote host. error.
I have a Chilkat.Socket Listener exe which is executing as a windows service and a test program which is simply sending strings data to this listener service. Listener is working fine but the program which is generatring strings and sending it to the listener is receiving the below mentioned error...please guide.
Error:
ChilkatLog:
SendString:
DllDate: Jan 19 2012
UnlockPrefix: XXXXSocket
Username: XXXXXX
Architecture: Little Endian; 64-bit
Language: .NET 4.0 / x64
fd: 0x510
objectId: 1433
NumChars: 111
Charset: ansi
NumBytes: 111
SocketError: WSAECONNRESET An existing connection was forcibly closed by the remote host.
For more information see this Chilkat Blog post: http://www.cknotes.com/?p=217
Error sending on socket
send_size: 111
Failed.
This is my windows service code running as a listner
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Windows.Forms;
using Chilkat;
using NLog;
using Newtonsoft.Json;
namespace Test.Services.MessageServer
{
public partial class MessageProcessor : ServiceBase
{
private Chilkat.Socket _socket;
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public MessageProcessor()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
init();
}
protected override void OnStop()
{
}
private void init()
{
_socket = new Chilkat.Socket();
_logger.Info("Service starting...");
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//_logger.Info("Service started");
var success = _socket.UnlockComponent("XXXXXXSocket_XXXXXXXXX");
try
{
if (success != true)
{
return;
}
success = _socket.BindAndListen(5555, 25);
if (success != true)
{
_logger.Error(String.Format("Error: {0}", _socket.LastErrorText));
return;
}
// Get the next incoming connection
// Wait a maximum of 0 seconds (0000 millisec)
Chilkat.Socket connectedSocket = null;
connectedSocket = _socket.AcceptNextConnection(0);
if (connectedSocket == null)
{
_logger.Error(String.Format("Error: {0}", _socket.LastErrorText));
return;
}
connectedSocket.MaxReadIdleMs = 1000;
string txt = connectedSocket.ReceiveUntilMatch("-EOM-");
_logger.Info(String.Format("Received Orignal Message: {0}", txt));
if (txt == string.Empty)
{
_logger.Error(String.Format("Error: {0}", _socket.LastErrorText));
return;
}
connectedSocket.Close(0);
((BackgroundWorker)sender).ReportProgress(0, txt.Replace("-EOM-", string.Empty).Trim());
}
catch (Exception ex)
{
_logger.Error(String.Format("Error caught: {0}", _socket.LastErrorText));
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState == null) return;
_logger.Info((String.Format("Message Received: {0}", e.UserState.ToString())));
var obj = JsonConvert.DeserializeObject<JsonGeoLocation>(e.UserState.ToString());
_logger.Info((String.Format("Received: JobId: {0}\tDateTime: {1}\tLatitude: {2}\tLongitude: {3}", obj.F0,obj.F1,obj.F2.F0,obj.F2.F1)));
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
}
}
This is my code which is connecting to the above code and sending the messages
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Chilkat;
using NLog;
using Newtonsoft;
using Newtonsoft.Json;
namespace SocketMessageGenerator
{
public partial class Form1 : Form
{
//private Chilkat.Socket _socket;
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public Form1()
{
InitializeComponent();
Init();
}
private void Init()
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
SendMessage();
}
private void SendMessage()
{
var socket = new Socket();
var success = socket.UnlockComponent("XXXXXXSocket_XXXXXXXXX");
try
{
if (success != true)
{
return;
}
success = socket.Connect("191.111.009.256", 5555, false, 0);
if (!success)
{
_logger.Info((String.Format("Error: \nunable to connect to host: {0}", socket.LastErrorText)));
}
var geoLocation = new JsonGeoLocation { F0 = 123, F1 = System.DateTime.Now, F2 = new JsonGeoPosition { F0 = 51.577790260314941, F1 = 0.0993499755859375 } };
var obj = JsonConvert.SerializeObject(geoLocation);
success = socket.SendString(message);
//success = socket.SendString(obj);
if (!success)
{
_logger.Info((String.Format("Error: \nunable to send message: {0}", socket.LastErrorText)));
}
socket.Close(1000);
}
catch (Exception)
{
throw;
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
}
}