Triggering method dependent on action on second window - c#

Please can someone tell me the technique that would be used, for the following scenario.
I would like to authenticate users, before I allow my code to perform another action.
I have a method that opens a new window that contains my authentication form (username and password).
private bool userLogin()
{
Window loginInterface = new Window()
{
Title = "Please Login",
Content = new login(),
Height = 282,
Width = 300,
ResizeMode = ResizeMode.NoResize,
WindowStartupLocation = WindowStartupLocation.CenterOwner
};
loginInterface.Owner = this;
loginInterface.ShowDialog();
return true;
}
I'm calling this method like so, on button click:
private void perform_action(object sender, RoutedEventArgs e)
{
if (!userLogin())
{
// Failed login, do nothing
}
else
{
// Authentication successful, perform action
delete_item();
}
}
The window opens fine, but how can I now make my method return true or false based on the what the user does on the opened form?
So when the user clicks the login button named login_button, my code already validates the credentials, but I need the 'bool' value sent back.
Can I make my first window almost wait for an action to be performed on another window and get the response back?

The Window.ShowDialog() method actually already returns a bool?. This can be set at any point from within the Window by setting (for example) this.DialogResult = true. You can then close the window and access the value from the calling code.
To close the window with a result:
this.DialogResult = true;
...and then to use that result in the calling code:
var myWindow = /*create window*/;
var result = myWindow.ShowDialog();
if (result == true)
{
//...
}

To close the login screen you can set DialogResult to true or false, and ShowDialog returns this value. For other things you can create events on the second window and subscribe to them on the first.

userLogin should return something other than true.
I would do something like this (based on the code shown):
return loginInterface.WasSuccessful; // you'd have to add this property

Related

MVC in the controller decide to open a popup or continue to nextpage

I have the following scenario:
When the user click on button next, I have to do some validation that must be done in the controller.
If there is an error, it will show the error messages in a popup with a Yes to continue or No to cancel and close the popup.
But if there are no errors, user will continue to next page without showing a popup.
Here is what I have:
[ActionName(PA.FlowActionName), AcceptPost("nextAanvullen")]
[NoAsyncTimeout]
public ActionResult Pagina_nextAanvullen(OffrerenFlow flow)
{
var medewerkers = ((MedewerkersAanvullenPakket)(flow.CurrentBusinessObject)).Medewerkers;
//validate here
if (true) // for test use true
{
var blok = medewerkers.Deelnemers;
return View("DeelnemersFout", medewerkers); // This doesnt open a popup
}
else
{
// Go to next page
DoWorkEventHandler handler = (o, e) =>
{
AsyncManager.Parameters["navigation"] = Navigate(new NavigationData<OffrerenFlow>((OffrerenFlow)flow), PA.Next,
true);
};
ExecuteAsyncMethod(handler);
}
}
I am not getting an popup, the view just display the view "DeelnemersFout". I need it to be in a popup. Any suggestions are welkom
Assign a value in ViewBag inside IF block
if (true) // for test use true
{
ViewBag.ShowPopup = true;
var blok = medewerkers.Deelnemers;
return View("DeelnemersFout", medewerkers); // This doesnt open a popup
}
and on Cshtml capture this value in a javascript variable and check if there is a value in this variable or not, and show the popup accordingly.

Dialog Result Set the Return Value

I have created a button on a form for which I set a return value programatically, seen below. First, is the event handler psudocode, followed by where the dialog result is returned to.
There is a default property where one can set a button's return behavior in the user interface, i.e. the Dialog Result behavior. In my full code I cannot see anywhere this button's return is set or modified.
When testing (running in debug mode) the first time the buttonSaveSet_Click event handler is used during the execution of code the returned dialog result value is "Cancel" despite the fact that I clicked the "Set" button. However, the second time that I execute the function, by pressing the same button, the dialog result is returned as "Yes".
It seems like there is another place that the Dialog Result is being modified, and I am setting that value in the incorrect location.
psudo code
private void buttonSaveSet_Click( object sender , EventArgs e )
{
setChars = new setChars();
//set the dr to yes.
buttonSaveSet.DialogResult = DialogResult.Yes;
// set the charCount
// set the rowCount
if ( conditional statement is true )
{
//return values;
}
else
{
//return nothing;
}
Close();
}
return location:
try
{
DialogResult dResult = setValPopup.ShowDialog();
SetChars sc = setValPopup.setChars;
int max;
if ( dResult == DialogResult.Yes )
{
if ( sc.set == true )
{
//do other work
}
}
}
You should set the DialogResult property of the form to exit. Any value but DialogResult.None will force the form to close and return whatever you set as DialogResult (on the form, not on the button)
private void buttonSaveSet_Click( object sender , EventArgs e )
{
setChars = new setChars();
this.DialogResult = DialogResult.Yes;
....
// No need to call Close here
// Close();
}
The behavior you observe is due to the fact that probably the form engine examines the DialogResult property of the button before entering the click event and it is not expected to reevaluate it again at the exit from the event. Thus, your first click sets the property on the button, at the second click the property on the button is noted by the form engine and everything closes.
Based on the behaviour you are decribing. It is likely that you have set the DialogResult property set on your designer, so the first time it executes, it runs whatever value has set on the designer, and on the following executions, it runs correcly as you expect.
Look at your designer and you´ll find the problem.

