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.

fbdevgd30 efw 014 en

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:

  1. 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.

  1. static class AppVariables
  2. {
  3. private static DbModel dbContext = null;
  4. /// <summary>
  5. /// Start date of the working period
  6. /// </summary>
  7. public static DateTime StartDate { get; set; }
  8. /// <summary>
  9. /// End date of the working period
  10. /// </summary>
  11. public static DateTime FinishDate { get; set; }
  12. /// <summary>
  13. /// Returns an instance of the model (context)
  14. /// </summary>
  15. /// <returns>Model</returns>
  16. public static DbModel CreateDbContext() {
  17. dbContext = dbContext ?? new DbModel();
  18. return dbContext;
  19. }
  20. }

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.

  1. private void MainForm_Load(object sender, EventArgs e) {
  2. var dialog = new LoginForm();
  3. if (dialog.ShowDialog() == DialogResult.OK)
  4. {
  5. var dbContext = AppVariables.getDbContext();
  6. try
  7. {
  8. string s = dbContext.Database.Connection.ConnectionString;
  9. var builder = new FbConnectionStringBuilder(s);
  10. builder.UserID = dialog.UserName;
  11. builder.Password = dialog.Password;
  12. dbContext.Database.Connection.ConnectionString = builder.ConnectionString;
  13. // try connect
  14. dbContext.Database.Connection.Open();
  15. }
  16. catch (Exception ex)
  17. {
  18. // display error
  19. MessageBox.Show(ex.Message, "Error");
  20. Application.Exit();
  21. }
  22. }
  23. else
  24. Application.Exit();
  25. }

Now, to get a context, we use the static CreateDbContext method:

  1. var dbContext = AppVariables.getDbContext();