I'm having some problems calling a class or method in C# using Mono, can anyone give some help on what I'm doing wrong?
I want this piece of code:
public static void Execute(ScriptHost host)
{
try
{
TesteGUI teste = new TesteGUI(); //?
TesteGUI(); // ?
}
catch(Exception e)
{
}
finally
{
}
}
To call this piece of code:
public TesteGUI(Gtk.Window parentWindow) : base(Gtk.WindowType.Toplevel)
{
base.Modal = false;
base.TransientFor = parentWindow;
base.Decorated = false;
base.WindowPosition = WindowPosition.CenterAlways;
this.MyBuild();
base.KeyReleaseEvent += delegate(object o, KeyReleaseEventArgs args)
{
if (args.Event.Key == Gdk.Key.Escape)
{
this.Destroy();
}
};
}
What is my doing wrong and how can I make it work?
Thank you
You should do it like this:
public static void Execute(ScriptHost host)
{
try
{
TesteGUI teste = new TesteGUI(parentWindow); //where parentWindow is defined somewhere earlier and is of type Gtk.Window
}
catch(Exception e)
{
}
finally
{
}
}
Related
I have a WPF (.NET Framework 4.6) application that uses websocket-sharp (version 3.0.0) to create a websocket server.
I have a WebsocketServer and using EventHandler to tranfer event to MainWindow.xaml.cs but it not working. The MainWindow.xaml.cs listened to a RaiseOnScanDevice event but not any event invoked here.
I think this issue is relative to different thread. I try using Dispatcher.Invoke but it still not working.
System.Windows.Application.Current.Dispatcher.Invoke(new System.Action(() =>
{
RaiseOnScanDevice(this, new EventArgs());
}));
I found an issue (https://github.com/sta/websocket-sharp/issues/350) but the answers do not resolve my issue.
Please help me a solution for this issue.
WebsocketServer.cs file
public class WebsocketServer : WebSocketBehavior
{
private static readonly Lazy<WebsocketServer> lazyInstance = new Lazy<WebsocketServer>(() => new WebsocketServer());
public static WebsocketServer Instance
{
get
{
return lazyInstance.Value;
}
}
private const string TAG = "WebsocketServer";
private const string HOST_IP_ADDRESS = "127.0.0.2"; // localhost
private const int PORT = 38001;
public WebSocketServer socket;
private PacketHandler packetHandler = new PacketHandler();
public event EventHandler<EventArgs> RaiseOnScanDevice = new EventHandler<EventArgs>((a, e) => { });
public WebsocketServer()
{
Initialize();
}
public void Initialize()
{
socket = new WebSocketServer(IPAddress.Parse(HOST_IP_ADDRESS), PORT);
socket.AddWebSocketService<WebsocketServer>("/");
StartServer();
}
public void StartServer()
{
socket.Start();
}
public void StopServer()
{
socket.Stop();
}
protected override Task OnOpen()
{
return base.OnOpen();
}
protected override Task OnClose(CloseEventArgs e)
{
return base.OnClose(e);
}
protected override Task OnError(ErrorEventArgs e)
{
return base.OnError(e);
}
protected override Task OnMessage(MessageEventArgs e)
{
System.IO.StreamReader reader = new System.IO.StreamReader(e.Data);
string message = reader.ReadToEnd();
//Converting the event back to 'eventName' and 'JsonPayload'
PacketModel packet = packetHandler.OpenPacket(message);
HandleMessageFromClient(packet);
return base.OnMessage(e);
}
private void HandleMessageFromClient(PacketModel packet) {
var eventName = packet.EventName;
var data = packet.Data;
if (eventName == null || eventName.Equals(""))
{
return;
}
switch (eventName)
{
case SocketEvent.Hello:
Send("OK");
break;
case SocketEvent.ScanDevice:
ScanDevice();
break;
default:
break;
}
}
private void ScanDevice()
{
try
{
RaiseOnScanDevice(this, new EventArgs());
// or dispatch to Main Thread
System.Windows.Application.Current.Dispatcher.Invoke(new System.Action(() =>
{
RaiseOnScanDevice(this, new EventArgs());
}));
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
}
MainWindow.xaml.cs file
public partial class MainWindow : Window
{
public WebsocketServer WebsocketConnection
{
get { return WebsocketServer.Instance; }
}
public MainWindow()
{
InitializeComponent();
WebsocketConnection.RaiseOnScanDevice += SocketConnection_RaiseOnScanDevice;
}
private void SocketConnection_RaiseOnScanDevice(object sender, EventArgs e)
{
Console.WriteLine("SocketConnection_RaiseOnScanDevice");
}
The queue of messages is a good idea but you may want to use a lock to guard access to it. Most likely it won't be an issue but if you don't, you leave yourself open to the possibility of an error if the coroutine is reading from the queue as the websocket is writing to it. For example you could do something like this:
var queueLock = new object();
var queue = new Queue<MyMessageType>();
// use this to read from the queue
MyMessageType GetNextMessage()
{
lock (queueLock) {
if (queue.Count > 0) return queue.Dequeue();
else return null;
}
}
// use this to write to the queue
void QueueMessage(MyMessageType msg)
{
lock(queueLock) {
queue.Enqueue(msg);
}
}
I wonder what is the best way.
If I need to pass a class to a class constructor why should I use a variable inside my class.
Example:
using Beckhoff.App.Ads.Core.Plc;
Class test()
{
private static IBAAdsServer AdsServer;
private static IBAAdsCncClient _cncClient;
public test(IBAAdsServer _adsServer) //constructor
{
try
{
AdsServer = _adsServer;
_cncClient = AdsServer.GetAdsClient<IBAAdsCncClient>("CNC");
_cncClient.Synchronize = true;
}
catch (Exception Except)
{ MessageBox.Show("Error ! " + Except.Message); }
}
Why can't I do:
using Beckhoff.App.Ads.Core.Plc;
Class test()
{
private static IBAAdsCncClient _cncClient;
public test(IBAAdsServer _adsServer) //constructor
{
try
{
_cncClient = _adsServer.GetAdsClient<IBAAdsCncClient>("CNC");
_cncClient.Synchronize = true;
}
catch (Exception Except)
{ MessageBox.Show("Error ! " + Except.Message); }
}
I would like to use _adsServer in a lot of class not connected, how can I do that properly?
Thanks for help.
Ok, here is like I do now.
using Beckhoff.App.Ads.Core.Plc;
Class test()
{
private static IBAAdsServer AdsServer;
private static IBAAdsCncClient _cncClient;
public test(IBAAdsServer _adsServer) //constructor
{
try
{
AdsServer = _adsServer;
_cncClient = AdsServer.GetAdsClient<IBAAdsCncClient>("CNC");
_cncClient.Synchronize = true;
Classtocall newClass = ClasstoCall(_cncClient);//Passing the argument directly
}
catch (Exception Except)
{ MessageBox.Show("Error ! " + Except.Message); }
}
I'm trying to block specific images on a page from loading, but I've ran into a bit of trouble.
GeckoWebBrowser's HttpActivityObserver is returning a Not Implemented exception and crashing my program, so I'm trying to implement my own observer but the observe method isn't being called.
Any ideas would be helpful.
public class HttpObserver : nsIObserver
{
private nsIObserverService service;
private List<string> bans;
public HttpObserver()
{
bans = new List<string>();
service = Xpcom.CreateInstance<nsIObserverService>("#mozilla.org/observer-service;1");
}
public void Register()
{
service.AddObserver(this, "http-on-modify-request", false);
}
public void Unregister()
{
service.RemoveObserver(this, "http-on-modify-request");
}
public void BanUrl(string url)
{
bans.Add(url);
}
public void Observe(nsISupports aSubject, string aTopic, string aData)
{
nsIHttpChannel httpChannel = Xpcom.QueryInterface<nsIHttpChannel>(aSubject);
if (aTopic == "http-on-modify-request")
{
foreach (string url in bans)
{
if (url == httpChannel.GetURIAttribute().ToUri().AbsoluteUri)
{
httpChannel.Cancel(unchecked((int)0x804b0002));
}
}
}
}
}
Figured it out. For anyone else struggling with this, replace Xpcom.CreateInterface with Xpcom.GetService
Thanks, i try to find alternative BeforeNavigate2 and all you need just:
Gecko.GeckoWebBrowser wb = new GeckoWebBrowser { Dock = DockStyle.Fill, UseHttpActivityObserver = true };
wb.ObserveHttpModifyRequest += (o, e) => { MessageBox.Show(e.Uri.ToString()); };
I am new to c# and I don't know if I am doing this right. My problem is that I need to return the error from a class(.dll) but I don't know how.It only returns true or false. This is the code of my class:
namespace DigitalAssetConverter
{
public class ConvertImage
{
public Boolean ImagePath(string filePath)
{
try
{
MagickReadSettings settings = new MagickReadSettings();
settings.ColorSpace = ColorSpace.RGB;
using (MagickImage image = new MagickImage(filePath))
{
image.Read(filePath, settings);
image.Resize(500, 500);
image.Write(Path.ChangeExtension(filePath, ".jpg"));
return true;
}
}
catch
{
return false;
}
}
}
}
and I use it like this:
private void btnConvert_Click(object sender, EventArgs e)
{
ConvertImage ci = new ConvertImage();
if (ci.ImagePath(#"C:\tryConvert\LP_10078.eps"))
{
MessageBox.Show("Success!");
}
else
{
MessageBox.Show("Failed.");
}
}
Omit the try/catch block and make the return type void:
public void ImagePath(string filePath)
{
MagickReadSettings settings = new MagickReadSettings();
settings.ColorSpace = ColorSpace.RGB;
using (MagickImage image = new MagickImage(filePath))
{
image.Read(filePath, settings);
image.Resize(500, 500);
image.Write(Path.ChangeExtension(filePath, ".jpg"));
}
}
The exception (if any) will bubble up on its own, and you can place a try/catch block in the btnConvert_Click event to handle it instead:
private void btnConvert_Click(object sender, EventArgs e)
{
ConvertImage ci = new ConvertImage();
try
{
ci.ImagePath(#"C:\tryConvert\LP_10078.eps")
MessageBox.Show("Success!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
i'm trying to create an application which connects to internet and consume web services for every of it's operation.As far as i'm concerned i'll like to useasync method which i'm using already to get a collection of Contacts.I've realized that when i'm doing the same for groups (meaning getting groups async) i'm having errors in the calls , but when using normal call there ins't.So i did some research online and find that a lot of people has the same problem.
Some of them are asked to use WCF (for which i don't know jack).I'll like to know if there is another way to overcome this. if not can somebody point me to reliable resource online and help me get through it? thanks for reading and helping
here is my code:
public partial class main : Window
{
//...
private static vmcSession session;
private MyService service = new MyService();
private contactInfo[] loadedcontact;
//....
public main()
{
InitializeComponent();
//service.addContactCompleted +=new addContactCompletedEventHandler(addContactCompleted);
service.getContactsCompleted += new getContactsCompletedEventHandler(getContactsCompleted);
service.getGroupsCompleted += new getGroupsCompletedEventHandler(getGroupsCompleted);
fillContents();
}
private void getGroupsCompleted(object sender, getGroupsCompletedEventArgs e)
{
try
{
groupListBox.ItemsSource = e.Result;
}
catch (Exception ex)
{
MessageBox.Show(ex.InnerException.Message);
}
}
private void getContactsCompleted(object sender, getContactsCompletedEventArgs e)
{
try
{
loadedcontact = e.Result;
contactListBox.ItemsSource = loadedcontact;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void addContactCompleted(object sender, addContactCompletedEventArgs e)
{
throw new NotImplementedException();
}
public void fillContents()
{
displayUserInformation();
loadContacts();
service.getGroupsAsync(session.key, null);
//groupListBox.ItemsSource = service.getGroups(session.key, null);
cmbSenderIds.ItemsSource = service.getSenderIds(session.key, null);
if (cmbSenderIds.Items.Count > 0)
{
cmbSenderIds.SelectedIndex = 0;
}
loadGrid();
}
public void loadContacts()
{
service.getContactsAsync(session.key, null);
}
public void displayUserInformation()
{
lblName.Content = session.user.firstName;
lblEmail.Content = session.user.email;
lblCreditValue.Content = Decimal.Ceiling(session.user.balance).ToString();
}
public void loadGrid()
{
try
{
hitoryGrid.ItemsSource = service.viewMessages(session.key, null).ToList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
solve it.there are 2 methods with async calls, one with additional parameter Unique ID.each of the call needed ID, so i pass new GUID to it and that's it.thanks for trying helping me