C# make method required - c#

I have a class with a method that when not called causes a crash.
Is there a way to make a compilation failure when the method isn't called?
Edit:
So what I have is basically a class that makes an istance of another class (a form) and it is a mesagebox with a do not show again option. Here's an example of how you'd use it.
public partial class Form1 : Form {
DontShowAgainBox box;
public void AlertYes() {
if (box.form.showagain.Checked)
t1.Text = "You chose yes (checked)!!!";
else
t1.Text = "You chose yes (unchecked)!!!";
}
public void AlertNo() {
if (box.form.showagain.Checked)
t1.Text = "You chose no (checked)!!!";
else
t1.Text = "You chose no (unchecked)!!!";
}
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
box = new DontShowAgainBox("Warning", "Are you sure?");
Action yesaction = new Action(AlertYes);
box.Bind_Yes(yesaction);
Action noaction = new Action(AlertNo);
box.Bind_No(noaction);
box.SetNoButton("Nope");
box.SetYesButton("I'm sure");
box.Show();
}
}
There's another method that you can hide the "No" button with also.
But the yes button is in every instance of the class so it needs to have a function associated with it or else... crash.

Why not just test for this in software instead of crashing?
if (!init_called) {
print error
exit
}

It is not possible for the compiler or linker to say, at build time, "Hey, this method that was supposed to be called wasn't called!" You can't make the compiler issue an error message because client code didn't call a particular method.
What you're asking is not possible.

Related

Passing a variable between forms WINFORMS [duplicate]

