I want to open the StdinfoPage page after clicking the Go to Admin button on the message box
how can i do that?
here is my button coding
private void button_login_Click(object sender, RoutedEventArgs e)
{
if (MyReader.HasRows && this.Frame != null)
{
while (MyReader.Read())
{
if (privilege == 1)
{
DisplayMsgBox("click to open the admin page ", "Go to Admin");
this.Frame.Navigate(typeof(StdinfoPage));
}
else
{
DisplayMsgBox("privilege 0", "ok");
}
}
}
else
{
DisplayMsgBox("sucess else", "ok");
}
conn.Close();
}
}
here is message box code
private async void DisplayMsgBox(string displayMsg, string displayBtn)
{
try
{
// Create the message dialog and set its content
var messageDialog = new MessageDialog(displayMsg);
// Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers
messageDialog.Commands.Add(new UICommand(displayBtn, new UICommandInvokedHandler(this.CommandInvokedHandler)));
messageDialog.Commands.Add(new UICommand("Close", new UICommandInvokedHandler(this.CommandInvokedHandler)));
// Set the command that will be invoked by default
messageDialog.DefaultCommandIndex = 0;
// Set the command to be invoked when escape is pressed
messageDialog.CancelCommandIndex = 1;
// Show the message dialog
await messageDialog.ShowAsync();
}
catch (Exception)
{
}
}
Based on the example from here: http://msdn.microsoft.com/library/windows/apps/windows.ui.popups.messagedialog.aspx, you need to create this method that will be executed when Go to Admin or Close button is clicked
private void CommandInvokedHandler(IUICommand command)
{
// Check which button is clicked
if (command.Label == "Go to Admin")
{
// open StdinfoPage
this.Frame.Navigate(typeof(StdinfoPage));
}
}
and delete this.Frame.Navigate(typeof(StdinfoPage)); inside if (privilege == 1) block
if (privilege == 1)
{
DisplayMsgBox("click to open the admin page ", "Go to Admin");
}
Related
This is for a Windows 10 UWP app. When the user tries to navigate away from a page, I want to have the user confirm if he wants to save the current data.
I have overridden OnNavigatingFrom as shown below. However, after the async MessageDialog, setting e.Cancel=false doesn't work. The page still stays on the current page even e.Cancel is later set to false. Please help!
protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
e.Cancel = true; //if I don't put this at the top, the page navigates right away
var yesCommand = new UICommand("Yes", async cmd => {
try
{
await SaveWorkshetItem(false);
e.Cancel = false;
}
catch (Exception ex)
{
await new MessageDialog("Error saving Worksheet Item. Please contact you administrator." + ex.Message + Environment.NewLine + ex.StackTrace).ShowAsync();
}
});
var noCommand = new UICommand("No", cmd => { e.Cancel = false; });
var cancelCommand = new UICommand("Cancel", cmd => { e.Cancel = true; });
var dialog = new MessageDialog("Do you want to save the current item before navigating away?");
dialog.Options = MessageDialogOptions.None;
dialog.Commands.Add(yesCommand);
dialog.Commands.Add(noCommand);
dialog.Commands.Add(cancelCommand);
await dialog.ShowAsync();
base.OnNavigatingFrom(e);
}
To simplify this the below code causes the page to never leave even though I am changing back e.Cancel=false after the sample MessageDialog.
protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
e.Cancel = true; //if I don't put this at the top, the page navigates right away
await new MessageDialog("Do you want to save the current item before navigating away?").ShowAsync();
e.Cancel = false; //unconditionally setting this back to false and it still won't leave the page
base.OnNavigatingFrom(e);
}
To handle the navigation yourself, set Cancel=true (as you already do), then bring up the dialog to obtain user input. Once you know the user's choice, use the navigation APIs (e.g. Frame.GoBack) to perform the desired navigation (based on e.NavigationMode) if the user decided to allow the navigation to happen.
Here is some basic sample code:
private bool isNavigationConfirmed = false;
protected async override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
base.OnNavigatingFrom(e);
if (isNavigationConfirmed)
{
isNavigationConfirmed = false;
return;
}
e.Cancel = true;
var noCommand = new UICommand("No", cmd => { });
var yesCommand = new UICommand("Yes", cmd =>
{
if (e.NavigationMode == NavigationMode.Back)
{
Frame.GoBack();
}
else
{
isNavigationConfirmed = true;
Frame.Navigate(e.SourcePageType);
}
});
var dialog = new MessageDialog("Do you want to allow navigation?");
dialog.Options = MessageDialogOptions.None;
dialog.Commands.Add(yesCommand);
dialog.Commands.Add(noCommand);
await dialog.ShowAsync();
}
Our application requires that a witness must authenticate before a logged in user can perform enrollment operations (Enroll and Delete).
This is not an issue for Enrolling as I can add a check (IsWitnessApproved) to an enrollment_OnStartEnroll method I.E. before the Capture method is called and fired.
However, this is not possible for Deletion as I don't have access to a point where the enrollment_OnDelete method hasn't fired.
I haven't been able to get a response to this issue from Digital Persona so I'm now looking at work-arounds.
I'm exploring if its possible to open up a new form (WitnessApproval) inside the enrollment_OnDelete method, approve the witness in the form (btnConfirmWitness_Click) and then come back into the method and continue on with the deletion?
enrollment_OnDelete method:
private void enrollment_OnDelete(DPCtlUruNet.EnrollmentControl enrollmentControl, Constants.ResultCode result, int fingerPosition)
{
if (!witnessApproved)
{
WitnessApproval witnessApproval = new WitnessApproval();
witnessApproval.Show();
}
else
{
int fingerMask = GetFingerMask(fingerPosition);
if (enrollmentControl.Reader != null)
{
try
{
// Delete from database
new EnrollmentDAL().DeleteEnrolledFingerprint(Settings.Default.Username, fingerMask, txt_WitnessName.Text);
MessageBox.Show("Fingerprint deleted.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
pbFingerprint.Image = null;
pbFingerprint.Visible = false;
btnCancel.Visible = false;
witnessApproved = false;
txt_WitnessName.Text = String.Empty;
txt_WitnessPassword.Text = String.Empty;
}
catch (Exception ex)
{
MessageBox.Show("There was a problem deleting the fingerprint.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
new Util().LogError(ex);
}
}
else
{
MessageBox.Show("No Reader Connected.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
_sender.Fmds.Remove(fingerPosition);
}
}
Selected WitnessApproval methods:
private void btnConfirmWitness_Click(object sender, EventArgs e)
{
lbl_Validation.Visible = false;
if (txt_WitnessName.Text == String.Empty)
{
SetMessage("Please enter a Witness.");
return;
}
if (txt_WitnessPassword.Text == String.Empty)
{
SetMessage("Please enter a Password.");
return;
}
if (txt_WitnessName.Text == Settings.Default.Username)
{
SetMessage("User and witness cannot be the same.");
return;
}
bool IsValidate = Membership.ValidateUser(txt_WitnessName.Text, txt_WitnessPassword.Text);
Settings.Default.WitnessName = txt_WitnessName.Text;
Settings.Default.WitnessPassword = txt_WitnessPassword.Text;
if (IsValidate)
{
this.Close();
// Allow enrollment operations
}
else
{
SetMessage("Witness credentials invalid.");
}
}
private void btnCancelWitness_Click(object sender, EventArgs e)
{
this.Close();
// DO NOT Allow enrollment operations
witnessCancelled = true;
}
private void SetMessage(string message)
{
lbl_Validation.Visible = true;
lbl_Validation.Text = message;
}
How to open form inside method, submit button and then come back to original method and continue?
There is ShowDialog method for this purposes.
Here is usage example from MSDN:
public void ShowMyDialogBox()
{
Form2 testDialog = new Form2();
// Show testDialog as a modal dialog and determine if DialogResult = OK.
if (testDialog.ShowDialog(this) == DialogResult.OK)
{
// Read the contents of testDialog's TextBox.
this.txtResult.Text = testDialog.TextBox1.Text;
}
else
{
this.txtResult.Text = "Cancelled";
}
testDialog.Dispose();
}
In your case, Form2 is WitnessApproval.
In WitnessApproval Form button handlers you will also need to set DialogResult to true when the witness is approved or to false when user cancelled operation.
I'm working on a text to speech demo, in which I'm using speech synthesizer.
My problem is when I click on play button the page is loading continuously.
It does not stop even if the speech is finished. Also in my demo pause and resume are not working.
I also tried to use spVoice interface for text to speech, but in this demo also pause and resume are not working.
Demo Using Speech synthesizer -
SpeechSynthesizer spRead;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Creating new object of SpeechSynthesizer.
spRead = new SpeechSynthesizer();
}
} // Page_Load
protected void btnPlay_Click(object sender, EventArgs e)
{
// Get the content data as per the content id
_contentData = new ContentFormData(ContentManager.GetContentData(Page.Database, ContentId, Page.IsLive));
// Get the text after trim
_speechText = WebUtility.HtmlDecode(_contentData.Content.Text1.Trim());
// If Speech Text is not null
// then check the button class, if cssclass is play change it to pause
and call speak method.
if (_speechText != null && !string.IsNullOrEmpty(_speechText))
{
// if button is play buttton
// then call play method and speech the text
if (btnPlay.CssClass == "button-play")
{
btnPlay.CssClass = btnPlay.CssClass.Replace("button-play",
"button-pause");
// creating the object of SpeechSynthesizer class
spRead = new SpeechSynthesizer();
spRead.SpeakAsync(_speechText);
spRead.SpeakCompleted += new
EventHandler<SpeakCompletedEventArgs>(spRead_SpeakCompleted);
}
// If button class is pause
// then change it to continue and call pause method.
else if (btnPlay.CssClass == "button-pause")
{
btnPlay.CssClass = btnPlay.CssClass.Replace("button-pause",
"button-continue");
if (spRead != null)
{
// Check the state of spRead, and call pause method.
if (spRead.State == SynthesizerState.Speaking)
{
spRead.Pause();
}
}
btnPlayFromStart.Enabled = true;
}
// If button class is continue
// then change it to pause and call resume method.
else if (btnPlay.CssClass == "button-continue")
{
btnPlay.CssClass = btnPlay.CssClass.Replace("button-continue",
"button-pause");
if (spRead != null)
{
// Check the state of spRead, and call resume method.
if (spRead.State == SynthesizerState.Paused)
{
spRead.Resume();
}
}
btnPlayFromStart.Enabled = false;
}
}
}
private void spRead_SpeakCompleted(object sender, SpeakCompletedEventArgs e)
{
// If Spread is not null
// then dispose the spread after the speak is completed
// else do nothing
if (spRead != null)
{
spRead.Dispose();
}
else
{
// do nothing
}
} // spRead_SpeakCompleted
Demo Using SpVoice -
SpVoice voice;
protected void Page_Load(object sender, EventArgs e)
{
_contentData = new
ContentFormData(ContentManager.GetContentData(Page.Database, ContentId,
Page.IsLive));
_speechText = WebUtility.HtmlDecode(_contentData.Content.Text1.Trim());
} // Page_Load
protected void btnPlay_Click(object sender, EventArgs e)
{
voice = new SpVoice();
if (btnPlay.CssClass == "button-play")
{
voice.Speak(_speechText, SpeechVoiceSpeakFlags.SVSFlagsAsync);
btnPlay.CssClass = btnPlay.CssClass.Replace("button-play", "button-
pause");
}
else if (btnPlay.CssClass == "button-pause")
{
voice.Pause();
btnPlay.CssClass = btnPlay.CssClass.Replace("button-pause", "button-
continue");
}
else if (btnPlay.CssClass == "button-continue")
{
voice.Resume();
btnPlay.CssClass = btnPlay.CssClass.Replace("button-continue",
"button-play");
}
}
Solved the issue by using handeler, to stop the postback.
Stored the voice object in session and in pause and resume get the voice object from session.
I want to cancel the loading and not show the window if my else statement executes in the loaded event. See the code below.
private void OpenTradesLoaded(object sender, RoutedEventArgs e)
{
if (OpenTradesQuery.Count() > 0)
{
numOfrecords = OpenTradesQuery.Count();
DataContext = this;
foreach (var rowObj in OpenTradesQuery)
{
row = SourceTable.NewRow();
SourceTable.Rows.Add(rowObj.TraderID, rowObj.ClientTradedDate, rowObj.ClientTradedTime, rowObj.ClientName, rowObj.CurrencyPair, rowObj.TradedAmount, rowObj.Action, rowObj.ExecutedRate);
}
}
else
{
Mouse.OverrideCursor = System.Windows.Input.Cursors.Arrow;
MeBox.Show("You have no open trades.", "", MessageBoxButton.OK, MessageBoxImage.Error);
**//Cancel Loading here and do not show window**
}
}
You can use this property:
public bool ShouldLoad
{
get { return OpenTradesQuery.Count() > 0; }
}
And when you want to open, ask if should open:
MyPage mypage = new MyPage();
if (mypage.ShouldLoad)
{
mmypage.Show();
}
else
{
MeBox.Show("You have no open trades.", "", MessageBoxButton.OK,
MessageBoxImage.Error);
}
With this code, you can check before loading if it really should load.
I just used
this.Close();
works fine.
I created a 'Remember me' option on an ASP site and the client said they also wanted it to show the login name in the user field even after they press 'logout'. It works as long as I don't ever use a different login name again. Once I assign the value to the text box in the code behind, even if I manually type a new value the old value is what is used.
Example:
I type a user/password (eg. User1), click 'Remember me' and login successfully.
I log out and am redirected back to the login page. On the page_load event, it detects that there is a valid cookie with the user name stored (User1) and it reads the value and sets the text field.
I change the login to something else (eg. User2) and it fails saying invalid user/password. Weird.
I check the data and it is using the old text field (User1). I try another (eg. User3) and press login. It fails and when I check the Text property, it still says User1 even though on screen it says User3.
No matter what I do, it will not change once I set it in the codebehind file. It's almost as if once the text field is set, it cannot be changed. This is not right, but I have no good explanation for it.
Here is the code in question:
Page load:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.ServerVariables["AUTH_USER"] != null && !Request.ServerVariables["AUTH_USER"].Equals(""))
{
login.Visible = false;
logout.Visible = true;
btnLogout.Text = "Logout " + Request.ServerVariables["AUTH_USER"];
}
else
{
login.Visible = true;
logout.Visible = false;
CheckLoginCookie();
}
}
Code to set the cookie:
private void SaveLoginCookie()
{
try
{
Response.Cookies["KYSUSR"].Value = txtLoginUsername.Text.Trim();
Response.Cookies["KYSUSR"].Expires = DateTime.Today.AddMonths(6);
}
catch (Exception ex)
{
ExceptionHandling.SendErrorReport(this, ex);
}
}
Code to load the cookie:
private void CheckLoginCookie()
{
try
{
if (Request.Browser.Cookies)
{
if (Request.Cookies["KYSUSR"] != null && Request.Cookies["KSYFOR"] != null)
{
// logged in as remember
if (Request.Cookies["KYSFOR"].Value == "R")
txtLoginUsername.Text = Request.Cookies["KYSUSR"].Value;
// once set here, the Text property never changes regardless of what is entered into it
}
}
}
catch (Exception ex)
{
ExceptionHandling.SendErrorReport(this, ex);
}
}
Code to do the login:
protected void btnLogin_Click(object sender, EventArgs e)
{
try
{
String user = txtLoginUsername.Text.Trim();
if (chkSaveUser.Checked)
SaveLoginCookie();
else
{
// set cookie as expired so browser will clear it
Response.Cookies["KYSUSR"].Expires = DateTime.Today.AddDays(-1);
}
if (CheckLogin(user, txtLoginPassword.Text))
{
if (chkSaveUser.Checked)
{
FormsAuthentication.SetAuthCookie(user, true);
}
FormsAuthentication.RedirectFromLoginPage(txtLoginUsername.Text.Trim(), false);
}
}
catch (Exception ex)
{
ExceptionHandling.SendErrorReport(this, ex);
}
}
Why would the Text property not change?
The issue is that you don't check if you are in a postback in your Page_Load method - which means even when the user puts something else in the txtLoginUsername Textbox it is overridden by CheckLoginCookie.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.ServerVariables["AUTH_USER"] != null
&& !Request.ServerVariables["AUTH_USER"].Equals(""))
{
login.Visible = false;
logout.Visible = true;
btnLogout.Text = "Logout " + Request.ServerVariables["AUTH_USER"];
}
else
{
login.Visible = true;
logout.Visible = false;
// Only check the login cookie if we are not dealing with a form submission.
if (!Page.IsPostBack)
{
CheckLoginCookie();
}
}
}