📄 logon.cs
字号:
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlServerCe;
using HardwareDistributor.Properties;
using HardwareDistributor.Utilities;
using HardwareDistributor.Synchronization;
namespace HardwareDistributor.UI
{
/// <summary>
/// UI Layer form that allows user to login and choose a role
/// </summary>
public partial class Logon : Form
{
#region Members
private IntPtr launchWindow;
//this matches the value being used by the splash screen to wait for messages
private const int WM_STATUSUPDATE = 0x0401;
private const int WM_ERROR = 0x0402;
private const int WM_DONE = 0x0403;
//used to detect first time load and activation
private bool _isFirstTime = true;
#endregion
#region Constructors
public Logon(string launchWindowName, string thisWindowName)
{
InitializeComponent();
//only if we are passed in the splash screen window name
if (!String.IsNullOrEmpty(launchWindowName))
{
//get and hold the pointer to the launch app window. do this once and hold the pointer since
//finding window is a interop call and expensive
launchWindow = HardwareDistributor.Utilities.Native.FindWindow(null, launchWindowName);
}
//if we expicitly have been instructed to attach a window name
if (!string.IsNullOrEmpty(thisWindowName))
{
this.Text = thisWindowName;
}
this.Hide();
// We are removing both the Control Box and the Minimize Box, so that we don't
// have to handle these in our code. This is not necessary in Windows Mobile Standard,
// but we are writing this code so that it works on all platforms without any changes
// or any recompiling.
this.ControlBox = false;
this.MinimizeBox = false;
SetupData();
}
#endregion
#region Event Handlers
/// <summary>
/// Shutdown application
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuItemExit_Click(object sender, EventArgs e)
{
//Exit app
this.Close();
Application.Exit();
}
/// <summary>
/// This menu logs you on to the system
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuItemLogon_Click(object sender, EventArgs e)
{
//proceed if user entered data is valid
if (!ValidateEntries())
{
return;
}
bool authorized = false;
//verify credentials
try
{
Cursor.Current = Cursors.WaitCursor;
Application.DoEvents();
//Verify correct credentials
authorized = Business.Services.VerifyCredentials(userNameTextBox.Text.Trim(), passwordTextBox.Text.Trim());
Application.DoEvents();
}
catch (Exception ex)
{
Business.Services.LogErrors(ex);
MessageBox.Show(Resources.CredentialsVerificationError, Resources.SystemError);
}
finally
{
Cursor.Current = Cursors.Default;
}
//if user is authorized take him to the pick role screen
//otherwise show error message
if (authorized)
{
//go to pick which role this user is
PickRole pickRoleDialog = new PickRole();
pickRoleDialog.ShowDialog();
pickRoleDialog.Dispose();
//get back focus to retain flow, in cases when the user had navigated away from the application
//breaking the window stacking order
this.Activate();
}
else
{
MessageBox.Show(Resources.InvalidCredsMessage, Resources.LogonError);
userNameTextBox.Text = string.Empty;
passwordTextBox.Text = string.Empty;
userNameTextBox.Focus();
}
}
/// <summary>
/// Launch Help screen for the form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void linkLabelHelp_Click(object sender, EventArgs e)
{
try
{
//Show Logon Help
OnlineHelper myHelp = new OnlineHelper("overview");
myHelp.ShowDialog();
//Free the resources of the help form
myHelp.Dispose();
//get back focus to retain flow, in cases when the user had navigated away from the application
//breaking the window stacking order
this.Activate();
}
catch (Exception ex)
{
Business.Services.LogErrors(ex);
MessageBox.Show(Resources.HelpDisplayError, Resources.SystemError);
}
}
// <summary>
/// Custom Handling for the back key
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BackKeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode == System.Windows.Forms.Keys.Back))
{
// Back
// if the back key is hit, close this dialog
this.Close();
}
}
/// <summary>
/// Bring up form to let the user select the language
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void linkLabelLanguage_Click(object sender, EventArgs e)
{
//bring up the change language form
ChangeLanguage changeLanguageForm = new ChangeLanguage();
changeLanguageForm.ShowDialog();
changeLanguageForm.Dispose();
//get back focus to retain flow, in cases when the user had navigated away from the application
//breaking the window stacking order
this.Activate();
}
/// <summary>
/// for the first time the form is activated, it notifies the
/// launcher windows (splash screen)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Logon_Activated(object sender, EventArgs e)
{
//signal only on first time activate
if (_isFirstTime)
{
//shutdown the splash screen
SignalLoaded(launchWindow);
}
_isFirstTime = false;
}
#endregion
#region Methods
/// <summary>
/// starts off the notification listener
/// </summary>
private void ListenForNotifications()
{
//wait for messages to arrive
}
/// <summary>
/// validate user input on the screen.
/// </summary>
/// <returns></returns>
private bool ValidateEntries()
{
//Ensure that a User name has been entered
if (string.IsNullOrEmpty(userNameTextBox.Text))
{
MessageBox.Show(Resources.EnterValidUserMessage, Resources.InputError);
userNameTextBox.Focus();
return false;
}
//Ensure that a Password has been entered
if (string.IsNullOrEmpty(passwordTextBox.Text))
{
MessageBox.Show(Resources.EnterValidPwdMessage, Resources.LogonError);
passwordTextBox.Focus();
return false;
}
return true;
}
/// <summary>
/// The Activated Event is used to kick off the execution of
/// Splash Screen code since it doesn't fire until after the
/// screen is drawn and visible.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SetupData()
{
try
{
//Load device and application data
Business.Services.LoadDeviceData();
//Load configuration information from config file
UpdateStatus(LoadStatus.LoadingConfiguration);
Business.Services.LoadAppSettings();
//create and cache connection to DB
UpdateStatus(LoadStatus.CreatingDbConnection);
Business.Services.CacheDataSourceConnection();
bool canSynchronize = CheckSyncServerReachable();
if (canSynchronize)
{
//hook up the call back method for processing messages
NotificationAgent.Instance.ProcessMessage =
new ProcessMessageDelegate(ProcessOrderMessage);
//Messages received while we are synchronizing are to be discarded
NotificationAgent.Instance.ProcessMessages = false;
NotificationAgent.Instance.StartListening();
//synchronize database
UpdateStatus(LoadStatus.SynchronizingDb);
Business.Services.SyncWithDataSource();
//Ready to process notifications
NotificationAgent.Instance.ProcessMessages = true;
}
else
{
/*
* Do nothing. Allow the user to continue in
* offline mode.
*/
}
//Load and cache Customers Collection
Business.GlobalCache.Instance.Customers = Business.Services.GetCustomers();
//show the screen
this.ShowDialog();
}
catch (SqlCeException sqlEx)
{
HandleSqlException(sqlEx);
this.Close();
}
catch (Exception ex)
{
Business.Services.LogErrors(ex);
UpdateStatus(LoadStatus.ErrorInitSystem, true);
this.Close();
}
}
/// <summary>
/// Checks and returns true if the syncrhonization server is reachable
/// </summary>
/// <returns></returns>
private bool CheckSyncServerReachable()
{
bool syncServerReachable = false;
UpdateStatus(LoadStatus.CheckingNetwork);
if ( Business.Services.GetConnectionStatus())
{
//Check Synchronization URL
UpdateStatus(LoadStatus.TestingIis);
if (Business.Services.CheckSynchronizationUrl())
{
syncServerReachable = true;
}
else
{
//Sync URL isn't reachable
UpdateStatus(LoadStatus.SyncServerUnavailable, false);
}
}
else
{
//Network isn't available
UpdateStatus(LoadStatus.NetworkUnavailable, false);
}
return syncServerReachable;
}
/// <summary>
/// Method that handles the messages received by the notification agent
/// </summary>
/// <param name="action">action token</param>
/// <param name="order">order object</param>
private void ProcessOrderMessage(string action, Business.Order order)
{
if ( action == "SYNC" )
Business.Services.SyncWithDataSource();
}
/// <summary>
/// interpret special sql exception codes and provide
/// descriptive status message
/// </summary>
/// <param name="sqlEx"></param>
private void HandleSqlException(SqlCeException sqlEx)
{
Business.Services.LogErrors(sqlEx);
//This error means SQL Server can't be found
if (sqlEx.NativeError == 29061)
{
UpdateStatus(LoadStatus.DbUnavailable, true);
//Delete corrupt local database
if (Business.Services.DatabaseExists())
{
Business.Services.DeleteDatabase();
}
}
else
{
UpdateStatus(LoadStatus.DbInitialization, true);
}
Application.DoEvents();
}
/// <summary>
/// used for non-error status messages
/// redirects to UpdateStatus() with isError = false
/// </summary>
/// <param name="status"></param>
private void UpdateStatus(LoadStatus status)
{
UpdateStatus(status, false);
}
/// <summary>
/// Notifies the launcher windows of a status changes
/// and passes the new status code to it
/// </summary>
/// <param name="status">new status enum</param>
/// <param name="isError">is the new state an error state</param>
private void UpdateStatus(LoadStatus status, bool isError)
{
//only if we have a valid handle
if (launchWindow != IntPtr.Zero)
{
//send the message to the splash screen with the message value the splash screen is waiting for.
Native.SendMessage(launchWindow, (isError) ? WM_ERROR : WM_STATUSUPDATE, (int)status, 0);
Application.DoEvents();
}
}
/// <summary>
/// Notifies the launcher window that the loading process is complete
/// </summary>
/// <param name="window"></param>
private static void SignalLoaded(IntPtr window)
{
//only if we have a valid handle
if (window != IntPtr.Zero)
{
//send the message to the splash screen with the message value the splash screen is waiting for.
Native.SendMessage(window, WM_DONE, 0, 0);
}
}
#endregion
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -