4.5. Creating a User Interface
In our application, we will create interfaces for two primary entities: a form each for the product and the customer entities. Each form contains a DataGridView grid, a ToolStrip toolbar with buttons and also a BindingSource component that is used to bind data to the controls on the form.
Figure 24. A form for the Customer entity
Since both forms are similar in function and implementation, we will describe just one.
4.5.1. Getting a Context
To work with our model, we will need the method for getting a context (or a model). The following statement is sufficient for that purpose:
DbModel dbContext = new DbModel();
If no confidential data are stored in the connection string — for example, the password is absent because it will be captured during the authentication process when the application is started — we will need a special method for storing and recovering the connection string or for storing the previously created context. For that, we will create a special class containing some application-level global variables, along with a method for getting a context.
A context might be the start and end dates of a work period, for example.
static class AppVariables
{
private static DbModel dbContext = null;
/// <summary>
/// Start date of the working period
/// </summary>
public static DateTime StartDate { get; set; }
/// <summary>
/// End date of the working period
/// </summary>
public static DateTime FinishDate { get; set; }
/// <summary>
/// Returns an instance of the model (context)
/// </summary>
/// <returns>Model</returns>
public static DbModel CreateDbContext() {
dbContext = dbContext ?? new DbModel();
return dbContext;
}
}
The connection string itself is applied after the authentication process completes successfully during the application launch. We will add the following code to the Load
event handler of the main form for that.
private void MainForm_Load(object sender, EventArgs e) {
var dialog = new LoginForm();
if (dialog.ShowDialog() == DialogResult.OK)
{
var dbContext = AppVariables.getDbContext();
try
{
string s = dbContext.Database.Connection.ConnectionString;
var builder = new FbConnectionStringBuilder(s);
builder.UserID = dialog.UserName;
builder.Password = dialog.Password;
dbContext.Database.Connection.ConnectionString = builder.ConnectionString;
// try connect
dbContext.Database.Connection.Open();
}
catch (Exception ex)
{
// display error
MessageBox.Show(ex.Message, "Error");
Application.Exit();
}
}
else
Application.Exit();
}
Now, to get a context, we use the static CreateDbContext
method:
var dbContext = AppVariables.getDbContext();