c++/cli best way to retrieve wpf window result

I have a WPF window and I'm calling it from a C++/cli code and it works fine. What I need is what's the best way to intercept user action I mean whether he click OK or Cancel. Wath I think to do is to define a Boolean property in my window and set it depends on user action. Here is my code :
MyWindowView^ window = gcnew MyWindowView();
System::Windows::Interop::WindowInteropHelper^ windowInteropHelper = gcnew System::Windows::Interop::WindowInteropHelper(window);
windowInteropHelper->Owner = (IntPtr)AfxGetMainWnd()->m_hWnd;
window->WindowStartupLocation = System::Windows::WindowStartupLocation::CenterScreen;
window->ShowDialog();
if ()
{
//some action
}
else
{
//
}
Also I want to know do I need to delete the window object ?
Window.ShowDialog returns dialog result. I can't see any reason to get this result in some way, that differs from C# or VB .NET:
System::Nullable<System::Boolean> result = window->ShowDialog();
if (result.HasValue)
{
// OK or Cancel
if (result.Value)
{
// OK clicked
}
else
{
// Cancel clicked
}
}
else
{
// dialog closed via system menu or Alt+F4
}
do I need to delete the window object ?
No, you don't. See this answer.

Custom MessageBox Through Synchronization Context - Cannot Access Disposed Object

I am in a fairly odd situation here. I have created a custom MessageBox form (instead of the built-in MessageBox.Show). The below code is what I use to call up the form, when I need it:
internal DialogResult ShowCustomMessageBox(string message, string caption, Icon icon = null)
{
var result = DialogResult.None;
MainForm.Get.UISynchContext.Send(s =>
{
var messageBox = new DialogBox
{
Icon = icon,
Text = caption,
rtbInDialogBox = { Text = message }
};
result = messageBox.ShowDialog();
messageBox.Dispose();
}, null);
return result;
}
When I run this, I get an error message on messageBox.ShowDialog(); that the messageBox instance has already been disposed.
When I post the code to the synchronization context I was pretty sure MainForm would run the code itself (as opposed to other threads), and I am not sure why it tells me that the messageBox has already been disposed.
Any ideas?
I found the problem. Apparently you need to specify the owner of the dialog box: result = messageBox.ShowDialog(MainForm.Get);

Using a child window from two different parent windows in c#

My problem deals with the following 3 forms:
MainWindow.cs
SettingsWindow.cs
AuthenticationWindow.cs
Settings window contains information like "Ask for password during startup or not".
I call the Authentication Window from Settings Window in order to remove password (when the password is set).
I call the Authentication Window also during startup (when the password is set).
My Authentication Window interacts with the settings window using a Static variable(To say whether the authentication is successful or not).
But, in order to reuse the same code (that is, to call the same authentication window during startup), I am unable to tell the MainWindow whether the authentication is successful or not.
However, I must some how reuse the code.
My question is: Is it possible to notify the Child Window about whom the parent window is? If yes, Sample code please...
Hope my question is clear.
Kindly help!
I assume that Authentication Window is being used with ShowDialog() along the lines of:
AuthenticationWindow auth = new AuthenticationWindow();
if (auth.ShowDialog(this) == DialogResult.Ok)
{
// we know it was successful
}
Then within AuthenticationWindow when you've had success you'll call:
DialogResult = DialogResult.Ok;
Close();
to get the feedback above, or to signal that it failed by
DialogResult = DialogResult.Cancel;
Close();
Alternatively, you could set a property on AuthenticationWindow:
class AuthenticationWindow : Form
{
public bool Success { get; set;}
}
and set the value of Success appropriately from within the AuthenticationWindow code.
Lastly, if you want immediate feed back to be sent to your other windows, consider implementing an event:
class AuthenticationWindow : Form
{
public event Action<bool> SignalOutcome;
private OnSignalOutcome(bool result)
{
Action<bool> handler = SignalOutCome;
if (handler != null) handler(result);
}
}
Then you will have to subscribe to that event where you call the Authentication window:
AuthenticationWindow auth = new AuthenticationWindow();
auth.SignalOutcome += (outcome) => { /* do something with outcome here */ };
auth.ShowDialog(this);
ChildWindow c1=new ChildWindow();
c1.Owener=authenticationWindow;
c1.Show(); //or ShowDialog();
ChildWindow c2=new ChildWindow();
c1.Owener=anotherWindow;
c2.Show(); //or ShowDialog();
//to get the parent, use the property c.Owner
if(c.Owner is AuthenticationWindow) //AuthenticationWindow is the type of authenticationWindow instance
{
...
}

Categories