I would like to add a REST API server to my WinForms application. I have chosen to use Grapveine for that purpose.
Here's my code:
namespace RestServerTest
{
public partial class Form1 : Form
{
private RestServer mServer;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
mServer = new RestServer();
mServer.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
mServer.Stop();
mServer.Dispose();
}
}
[RestResource]
class MyRoute
{
[RestRoute]
public IHttpContext HelloWorld(IHttpContext context)
{
// Todo: how access form object from here?
context.Response.SendResponse("Hello, world.");
return context;
}
}
}
Currently I have no idea how to actually access my Form object from the REST route (without using an ugly global/static variable).
How would one do that elegantly?
If you want the current form (or any other object/variable in your project) to be accessible to your routes, you can take advantage of Dynamic Properties. Both the IRestServer and IHttpContext implement IDynamicProperties, which gives you two ways to accomplish your goal.
Add either of these to your Form1_Load() method.
Add a Reference On The Server
server.Properties.Add("CurrentForm", this);
Add a BeforeRouting Event Handler
server.Router.BeforeRouting += cxt =>
{
cxt.Properties.Add("CurrentForm", this);
};
Access a Property In a Route
In either case, you can access the property using the built in extensions methods:
// On the server
var form = context.Server.GetPropertyValueAs<Form1>("CurrentForm");
// On the context
var form = context.GetPropertyValueAs<Form1>("CurrentForm");
Related
First I know there are already answer for this question but most solution seems complicated for nothing.
Situation :
I have a form called frm1. I want to pass it as parameter
myfunc(ref frm1)
I would then do
private void myfunc(ref Form frm1)
It says : frm1 is a type but is used as a variable.
My reason for doing this is because depending on choice I pass my form to one of either two functions which fills it differently.
Problem :
However I cannot pass as argument my form. However I can pass other controls like button in the same way. How can I do this simply with the form, without interface etc...
There is something wrong with the way you are passing the parameter in. Are you definitely passing in the instance and not the type?
Here's a working example.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Name = "form";
Form f = this;
doSomethingWithForm(f);
}
private void doSomethingWithForm(Form f)
{
Console.WriteLine(f.Name);
}
}
I have created one function. I think it will help you. I am using this in my practice.
-->function below:
public void showForm(Form _form, Form _main) {
if (_main != null)
{
if (_main.ActiveMdiChild != null)
{
_main.ActiveMdiChild.Close();
}
_form.MdiParent = _main;
_form.Activate();
_form.Show();
}
else
{
_form.Activate();
_form.ShowDialog();
}
-->how to use it:
objLib.showForm(new frmMain(), null);
OR
objLib.showForm(new frmNewspaper(), this);
Thank You
I will add to kenjara's answer.
// For example: change color of the form - from some other method
private void Form_Load(object sender, EventArgs e)
{
ChS = new ChangeSomething();
ChS.ChangeBackColor(this);
}
public class ChangeSomething
{
public void ChangeBackColor(Form form)
{
form.BackColor = System.Drawing.Color.Black;
return;
}
}
Tested VS2022 / .NET4.8 / Windows Forms
Im new to .net and this is also my first post here so apologies in advance for any newb mistakes I may be doing:)
Background of the problem.
I’m working on a C# project and as part of it I have to store windows form data onto a database. I am using a data class “person” to transport the windows form data to a class responsible for accessing the database on the windows forms behalf. I wish to use the Singleton pattern on the windows forms code to prevent multiple instances of the window from existing.
Problem
In the save buttons event handling code I wish to create a “Person” object, populate it with user entered values and send it to be saved onto the database. The problem occurs here. The “Person” object does not get populated!
I’ve tried doing this in another form where I have not modified the code to accommodate the singleton pattern and that works.
So what am I doing wrong here? Is there a way for me to still keep the singleton pattern and make it work?
Window Form Code
namespace AgTrain
{
public partial class CreateAdmin : Form
{
private static CreateAdmin instance;
private CreateAdmin()
{
InitializeComponent();
}
private void CreateAdmin_Load(object sender, EventArgs e)
{
}
public static CreateAdmin getInstance()
{
if(instance==null)
{
instance = new CreateAdmin();
instance.InitializeComponent();
}
return instance;
}
public void makeInstanceNull()
{
instance = null;
}
private void button1_Click(object sender, EventArgs e)
{
Person personToBeSaved = new Person();
PersonDAO personDAO = new PersonDAO();
personToBeSaved.FirstName = textBox1.Text;
personToBeSaved.LastName = textBox2.Text;
personToBeSaved.Address = textBox3.Text;
personToBeSaved.TelNo = textBox4.Text;
personToBeSaved.UserName = textBox5.Text;
personToBeSaved.Password = textBox6.Text;
personToBeSaved.UserType = "admin";
personDAO.addPerson(personToBeSaved);
}
}
}
Caller Code
private void createAdminToolStripMenuItem_Click(object sender, EventArgs e)
{
CreateAdmin creAdmin = CreateAdmin.getInstance();
creAdmin.Closed += (s, ex) => { creAdmin.makeInstanceNull(); };
creAdmin.MdiParent=this;
creAdmin.Show();
}
Thanks.
Dumidu
You are calling InitializeComponent twice.
Try that:
private static CreateAdmin _instance;
public static CreateAdmin Instance
{
get { return _instance ?? (_instance = new CreateAdmin()); }
}
In my opionion is thefiloe's solution the cleanest, but there is a further possibility to introduce (effective) singletons in C#:
public static readonly CreateAdmin Instance = new CreateAdmin();
Client Code:
CreateAdmin.Instance.DoSomething()
But as already mentioned I recommend thefiloe's way!
Im making a program what connects to multiple 3th party systems. The connect with different formats so i created multiple classes to deal with them. I have now three 4 classes.
The MainForm is the first class. This is the basic windows form class with the user interface.
SDKCommunication is the second class.
VMS (this class handles the events given of by the 2th party system and activates methods on SDK COmmunication)
Events
Events Class
public class Events
{
public event EventHandler LoginStateChanged;
private bool loginstate;
public bool LogInState
{
get { return this.loginstate; }
set
{
this.loginstate = value;
if (this.LoginStateChanged != null)
this.LoginStateChanged(this, new EventArgs());
}
}
}
part of SDKCommunicatie class
Events events = new Events();
public void onLogon(string username, string directory, string system)
{
events.LogInState = false;
}
MainForm Class
SDKCommunicatie sdkcommunicatie = new SDKCommunicatie();
Events events = new Events();
public MainForm()
{
InitializeComponent();
events.LoginStateChanged += new EventHandler(events_LoginStateChanged);
}
void events_LoginStateChanged(object sender, EventArgs e)
{
log.Info("EventFired loginstateChanged");
}
When the LogInState Changes in the SDKCommunicatie class. There needs to be an event fired in the MainForm class. But sadly that doesn't work.
But when I change the loginstate in the mainform(with a buttonclick)(see code below) the event is fired. But that is not the intention i would like to have.
private void button1_Click(object sender, EventArgs e)
{
events.LogInState = true;
}
If my question isn't clear enough, please let me know.
VMS class Added as reply to #Astef
class VMS {
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(MainForm));
GxUIProxyVB m_UIProxy = new GxUIProxyVB();
public string username2;
public string directory2;
public string Status;
public void initOmni()
{
m_UIProxy.CreateInstance();
m_UIProxy.OnLogon += new _IGxUIProxyVBEvents_OnLogonEventHandler(m_UIProxy_OnLogon);
m_UIProxy.OnLogoff += new _IGxUIProxyVBEvents_OnLogoffEventHandler(m_UIProxy_OnLogoff);
m_UIProxy.OnError += new _IGxUIProxyVBEvents_OnErrorEventHandler(m_UIProxy_OnError);
m_UIProxy.OnAlarmStatusEx2 += new _IGxUIProxyVBEvents_OnAlarmStatusEx2EventHandler(m_UIProxy_OnAlarmStatusEx2);
}
public void login(string username, string password, string directory)
{
username2 = username;
directory2 = directory;
initOmni();
m_UIProxy.LogOn(directory, username, password,false);
}
public void logOff()
{
m_UIProxy.LogOff();
}
void m_UIProxy_OnLogon()
{
SDKCommunicatie sdkcommunicatie = new SDKCommunicatie();
sdkcommunicatie.onLogon(username2, directory2, "Genetec Omnicast");
}
I have fixed this with deleting the following:
SDKCommunicatie sdkcommunicatie = new SDKCommunicatie();
And adding the following in the base of VMS:
SDKCommunicatie sdkcommunicatie;
But now i got a new error in the mainform when i tried to call a class in SDKCommunicatie
connectedStatus = sdkcommunicatie.connectedStatus();
I got the following error:
NullReferenceException was unhandled
You are not using the same instance of the Events class, and that's why on button click you catch LoginStateChanged. You should inject the same instance of Events class to SDKCommunicatie class, then you'll be able to listen to event changes.
Edit:
Jeremy Todd and I were both writing at the same time.
Events in your SDKCommunicatie are not fired because you've created an individual instance of class Events for it. That is not the instance you have placed on the MainForm.
Inject the right instance (pass a reference) to SDKCommunicatie from MainForm through constructor, property or somehow else. For example:
MainForm:
SDKCommunicatie sdkcommunicatie;
Events events = new Events();
public MainForm()
{
InitializeComponent();
events.LoginStateChanged += new EventHandler(events_LoginStateChanged);
sdkcommunicatie = new SDKCommunicatie(events);
}
void events_LoginStateChanged(object sender, EventArgs e)
{
log.Info("EventFired loginstateChanged");
}
SDKCommunicatie:
Events events;
public SDKCommunicatie(Envents eventsInstance)
{
events = eventsInstance;
}
public void onLogon(string username, string directory, string system)
{
events.LogInState = false;
}
Your SDKCommunication class and your MainForm class each have their own separate instance of Events, so any events you trigger from one won't be visible from the other -- they're being raised on an entirely different object.
What you need is a single instance of the Events class that both SDKCommunication and MainForm can share -- that way they'll both be seeing the same thing. There are several different approaches you could take for this. Depending on what it needs to do, one very simple possibility might be to make Events a static class, and then the events would be visible everywhere without needing to create any instances.
I have solved the riddle.
When i need a method is a class i can call the method directly like this:
public class MainForm : Form
{
SDKCommunication sdkcommunication = new SDKCommunication();
public MainForm()
{
}
private void Button1_Click(oject sender, EventArgs e)
{
sdkcommunication.method("Test")
}
}
This is pretty straightforward. Look here the receiverclass:
public class SDKCommunication
{
method(string word)
{
//do something with word
}
}
The biggest problem is calling the class with the form(the original class). I have solved this with a eventhandler.
class CustomEventHandler1 : EventArgs
{
public CustomEventHandler1(string u, string d)
{
msgu = u;
msgd = d;
}
private string msgu;
private string msgd;
public string Username
{
get { return msgu; }
}
public string Directory
{
get { return msgd; }
}
}
Then the SDKCOmmunication class should look like this:
class SDKCommunication
{
public event EventHandler<CustomEventHandler1> RaiseCustomEventHandler1;
protected virtual void OnRaiseCustomEventHandler1(CustomEventHandler1 e)
{
EventHandler<CustomEventHandler1> handler = RaiseCustomEventHandler1;
if (handler != null)
{
handler(this,e);
}
}
//Custom Method that is called somewhere
internal void custommethod()
{
OnRaiseCustomEventHandler1(new CustomEventHandler1("johnsmith", "localhost");
}
}
Then in the mainform class:
public class MainForm : Form
{
public MainForm()
{
sdkcommunication.RaiseCustomEventHandler1 += new EventHandler<CustomEventHandler1>(sdkcommunication_RaiseCustomEventHandler1);
}
void sdkcommunication_RaiseCustomEventHandler1(object sender, CustomEventHandler1 e)
{
//Do something.
}
}
The information sended with the event you can get with e.Username and e.Directory. In this example they are strings where e.Username = johnsmith and e.Directory = localhost.
I hope somebody can use this information for their own code.
I am new to c#. I have created main windows that I am adding usercontrols to switch between screens with command:
Switcher.Switch(new NewPage());
The class Switcher is:
public static class Switcher
{
public static MainWindow pageSwitcher;
public static void Switch(UserControl newPage)
{
pageSwitcher.Navigate(newPage);
}
public static void Switch(UserControl newPage, object state)
{
pageSwitcher.Navigate(newPage, state);
}
}
But how to I exit the user control? I wish to finish it (like back button). I can use:
Switcher.Switch(new PreviousPage());
but it will keep the new page in memory and will not release it.
Example of NewPage class:
namespace MyProject.Screens
{
public partial class NewPage : UserControl
{
public NewPage()
{
InitializeComponent();
}
private void back_button_Click_(object sender, RoutedEventArgs e)
{
//what to put here?
}
}
}
The framework does a lot of the heavy lifting for navigation for you, including the "back" operation that you're interested in.
Take a look at http://msdn.microsoft.com/en-us/library/ms750478.aspx
NavigationService.GoBack is what you'll use.
In the off-chance that you're working on a Windows Store App, let me know, since my answer will be different.
You should really try and use the standard Navigation services available with WPF. This will give you configurable oage caching and journalling.
http://msdn.microsoft.com/en-GB/library/ms750478(v=vs.100).aspx
Try this:
private void back_button_Click_(object sender, RoutedEventArgs e)
{
Window parentWindow = (Window)this.Parent;
parentWindow.Close();
}
I have a class Lot with a function AddPiece(piece).
I also have a Page with a button btnPanel that on click fires the function
public void btnPanel_OnClick(object sender, EventArgs e){}
I want to call the btnPanel_OnClick from the Addpiece function but when I try to do it it does not show in the intlliSense and I get this compilation error "The name 'btnPanel_OnClick' does not exist in the current context". Both classes are in the same namespace. Is this possible?
Here is what I have:
namespace GraphicW_Array
{
public partial class Board : System.Web.UI.Page
{
public void btnPanel_OnClick(object sender, EventArgs e)
{
...code...
}
}
}
and
namespace GraphicW_Array
{
public class Lot
{
public void addPiece(int piece)
{
lotPresent[lotLoad] = piece;
lotLoad++;
}
}
}
I think the answer is yes you can but you probably don't want to. To call the method you need and instance of your page class so you could do
namespace GraphicW_Array
{
public class Lot
{
public void addPiece(int piece)
{
lotPresent[lotLoad] = piece;
lotLoad++;
var myPage = new Board();
myPage.btnPanel_OnClick(null,EventArgs.Empty);
}
}
}
But what would that actually do? I have no idea because you haven't posted the code but i suspect it won't do anything useful for you.
What are you actually trying to achieve?
Maybe this is want you want
namespace GraphicW_Array
{
public class Lot
{
public void addPiece(int piece, Board myPAge)
{
lotPresent[lotLoad] = piece;
lotLoad++;
myPage.btnPanel_OnClick(null,EventArgs.Empty);
}
}
}
Then in your page you can call it like this:
var myLot = new Lot();
myLot.addPiece(4,this);
Yes, this is possible.
Ensure your Lot class has a reference to the Board class in order to be able to call it, or define an event on it that the Board class can subscribe to and that will call this mathod when the event fires.
If you don't use the sender and e parameters, just pass a null and EventArgs.Empty.
You can call page's event by passing either null(if sender and EventArgs is not mandatory) but below is the better way to go.
It is not wise and not good practice to call a event from a class, however you can create another method with arguments in your class and then call it with desired parameters when it is needed.
This is can be accomplished as below:
Say you have below event
public void btnPanel_OnClick(object sender, EventArgs e)
{
//Do some common tasks to do here
}
Rearrange it as below:
public void btnPanel_OnClick(object sender, EventArgs e)
{
Lot lot = new Lot();
lot.CommonFunction(arg1, arg2); // Pass required data
}
public class Lot
{
public void AFunction()
{
//Do something
//...
CommonFunction(arg1, arg2); // Pass required data
//...
//Do something
}
public void CommonFunction(string arg1, string arg2)
{
// Do some common tasks to do here
}
}