Wierd behaviour when passing values to and from second form.
ParameterForm pf = new ParameterForm(testString);
works
ParameterForm pf = new ParameterForm();
pf.testString="test";
doesn't (testString defined as public string)
maybe i'm missing something? Anyway I'd like to make 2nd variant work properly, as for now - it returns null object reference error.
Thanks for help.
Posting more code here:
calling
Button ParametersButton = new Button();
ParametersButton.Click += delegate
{
ParameterForm pf = new ParameterForm(doc.GetElementById(ParametersButton.Tag.ToString()));
pf.ShowDialog(this);
pf.test = "test";
pf.Submit += new ParameterForm.ParameterSubmitResult(pf_Submit);
};
definition and use
public partial class ParameterForm : Form
{
public string test;
public XmlElement node;
public delegate void ParameterSubmitResult(object sender, XmlElement e);
public event ParameterSubmitResult Submit;
public void SubmitButton_Click(object sender, EventArgs e)
{
Submit(this,this.node);
Debug.WriteLine(test);
}
}
result:
Submit - null object reference
test - null object reference
pf.ShowDialog(this); is a blocking call, so pf.Submit += new ParameterForm.ParameterSubmitResult(pf_Submit); is never reached: switch the order.
Submit(this,this.node); throws a null object reference because no event is assigned to it (see above). Generally, you should always check first: if (Submit != null) Submit(this,this.node);
You should change ``pf.ShowDialog(this);topf.Show(this);` so that your main form isn't disabled while your dialog box is open, if that's what you want, or use the model below (typical for dialog boxes.)
I'm not sure what pf_Submit is supposed to do, so this might not be the best way to go about it in your application, but it's how general "Proceed? Yes/No" questions work.
Button ParametersButton = new Button();
ParametersButton.Click += delegate
{
ParameterForm pf = new ParameterForm(testString);
pf.ShowDialog(this); // Blocks until user submits
// Do whatever pf_Submit did here.
};
public partial class ParameterForm : Form
{
public string test; // Generally, encapsulate these
public XmlElement node; // in properties
public void SubmitButton_Click(object sender, EventArgs e)
{
Debug.WriteLine(test);
this.Close(); // Returns from ShowDialog()
}
}
When you want to use your second variant, you have to use a getString()-Method, where you can put the e.g. "testString". The way you wrote it, "testString" should be a method (and got brackets).
EDIT (a bit more precise):
You could write:
pf.getString(testString);
, if "pf" is an instance of your own class, otherwise you had to look up, whether you can retrieve a String in this class.
the thing was in line order :)
pf.Submit += new ParameterForm.ParameterSubmitResult(pf_Submit);
and
pf.Test = "test";
should have been set before
pf.ShowDialog(this);
my mistake thingking that parameter can be passed after 2nd form was displayed
thnx for answers

Display my forms in another class

I recently developped an application for a student project, and everything works fine. However, if I'm asking something here, you can certainly assume that the whole thing isn't so functional...and you'd be right hohoho. Let's get started. Basically the functional version of my project uses an UI console.
It runs, but from an user point of view, working with something like this isn't the most amazing stuff in the world. So I decided to replace my old console by some Windows Forms.
Project global render with console
Project global render with form
This is where things become wrong. I have "3" classes :
Program.cs (the main program with all the serious stuff)
formOne.cs (the first form with a button for each options)
form/Two to Five/.cs (each options open the corresponding form)
At some point, Program.cs will launch formOne.cs, and from there the user should be able to navigate between the various options and so the various forms...but nope. formOne.cs opens, and then we can't click on anything (well we can but nothing happens). I did a mistake somewhere, I would like to know where and how to fix it. Here's how I proceeded :
(this is the basic algorithm, not the whole code)
Program.cs :
class Program {
formOne winRecep = new formOne();
formTwo winCrea = new formTwo();
formThree winSearch = new formThree();
formFour winDel = new formFour();
formFive winView = new formFive();
winRecep.ShowDialog();
string userChoice = winRecep.getUserChoice();
switch(userChoice){
case "create new task" :
winCrea.ShowDialog();
break;
case "search a task" :
winSearch.ShowDialog();
break;
case "delete a task" :
winDel.ShowDialog();
break;
case "view my tasks" :
winView.ShowDialog();
break;
}
}
formOne.cs :
class formOne {
string userChoice;
public formOne()
{
InitializeComponent();
}
public string getUserChoice()
{
return userChoice;
}
private void formOne_Load(object sender, EventArgs e)
{
//blabla update current date, current hour...
}
private void buttonOptionOne_Click(object sender, EventArgs e)
{
userChoice = "create new task";
}
private void buttonOptionTwo_Click(object sender, EventArgs e)
{
userChoice = "search a task";
}
private void buttonOptionThree_Click(object sender, EventArgs e)
{
userChoice = "delete a task";
}
private void buttonOptionFour_Click(object sender, EventArgs e)
{
userChoice = "view my tasks";
}
}
It seems pretty clear to me, but I did a mistake somewhere. I would like to work in Program.cs instead of formOne.cs because, well, everything is in Program.cs so the most logical way to proceed is certainly to work here instead of bring informations and variables everywhere accross the classes.
Could someone help me and explain why it's wrong ?
EDIT : Program.cs using Application doesn't solve the thing :
class Program {
var winRecep = new formOne();
var createtask = new formTwo();
var viewTask = new formThree();
var searchTask = new formFour();
var deleteTask = new formFive();
Application.Run(winRecep);
string userChoice = winRecep.getUserChoice();
switch(userChoice){
case "create new task" :
Application.Run(createtask);
break;
case "search a task" :
Application.Run(searchTask);
break;
case "delete a task" :
Application.Run(deleteTask);
break;
case "view my tasks" :
Application.Run(viewTask);
break;
}
}
You need to start your main form like this:
var mainForm = new formOne();
Application.Run(mainForm);
This starts the windows message loop. Without a message loop, your application can't respond to any events (such as mouse clicks or keypresses).
The first thing you should do, is opening the main form using Application.Run, as already suggested. This starts the message loop which is essential for the rest of the execution:
var mainForm = new formOne();
Application.Run(mainForm);
Then use that form to open all others. Closing the form started with Application.Run will close the application since the message loop will end too. So on any action, like a button click or a command written, open the form you need. You can call Show to open the other form and make it possible to still access the main form, or ShowDialog which will block further actions until the child form was closed.

ManagementObjectSearcher causes re-entrancy issues for onclick handler

I am having an odd problem with protecting a section of code. My application is a tray app. I create a NotifyIcon inside my class (ApplicationContext). I have assigned a balloon click handler and a double click handler to the NotifyIcon object. there is also a context menu but I am not showing all code. Only important pieces.
public class SysTrayApplicationContext: ApplicationContext
{
private NotifyIcon notifyIcon;
private MainForm afDashBoardForm;
public SysTrayApplicationContext()
{
this.notifyIcon = new NotifyIcon();
this.notifyIcon.BalloonTipClicked += notifyIcon_BalloonTipClicked;
this.notifyIcon.MouseDoubleClick += notifyIcon_MouseDoubleClick;
// ... more code
}
Both handlers launch or create/show my form:
private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
openDashboard();
}
}
private void notifyIcon_BalloonTipClicked(object sender, EventArgs e)
{
openDashboard();
}
private void openDashboard()
{
if (dashBoardForm != null)
{
log.Debug("Dashboard form created already, so Activate it");
dashBoardForm.Activate();
}
else
{
log.Debug("Dashboard form does not exist, create it");
dashBoardForm = new MainForm();
dashBoardForm.Show();
}
}
There is a problem with the above code. Maybe more than 1. Issue: it is possible to display 2 dashboard forms which is not what I want. If user double clicks on tray icon while balloon message is displaying causes a race condition in openDashboard. I can reproduce this easily. So I added a lock around the code in openDashboard code and, to my surprise, that did NOT prevent 2 dashboard forms from displaying. I should not be able to create 2 MainForms. Where am I going wrong here?
here is the updated code with lock statement:
private void openDashboard()
{
lock (dashBoardFormlocker)
{
if (dashBoardForm != null)
{
log.Debug("Dashboard form created already, so Activate it");
dashBoardForm.Activate();
}
else
{
log.Debug("Dashboard form does not exist, create it");
dashBoardForm = new MainForm();
dashBoardForm.Show();
}
}
}
Note: lock object was added to the class and initialized in constructor.
private object dashBoardFormlocker;
UPDATE: Showing more code. this is how code gets started :
static void Main()
{
if (SingleInstance.Start())
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
XmlConfigurator.Configure();
// For a system tray application we don't want to create
// a form, we instead create a new ApplicationContext. The Run method takes
Application.Run(new SysTrayApplicationContext());
SingleInstance.Stop();
SingleInstance.Dispose();
}
}
}
UPDATE 2: Provide more code for clarity
public partial class MainForm : Form
{
public MainForm()
{
log.Trace("MainForm constructor...");
InitializeComponent();
// ... code not shown
this.label_OSVersion.Text = getOSFriendlyName();
// .. more code
}
private string getOSFriendlyName()
{
try
{
string result = string.Empty;
var mgmtObj = (from x in new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem").Get().OfType<ManagementObject>()
select x.GetPropertyValue("Caption")).FirstOrDefault();
result = mgmtObj != null ? mgmtObj.ToString() : string.Empty;
OperatingSystem os = Environment.OSVersion;
String sp = os.ServicePack ?? string.Empty;
return !string.IsNullOrWhiteSpace(result) ? result + sp : "Unknown";
}
catch (System.Exception ex)
{
log.Error("Error trying to get the OS version", ex);
return "Unknown";
}
}
}
The main UI thread must always pump a message loop to support communication from COM components.
So when you do a blocking operation from the UI thread like locking or joining a thread, (EDIT: edited based on Peter Duniho's fix) the UI thread will enter an 'alertable' state, allowing COM to dispatch certain type of messages, which in turn can cause re-entrancy issues like in your scenario.
Look at the answer to this question (Why did entering a lock on a UI thread trigger an OnPaint event?) for a much more accurate explanation.
Looking at the source code of ManagementObjectSearcher.Get there is a lock (inside Initialize), and since you call it from the constructor of your form, it may lead to the second event triggering while the form's constructor has not finished. The assignment to the dashBoardFormlocker variable only happens after the constructor finishes, so that would explain why it was null on the second entry.
The moral of the story is never do blocking operations on the UI thread.
Without a good, minimal, complete code example that reliably reproduces the problem, it's impossible to know for sure what the problem is. But the guess by answerer tzachs seems reasonable. If so, you can fix your problem by changing your method to look like this:
private bool _dashboardOpen;
private void openDashboard()
{
if (_dashboardOpen)
{
if (dashBoardForm != null)
{
log.Debug("Dashboard form created already, so Activate it");
dashBoardForm.Activate();
}
}
else
{
log.Debug("Dashboard form does not exist, create it");
_dashboardOpen = true;
dashBoardForm = new MainForm();
dashBoardForm.Show();
}
}
In that way, any re-entrant attempt to open the window will be detected. Note that you still need the check for null before actually activating; you can't activate a window that hasn't actually finished being created yet. The subsequent call to Show() will take care of activation anyway, so ignoring the activation in the re-entrant case shouldn't matter.

Accessing background worker from another form's button click event

I'm getting my way around c# slowly but surely lol in this code:
// create an instance of the main form
public formMain _formMain;
public void btnDynaDotCheck_Click(object sender, EventArgs e)
{
if (_formMain.bgWorker.IsBusy != true)
{
this.btnDynaDotCheck.Enabled = false;
_formMain.bgWorker.RunWorkerAsync("dr_begin_dd_check");
}
else
{
_formMain.returnMessage("Please wait untill the current task is finished...");
return;
}
}
I'm trying to access the background worker in formMain.cs from anotherForm.cs there is no errors in VS, but when run i get
"An unhandled exception of type 'System.NullReferenceException'
occurred in " and "Additional information: Object reference not set to
an instance of an object."
On this line:
if (_formMain.bgWorker.IsBusy != true)
So i'm not really getting access in this case eh?
Use dependency injection to inject a reference to your mainform into the otherone : somewhere in your mainform code do the following :
anotherForm _anotherForm = new anotherForm(this);
_anotherForm.Show();
assuming you are creating anotherform from code within the mainform, this is actually referring to the mainform.
In the constructor of anotherFrom do this :
public anotherForm(MainForm formMain){
_formMain = formMain;
}
This is by far the most elegant way to solve this issue. Because it makes clear that there is a dependency from one form to the other and makes the design intention clear.
Using a parent is also fine, but only if the mainform is really a parent of the other form.
Going via Application object will work, but the application object is a global and you hide your dependency that way.
_formMain = Application.OpenForms["formMain"];
Add this code in button click and try it.
When accessing _formMain from anotherForm:
I assume anotherForm is instantiated and called from _formMain like this:
anotherForm _anotherForm = new anotherForm();
_anotherForm.Show();
there's now several ways to access _formMain from _anotherForm but the easiest I think is to set _formMain as the parent of _anotherForm:
_anotherForm.Parent = this; // insert before _anotherForm.Show()
this way you can get hold of it in _anotherForm like this
public void btnDynaDotCheck_Click(object sender, EventArgs e)
{
...
formMain _formMain = this.Parent as formMain;
if(_formMain != null)
{
... // do whatever ever you have to do
}
}
but be careful... getting your BackgroundWorker in _formMain requires public methods you can call and return your BackgroundWorker.
Hope this helps!
Thanks for the help guys :)
I now have:
// create an instance of the formMain
formMain _formMain = new formMain();
public void btnDynaDotCheck_Click(object sender, EventArgs e)
{
if (_formMain.bgWorker.IsBusy != true)
{
this.btnDynaDotCheck.Enabled = false;
_formMain.bgWorker.RunWorkerAsync("dr_begin_dd_check");
}
else
{
_formMain.returnMessage("Please wait untill the current task is finished...");
return;
}
}
Which works :) it gets through to the main form:
public void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
// action to string format
string action = e.Argument as string;
if (action == "dr_begin_dd_check")
{
BeginInvoke((Action)(() =>
{
statusLabel.Text = "Access the bgw...";
}
));
} // dr_begin_dd_check
I'm now getting the error in the formMain:
Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
I'm not sure where the error lies in my above code or actually in the formMain section, or should i open a new question? :)
cheers guys
Graham

Static member inside the form

In my project on the WindowsForms, if I have a static instance inside the form, when I'm opening my form at the first time, it works. But if I'll close it and open again, the form will be empty. Why can it be?
public partial class Computer : Form
{
static Indicators indicators = new Code.Indicators();
}
P.S. I'm making it static, because I want to save it's value after the form will be closed.
Edit 1: Opening the form
private void button3_Click(object sender, EventArgs e)
{
Computer computer = new Computer();
computer.ShowDialog();
}
Edit 2: Computer Form
namespace WF
{
public partial class Computer : Form
{
static Code.Indicators indicators = new Code.Indicators();
public Computer()
{
if (indicators.isComputerAlreadyRunning == false)
{
InitializeComponent();
pictureBox1.Image = Properties.Resources.Computer1;
indicators.isComputerAlreadyRunning = true;
}
}
// My not successful try to save the value of the variable
public Code.Indicators ShowForm()
{
return new Code.Indicators(indicators.isComputerAlreadyRunning);
}
}
}
I don't think that static members work well with the Windows Form lifecycle.
I suggest you make Indicators a normal instance member of your form. To preserve state beyond the life of a form you can copy your state from the form and copy it back to the form when you open it.
// Keep this in the proper place
var indicators = new Code.Indicators();
...
// Copy back and forth for the life time of the form
using (var form = new Computer())
{
form.Indicators.AddRange(indicators);
form.Close += (s, e) =>
{
indicators.Clear();
indicators.AddRange(form.Indicators);
}
}
...
According to the constructor in the Computer class, the indicators.isComputerAlreadyRunning is set to true the first time the form is created.
So when Computer is created the second time, the if condition will fail and the whole if block will be skipped. That means your InitializeComponent(); won't get run and hence nothing in the form will shows up.
Put the InitializeComponent(); outside the if clause to make it work.

Categories

Resources