Home

Application Authentication

   

Introduction

Application authentication consists of restricting access to an application. You can first create an application and take care of authentication later, but it is better to design the concept before starting. In this series of articles, we are going to create a complete application, step by step, and in different sections that each deals with one particular issue.

Imagine you want to create an application for a department store. One of the things you can take care of, as far as people who access the program are concerned, is authentication.

In this example, we will create an application for file processing. We will use either Microsoft Visual Studio 2010 Professional or Microsoft Visual C# 2010 Express.

Practical LearningPractical Learning: Creating a Folder for the Application

  1. Log on to the server or the computer that will hold the records for the application
  2. Create a folder named Fun Department Store
  3. Right-click that folder and click Share
     
    Sharing a Folder
  4. Click the arrow of the combo box in the File Sharing window and select Everyone
  5. Click Add
  6. Click the down-pointing arrow on the right side of Everyone:
    • If you are sharing from Microsoft Windows Server 2008, select Contributor
       
      Sharing
    • If you are sharing from Microsoft Windows 7, select Read/Write
  7. Click Share
     
    Sharing
  8. Click Close

Practical LearningPractical Learning: Starting the Project

  1. Launch either Microsoft Visual C# Express or Microsoft Visual Studio
  2. To start an application, on the main menu, click File -> New Project ...
  3. If you are using Microsoft Visual Studio, in the left list, click Visual C#.
    In the middle list, click Empty Project
  4. Set the Name to FunDS1
  5. Click OK
  6. On the main menu, click Project -> FunDepartmentStore1 Properties...
  7. In the Output Type combo box, select Windows Application
  8. Close the Properties window
  9. On the main menu, click Project -> Add Reference...
  10. In the Add Reference dialog box, click .NET
  11. In the list view, click System.Data
  12. Press and hold Ctrl
  13. Click System
  14. Click System.Drawing
  15. Click System.Windows.Forms
  16. Click System.Xml
  17. Release Ctrl
  18. Click OK
  19. To save the project, on the Standard toolbar, click the Save All button
  20. Accept the suggested path but make a note of it (you will need it) and click OK
  21. To create a file for the project, on the main menu, click Project -> Add New Item...
  22. In the middle list, click Code File
  23. Set the name to Employee
  24. Click Add
  25. In the empty document, type the following:
    using System;
    
    [Serializable]
    public class Employee
    {
        public string EmployeeNumber { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Title { get; set; }
        public bool   Manager { get; set; }
        public double HourlySalary { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
    }
  26. To create a file for the project, on the main menu, click Project -> Add New Item...
  27. In the middle list, click Code File
  28. Set the name to StoreItem
  29. Click Add
  30. In the empty document, type the following:
    using System;
    
    [Serializable]
    public class StoreItem
    {
        public string ItemNumber { get; set; }
        public DateTime ArrivalDate { get; set; }
        public string Manufacturer { get; set; }
        public string Category { get; set; }
        public string SubCategory { get; set; }
        public string ItemName { get; set; }
        public string ItemSize { get; set; }
        public double UnitPrice { get; set; }
        public double DiscountRate { get; set; }
        public string SaleStatus { get; set; }
    }
  31. To create a new file, on the main menu, click Project -> Add File...
  32. In the middle list, click Code File
  33. Set the Name to StoreInventory
  34. Click Add
  35. In the empty document, type the following:
    using System;
    using System.Data;
    using System.Drawing;
    using System.Windows.Forms;
    using System.ComponentModel;
    
    public class StoreInventory : Form
    {
        private ColumnHeader colIndex;
        private ColumnHeader colItemNumber;
        private ColumnHeader colArrivalDate;
        private ColumnHeader colManufacturer;
        private ColumnHeader colCategory;
        private ColumnHeader colSubCategory;
        private ColumnHeader colItemName;
        private ColumnHeader colItemSize;
        private ColumnHeader colUnitPrice;
        private ColumnHeader colSaleStatus;
    
        private ListView lvwStoreItems;
    
        private Button btnClose;
    
        public StoreInventory()
        {
            InitializeComponent();
        }
    
        private void InitializeComponent()
        {
            colIndex = new ColumnHeader();
            colItemNumber = new ColumnHeader();
            colArrivalDate = new ColumnHeader();
            colManufacturer = new ColumnHeader();
            colCategory = new ColumnHeader();
            colSubCategory = new ColumnHeader();
            colItemName = new ColumnHeader();
            colItemSize = new ColumnHeader();
            colUnitPrice = new ColumnHeader();
            colSaleStatus = new ColumnHeader();
    
            lvwStoreItems = new ListView();
            btnClose = new Button();
    
            SuspendLayout();
    
            colIndex.Text = "Index";
            colIndex.Width = 40;
    
            colItemNumber.Text = "Item #";
            colItemNumber.TextAlign = HorizontalAlignment.Center;
            colItemNumber.Width = 50;
    
            colArrivalDate.Text = "Arrival Date";
            colArrivalDate.Width = 70;
    
            colManufacturer.Text = "Manufacturer";
            colManufacturer.Width = 100;
    
            colCategory.Text = "Category";
            colSubCategory.Text = "Sub-Category";
            colSubCategory.Width = 80;
    
            colItemName.Text = "Item Name/Description";
            colItemName.Width = 220;
    
            colItemSize.Text = "Size";
            colItemSize.TextAlign = HorizontalAlignment.Center;
    
            colUnitPrice.Text = "Unit Price";
            colUnitPrice.TextAlign = HorizontalAlignment.Right;
    
            colSaleStatus.Text = "Status";
            colSaleStatus.Width = 70;
    
            btnClose.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            btnClose.Location = new Point(772, 182);
            btnClose.Size = new Size(75, 23);
            btnClose.TabIndex = 33;
            btnClose.Text = "Close";
            btnClose.UseVisualStyleBackColor = true;
            btnClose.Click += new System.EventHandler(btnCloseClicked);
    
            lvwStoreItems.Anchor = AnchorStyles.Top | AnchorStyles.Bottom |
                                   AnchorStyles.Left | AnchorStyles.Right;
            lvwStoreItems.Columns.AddRange(new ColumnHeader[] {
                colIndex, colItemNumber, colArrivalDate, colManufacturer,
                colCategory, colSubCategory, colItemName,
                colItemSize, colUnitPrice, colSaleStatus});
            lvwStoreItems.FullRowSelect = true;
            lvwStoreItems.GridLines = true;
            lvwStoreItems.Location = new Point(12, 12);
            lvwStoreItems.Size = new Size(835, 160);
            lvwStoreItems.TabIndex = 32;
            lvwStoreItems.UseCompatibleStateImageBehavior = false;
            lvwStoreItems.View = System.Windows.Forms.View.Details;
    
            ClientSize = new Size(859, 213);
            Controls.Add(btnClose);
            Controls.Add(lvwStoreItems);
            ShowInTaskbar = false;
            StartPosition = FormStartPosition.CenterScreen;
            Text = "Fun Department Store - Current Store Inventory";
            Load += new System.EventHandler(StoreInventoryLoaded);
    
            ResumeLayout(false);
        }
    
        private void ShowInventory()
        {
    
        }
    
        private void StoreInventoryLoaded(object sender, EventArgs e)
        {
            ShowInventory();
        }
    
        private void btnCloseClicked(object sender, EventArgs e)
        {
            Close();
        }
    }
  36. To create a new file, on the main menu, click Project -> Add New Item...
  37. In the middle list, click Code File
  38. Set the Name to Switchboard
  39. Click Add
  40. In the empty document, type the following:
    using System;
    using System.Data;
    using System.Drawing;
    using System.Windows.Forms;
    using System.ComponentModel;
    
    public class Switchboard : Form
    {
        private Button btnStoreInventory;
        private Button btnCreateStoreItem;
        private Button btnEmployees;
        private Button btnLogInUser;
        private Button btnClose;
    
        public Switchboard()
        {
            InitializeComponent();
        }
    
        private void InitializeComponent()
        {
            btnStoreInventory = new Button();
            btnCreateStoreItem = new Button();
            btnEmployees = new Button();
            btnLogInUser = new Button();
            btnClose = new Button();
    
            SuspendLayout();
            
            btnStoreInventory.Font = new Font("Georgia", 18F,
                FontStyle.Bold, GraphicsUnit.Point, 0);
            btnStoreInventory.Location = new Point(12, 12);
            btnStoreInventory.Size = new Size(227, 98);
            btnStoreInventory.TabIndex = 23;
            btnStoreInventory.Text = "View Store Inventory";
            btnStoreInventory.UseVisualStyleBackColor = true;
            btnStoreInventory.Click +=
                new System.EventHandler(btnStoreInventoryClicked);
    
            btnCreateStoreItem.Font = new Font("Georgia", 18F,
                FontStyle.Bold, GraphicsUnit.Point, 0);
            btnCreateStoreItem.Location = new Point(255, 13);
            btnCreateStoreItem.Size = new Size(227, 98);
            btnCreateStoreItem.TabIndex = 25;
            btnCreateStoreItem.Text = "Create Store Item";
            btnCreateStoreItem.UseVisualStyleBackColor = true;
            btnCreateStoreItem.Click +=
                new System.EventHandler(btnCreateStoreItemClicked);
    
            btnEmployees.Font = new Font("Georgia", 18F,
                FontStyle.Bold, GraphicsUnit.Point, 0);
            btnEmployees.Location = new Point(12, 128);
            btnEmployees.Size = new Size(227, 98);
            btnEmployees.TabIndex = 27;
            btnEmployees.Text = "Employees";
            btnEmployees.UseVisualStyleBackColor = true;
            btnEmployees.Click +=
                new System.EventHandler(btnEmployeesClicked);
    
            btnLogInUser.Font = new Font("Georgia", 18F,
                FontStyle.Bold, GraphicsUnit.Point, 0);
            btnLogInUser.Location = new Point(255, 128);
            btnLogInUser.Size = new Size(227, 98);
            btnLogInUser.TabIndex = 26;
            btnLogInUser.Text = "Log in as a Different Employee";
            btnLogInUser.UseVisualStyleBackColor = true;
            btnLogInUser.Click +=
                new System.EventHandler(btnLogInUserClicked);
    
            btnClose.Font = new Font("Georgia", 18F,
                FontStyle.Bold, GraphicsUnit.Point, 0);
            btnClose.Location = new Point(11, 241);
            btnClose.Size = new Size(471, 67);
            btnClose.TabIndex = 24;
            btnClose.Text = "Close Application";
            btnClose.UseVisualStyleBackColor = true;
            btnClose.Click += new System.EventHandler(btnCloseClicked);
    
            ClientSize = new Size(494, 319);
            Controls.Add(btnEmployees);
            Controls.Add(btnLogInUser);
            Controls.Add(btnCreateStoreItem);
            Controls.Add(btnClose);
            Controls.Add(btnStoreInventory);
            Name = "Switchboard";
            StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            Text = "Fun Department Store";
    
            ResumeLayout(false);
        }
    
        private void btnStoreInventoryClicked(object sender, EventArgs e)
        {
            StoreInventory si = new StoreInventory();
            si.ShowDialog();
        }
    
        private void btnCreateStoreItemClicked(object sender, EventArgs e)
        {
    
        }
    
        private void btnEmployeesClicked(object sender, EventArgs e)
        {
    
        }
    
        private void btnLogInUserClicked(object sender, EventArgs e)
        {
    
        }
    
        private void btnCloseClicked(object sender, EventArgs e)
        {
            Close();
        }
    }
    
    public class DepartmentStore
    {
        public static int Main()
        {
            Application.Run(new Switchboard());
            return 0;
        }
    }
  41. To execute the application, press F5
  42. Click the View Store Inventory button
  43. Close the Store Inventory form
  44. Close the Switchboard form
  45. To add a new file, on the main menu, click Project -> New Item...
  46. In the middle list, click Code File
  47. Change the Name to CreateStoreItem
  48. Click Add
  49. In the empty document, type the following:
    using System;
    using System.IO;
    using System.Data;
    using System.Drawing;
    using System.Windows.Forms;
    using System.ComponentModel;
    using System.Collections.Generic;
    using System.Runtime.Serialization.Formatters.Binary;
    
    public class CreateStoreItem : Form
    {
        private Label lblItemNumber;
        private TextBox txtItemNumber;
        private Label lblArrivalDate;
        private MaskedTextBox txtArrivalDate;
        private Label lblManufacturer;
        private TextBox txtManufacturer;
        private Label lblCategory;
        private ComboBox cbxCategories;
        private Label lblSubCategory;
        private ComboBox cbxSubCategories;
        private Label lblItemName;
        private TextBox txtItemName;
        private Label lblItemSize;
        private TextBox txtItemSize;
        private Label lblUnitPrice;
        private TextBox txtUnitPrice;
        private Label lblDiscountRate;
        private TextBox txtDiscountRate;
        private Label lblPercent;
        private Label lblSaleStatus;
        private ComboBox cbxSaleStatus;
    
        private Button btnReset;
        private Button btnCreate;
        private Button btnClose;
    
        public CreateStoreItem()
        {
            InitializeComponent();
        }
    
        private void InitializeComponent()
        {
            lblItemNumber = new Label();
            txtItemNumber = new TextBox();
            lblArrivalDate = new Label();
            txtArrivalDate = new MaskedTextBox();
            lblManufacturer = new Label();
            txtManufacturer = new TextBox();
            lblCategory = new Label();
            cbxCategories = new ComboBox();
            lblSubCategory = new Label();
            cbxSubCategories = new ComboBox();
            lblItemName = new Label();
            txtItemName = new TextBox();
            lblItemSize = new Label();
            txtItemSize = new TextBox();
            lblUnitPrice = new Label();
            txtUnitPrice = new TextBox();
            txtDiscountRate = new TextBox();
            lblDiscountRate = new Label();
            lblPercent = new Label();
            lblSaleStatus = new Label();
            cbxSaleStatus = new ComboBox();
    
            btnClose = new Button();
            btnCreate = new Button();
            btnReset = new Button();
            
            SuspendLayout();
    
            lblItemNumber.AutoSize = true;
            lblItemNumber.Location = new Point(11, 14);
            lblItemNumber.Size = new Size(40, 13);
            lblItemNumber.TabIndex = 0;
            lblItemNumber.Text = "Item #:";
    
            txtItemNumber.Location = new Point(95, 11);
            txtItemNumber.Size = new Size(96, 20);
            txtItemNumber.TabIndex = 1;
    
            lblArrivalDate.AutoSize = true;
            lblArrivalDate.Location = new Point(223, 14);
            lblArrivalDate.Size = new Size(65, 13);
            lblArrivalDate.TabIndex = 2;
            lblArrivalDate.Text = "Arrival Date:";
    
            txtArrivalDate.Location = new Point(303, 11);
            txtArrivalDate.Mask = "00/00/0000";
            txtArrivalDate.Size = new Size(121, 20);
            txtArrivalDate.TabIndex = 3;
            txtArrivalDate.ValidatingType = typeof(System.DateTime);
    
            lblManufacturer.AutoSize = true;
            lblManufacturer.Location = new Point(11, 43);
            lblManufacturer.Size = new Size(73, 13);
            lblManufacturer.TabIndex = 4;
            lblManufacturer.Text = "Manufacturer:";
    
            txtManufacturer.Location = new Point(95, 40);
            txtManufacturer.Size = new Size(330, 20);
            txtManufacturer.TabIndex = 5;
    
            lblCategory.AutoSize = true;
            lblCategory.Location = new Point(11, 72);
            lblCategory.Size = new Size(52, 13);
            lblCategory.TabIndex = 6;
            lblCategory.Text = "Category:";
    
            cbxCategories.FormattingEnabled = true;
            cbxCategories.Items.AddRange(new object[] {
                "Men", "Girls", "Boys",
                "Babies", "Women", "Other"});
            cbxCategories.Location = new Point(95, 70);
            cbxCategories.Size = new Size(116, 21);
            cbxCategories.TabIndex = 7;
    
            lblSubCategory.AutoSize = true;
            lblSubCategory.Location = new Point(223, 73);
            lblSubCategory.Size = new Size(74, 13);
            lblSubCategory.TabIndex = 8;
            lblSubCategory.Text = "Sub-Category:";
    
            cbxSubCategories.FormattingEnabled = true;
            cbxSubCategories.Items.AddRange(new object[] {
                "Skirts", "Pants", "Shirts", "Shoes",
                "Blouse", "Beauty", "Dresses", "Clothing",
                "Sweater", "Watches", "Handbags", "Miscellaneous"});
            cbxSubCategories.Location = new Point(303, 70);
            cbxSubCategories.Size = new Size(121, 21);
            cbxSubCategories.TabIndex = 9;
    
            lblItemName.AutoSize = true;
            lblItemName.Location = new Point(11, 104);
            lblItemName.Size = new Size(61, 13);
            lblItemName.TabIndex = 10;
            lblItemName.Text = "Item Name:";
    
            txtItemName.Location = new Point(95, 100);
            txtItemName.Size = new Size(329, 20);
            txtItemName.TabIndex = 11;
    
            lblItemSize.AutoSize = true;
            lblItemSize.Location = new Point(12, 132);
            lblItemSize.Size = new Size(30, 13);
            lblItemSize.TabIndex = 12;
            lblItemSize.Text = "Size:";
    
            txtItemSize.Location = new Point(95, 129);
            txtItemSize.Size = new Size(96, 20);
            txtItemSize.TabIndex = 13;
    
            lblUnitPrice.AutoSize = true;
            lblUnitPrice.Location = new Point(224, 135);
            lblUnitPrice.Size = new Size(56, 13);
            lblUnitPrice.TabIndex = 14;
            lblUnitPrice.Text = "Unit Price:";
    
            txtUnitPrice.Location = new Point(304, 132);
            txtUnitPrice.Size = new Size(121, 20);
            txtUnitPrice.TabIndex = 15;
            txtUnitPrice.Text = "0.00";
            txtUnitPrice.TextAlign = HorizontalAlignment.Right;
    
            lblDiscountRate.AutoSize = true;
            lblDiscountRate.Location = new Point(11, 161);
            lblDiscountRate.Size = new Size(78, 13);
            lblDiscountRate.TabIndex = 16;
            lblDiscountRate.Text = "Discount Rate:";
    
            txtDiscountRate.Location = new Point(95, 158);
            txtDiscountRate.Size = new Size(96, 20);
            txtDiscountRate.TabIndex = 17;
            txtDiscountRate.Text = "0.00";
            txtDiscountRate.TextAlign = HorizontalAlignment.Right;
    
            lblPercent.AutoSize = true;
            lblPercent.Font = new Font("Microsoft Sans Serif", 9.75F,
                                       FontStyle.Bold,
                                       GraphicsUnit.Point, ((byte)(0)));
            lblPercent.Location = new Point(191, 161);
            lblPercent.Size = new Size(21, 16);
            lblPercent.TabIndex = 18;
            lblPercent.Text = "%";
    
            lblSaleStatus.AutoSize = true;
            lblSaleStatus.Location = new Point(224, 164);
            lblSaleStatus.Size = new Size(64, 13);
            lblSaleStatus.TabIndex = 19;
            lblSaleStatus.Text = "Sale Status:";
    
            cbxSaleStatus.FormattingEnabled = true;
            cbxSaleStatus.Items.AddRange(new object[] {
                "Sold", "In Stock",
                "On Display", "Processing", "Other"});
            cbxSaleStatus.Location = new Point(304, 161);
            cbxSaleStatus.Size = new Size(121, 21);
            cbxSaleStatus.TabIndex = 20;
    
            btnReset.Location = new Point(125, 193);
            btnReset.Size = new Size(95, 23);
            btnReset.TabIndex = 23;
            btnReset.Text = "Reset";
            btnReset.UseVisualStyleBackColor = true;
            btnReset.Click += new System.EventHandler(btnResetClicked);
    
            btnCreate.Location = new Point(226, 193);
            btnCreate.Size = new Size(108, 23);
            btnCreate.TabIndex = 21;
            btnCreate.Text = "Create";
            btnCreate.UseVisualStyleBackColor = true;
            btnCreate.Click += new System.EventHandler(btnCreateClicked);
    
            btnClose.Location = new Point(340, 193);
            btnClose.Size = new Size(83, 23);
            btnClose.TabIndex = 22;
            btnClose.Text = "Close";
            btnClose.UseVisualStyleBackColor = true;
            btnClose.Click += new System.EventHandler(btnCloseClicked);
    
            ClientSize = new Size(437, 230);
            Controls.Add(txtManufacturer);
            Controls.Add(lblPercent);
            Controls.Add(txtDiscountRate);
            Controls.Add(lblDiscountRate);
            Controls.Add(txtArrivalDate);
            Controls.Add(lblArrivalDate);
            Controls.Add(btnClose);
            Controls.Add(btnCreate);
            Controls.Add(btnReset);
            Controls.Add(txtUnitPrice);
            Controls.Add(lblUnitPrice);
            Controls.Add(cbxSaleStatus);
            Controls.Add(lblSaleStatus);
            Controls.Add(txtItemSize);
            Controls.Add(lblItemSize);
            Controls.Add(txtItemName);
            Controls.Add(lblItemName);
            Controls.Add(cbxSubCategories);
            Controls.Add(lblSubCategory);
            Controls.Add(cbxCategories);
            Controls.Add(lblCategory);
            Controls.Add(lblManufacturer);
            Controls.Add(txtItemNumber);
            Controls.Add(lblItemNumber);
    
            FormBorderStyle = FormBorderStyle.FixedDialog;
            MaximizeBox = false;
            MinimizeBox = false;
            ShowInTaskbar = false;
            StartPosition = FormStartPosition.CenterScreen;
            Text = "Fun Department Store - Create New Store Item";
            Load += new System.EventHandler(CreateStoreItemLoaded);
    
            ResumeLayout(false);
            PerformLayout();
        }
    
        private void btnResetClicked(object sender, EventArgs e)
        {
            Random rndNumber = new Random();
            txtItemNumber.Text = rndNumber.Next(100000, 999999).ToString();
    
            txtArrivalDate.Text = DateTime.Today.ToShortDateString();
            txtManufacturer.Text = "";
            cbxCategories.Text = "";
            cbxSubCategories.Text = "";
            txtItemName.Text = "";
            txtItemSize.Text = "";
            txtUnitPrice.Text = "0.00";
            txtDiscountRate.Text = "";
            cbxSaleStatus.Text = "";
        }
    
        private void CreateStoreItemLoaded(object sender, EventArgs e)
        {
            // When the form opens, reset it
            btnResetClicked(sender, e);
        }
    
        private void btnCreateClicked(object sender, EventArgs e)
        {
            double unitPrice = 0.00;
            double discountRate = 0.00;
            FileStream fsStoreItems = null;
            DateTime dtArrivalDate = DateTime.Today;
            BinaryFormatter bfStoreItems = new BinaryFormatter();
            List<StoreItem> lstStoreItems = new List<StoreItem>();
            string strFileName = @"\\Expression\\Fun Department Store\\StoreItems.fds";
    
            // Make sure the user entered an item number.
            // If not, don't do anything
            if (txtItemNumber.Text.Length == 0)
            {
                MessageBox.Show("You must provide a (unique) item number.",
                                "Fun Department Store",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
    
            // Make sure the user entered a name for the new item.
            // If not, don't do anything
            if (txtItemName.Text.Length == 0)
            {
                MessageBox.Show("You must provide a name for the item.",
                                "Fun Department Store",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
    
            // Make sure the user provided a price for the item
            if (txtUnitPrice.Text.Length == 0)
            {
                MessageBox.Show("You must provide a price for the item.",
                                "Fun Department Store",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
    
            try
            {
                dtArrivalDate = DateTime.Parse(txtArrivalDate.Text);
            }
            catch (FormatException)
            {
            }
    
            // Check if the user provided a valid price...
            try
            {
                unitPrice = double.Parse(txtUnitPrice.Text);
            }
            catch (FormatException)
            {
                // ... if not, use 0.00
            }
    
            // Check if the user provided a valid discount rate...
            try
            {
                discountRate = double.Parse(txtDiscountRate.Text);
            }
            catch (FormatException)
            {
                // ... if not, use 0.00
            }
    
            if (!Directory.Exists(@"\\Expression\\Fun Department Store"))
            {
                MessageBox.Show("The folder used to hold the records doesn't exist.",
                                "Fun Department Store",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
    
            if (File.Exists(strFileName))
            {
                fsStoreItems = new FileStream(strFileName, FileMode.Open,
                                              FileAccess.Read, FileShare.Read);
    
                try
                {
                    lstStoreItems = 
                    	(List<StoreItem>)(bfStoreItems.Deserialize(fsStoreItems));
                }
                finally
                {
                    fsStoreItems.Close();
                }
            }
    
            StoreItem si = new StoreItem();
    
            si.ItemNumber = txtItemNumber.Text;
    
            if (txtArrivalDate.Text != "")
                si.ArrivalDate = dtArrivalDate;
            si.Manufacturer = txtManufacturer.Text;
            si.Category = cbxCategories.Text;
            si.SubCategory = cbxSubCategories.Text;
            si.ItemName = txtItemName.Text;
            si.ItemSize = txtItemSize.Text;
            si.UnitPrice = unitPrice;
            if (txtDiscountRate.Text != "")
                si.DiscountRate = discountRate;
            si.SaleStatus = cbxSaleStatus.Text;
            lstStoreItems.Add(si);
    
            fsStoreItems = new FileStream(strFileName, FileMode.Create,
                                          FileAccess.Write, FileShare.Write);
            try
            {
                bfStoreItems.Serialize(fsStoreItems, lstStoreItems);
    
                // Once the item has been created, let the user know
                MessageBox.Show("The item has been created",
                                "Fun Department Store",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
    
                btnResetClicked(sender, e);
            }
            finally
            {
                fsStoreItems.Close();
            }
        }
    
        private void btnCloseClicked(object sender, EventArgs e)
        {
            Close();
        }
    }
  50. In the Solution Explorer, double-click CreateStoreItem.cs
     
    Fun Department Store - Create Store Item
  51. Display the StoreInventory.cs file
  52. Change the ShowInventory() method as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Drawing;
    using System.Windows.Forms;
    using System.ComponentModel;
    using System.Collections.Generic;
    using System.Runtime.Serialization.Formatters.Binary;
    
    public class StoreInventory : Form
    {
        private ColumnHeader colIndex;
        private ColumnHeader colItemNumber;
        private ColumnHeader colArrivalDate;
        private ColumnHeader colManufacturer;
        private ColumnHeader colCategory;
        private ColumnHeader colSubCategory;
        private ColumnHeader colItemName;
        private ColumnHeader colItemSize;
        private ColumnHeader colUnitPrice;
        private ColumnHeader colSaleStatus;
    
        private ListView lvwStoreItems;
        private Button btnClose;
    
        public StoreInventory()
        {
            InitializeComponent();
        }
    
        private void InitializeComponent()
        {
            colIndex = new System.Windows.Forms.ColumnHeader();
            colItemNumber = new System.Windows.Forms.ColumnHeader();
            colArrivalDate = new System.Windows.Forms.ColumnHeader();
            colManufacturer = new System.Windows.Forms.ColumnHeader();
            colCategory = new System.Windows.Forms.ColumnHeader();
            colSubCategory = new System.Windows.Forms.ColumnHeader();
            colItemName = new System.Windows.Forms.ColumnHeader();
            colItemSize = new System.Windows.Forms.ColumnHeader();
            colUnitPrice = new System.Windows.Forms.ColumnHeader();
            colSaleStatus = new System.Windows.Forms.ColumnHeader();
            lvwStoreItems = new System.Windows.Forms.ListView();
            btnClose = new System.Windows.Forms.Button();
    
            SuspendLayout();
     
            colIndex.Text = "Index";
            colIndex.Width = 40;
    
            colItemNumber.Text = "Item #";
            colItemNumber.TextAlign = HorizontalAlignment.Center;
            colItemNumber.Width = 50;
    
            colArrivalDate.Text = "Arrival Date";
            colArrivalDate.Width = 70;
    
            colManufacturer.Text = "Manufacturer";
            colManufacturer.Width = 100;
    
            colCategory.Text = "Category";
            colSubCategory.Text = "Sub-Category";
            colSubCategory.Width = 80;
    
            colItemName.Text = "Item Name/Description";
            colItemName.Width = 220;
    
            colItemSize.Text = "Size";
            colItemSize.TextAlign = HorizontalAlignment.Center;
    
            colUnitPrice.Text = "Unit Price";
            colUnitPrice.TextAlign = HorizontalAlignment.Right;
     
            colSaleStatus.Text = "Status";
            colSaleStatus.Width = 70;
    
            btnClose.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            btnClose.Location = new Point(772, 182);
            btnClose.Size = new Size(75, 23);
            btnClose.TabIndex = 33;
            btnClose.Text = "Close";
            btnClose.UseVisualStyleBackColor = true;
            btnClose.Click += new System.EventHandler(btnCloseClicked);
    
            lvwStoreItems.Anchor = AnchorStyles.Top | AnchorStyles.Bottom |
                                   AnchorStyles.Left | AnchorStyles.Right;
            lvwStoreItems.Columns.AddRange(new ColumnHeader[] {
                colIndex, colItemNumber, colArrivalDate, colManufacturer,
                colCategory, colSubCategory, colItemName,
                colItemSize, colUnitPrice, colSaleStatus});
            lvwStoreItems.FullRowSelect = true;
            lvwStoreItems.GridLines = true;
            lvwStoreItems.Location = new Point(12, 12);
            lvwStoreItems.Size = new Size(835, 160);
            lvwStoreItems.TabIndex = 32;
            lvwStoreItems.UseCompatibleStateImageBehavior = false;
            lvwStoreItems.View = System.Windows.Forms.View.Details;
     
            ClientSize = new Size(859, 213);
            Controls.Add(btnClose);
            Controls.Add(lvwStoreItems);
            ShowInTaskbar = false;
            StartPosition = FormStartPosition.CenterScreen;
            Text = "Fun Department Store - Current Store Inventory";
            Load += new System.EventHandler(StoreInventoryLoaded);
    
            ResumeLayout(false);
        }
    
        private void ShowInventory()
        {
            List StoreItems;
            FileStream fsStoreItems = null;
            BinaryFormatter bfStoreItems = new BinaryFormatter();
    
            // If there were some items in the list view, remove them before filling it up
            lvwStoreItems.Items.Clear();
    
            string strFileName = @"\\Expression\\Fun Department Store\\StoreItems.fds";
             
            if (File.Exists(strFileName))
            {
                fsStoreItems = new FileStream(strFileName, FileMode.Open,
                                              FileAccess.Read, FileShare.Read);
    
                try
                {
                    StoreItems = (List)(bfStoreItems.Deserialize(fsStoreItems));
                
                    // Using the total number of records, display each in the list view
                    for(int i = 0; i < StoreItems.Count; i++)
                    {
                        StoreItem si = StoreItems[i];
    
                    ListViewItem lviStoreItem = new ListViewItem((i + 1).ToString());
                    lviStoreItem.SubItems.Add(si.ItemNumber);
                    lviStoreItem.SubItems.Add(si.ArrivalDate.ToShortDateString());
                    lviStoreItem.SubItems.Add(si.Manufacturer);
                    lviStoreItem.SubItems.Add(si.Category);
                    lviStoreItem.SubItems.Add(si.SubCategory);
                    lviStoreItem.SubItems.Add(si.ItemName);
                    lviStoreItem.SubItems.Add(si.ItemSize);
                    lviStoreItem.SubItems.Add(si.DiscountRate.ToString("F"));
                    lviStoreItem.SubItems.Add(si.UnitPrice.ToString("F"));
                    lviStoreItem.SubItems.Add(si.SaleStatus);
                    lvwStoreItems.Items.Add(lviStoreItem);
                }
                }
                finally
                {
                    fsStoreItems.Close();
                }
            }
        }
    
        private void StoreInventoryLoaded(object sender, EventArgs e)
        {
            ShowInventory();
        }
    
        private void btnCloseClicked(object sender, EventArgs e)
        {
            Close();
        }
    }
  53. To create a new file, on the main menu, click Project -> Add New Item...
  54. In the middle list, make sure Code File is selected.
    Change the Name to Employees
  55. Click Add
  56. In the empty document, type the following:
    using System;
    using System.IO;
    using System.Data;
    using System.Drawing;
    using System.Windows.Forms;
    using System.ComponentModel;
    using System.Collections.Generic;
    using System.Runtime.Serialization.Formatters.Binary;
    
    public class Employees : Form
    {
        private ColumnHeader colEmployeeNumber;
        private ColumnHeader colFirstName;
        private ColumnHeader colLastName;
        private ColumnHeader colTitle;
        private ColumnHeader colManager;
        private ColumnHeader colHourlySalary;
        private ColumnHeader colUsername;
        private ColumnHeader colPassword;
        private ListView lvwEmployees;
    
        public GroupBox grpNewEmployee;
        private Label lblEmployeeNumber;
        private MaskedTextBox txtEmployeeNumber;
        private Label lblFirstName;
        private TextBox txtFirstName;
        private Label lblLastName;
        private TextBox txtLastName;
        private Label lblTitle;
        private TextBox txtTitle;
        private Button btnReset;
        private CheckBox chkManager;
        private Label lblHourlySalary;
        private TextBox txtHourlySalary;
        private Button btnSubmit;
        private Label lblUsername;
        private TextBox txtUsername;
        private Label lblPassword;
        private TextBox txtPassword;
    
        private Button btnClose;
    
        public Employees()
        {
            InitializeComponent();
        }
    
        private void InitializeComponent()
        {
            colEmployeeNumber = new ColumnHeader();
            colFirstName = new ColumnHeader();
            colLastName = new ColumnHeader();
            colTitle = new ColumnHeader();
            colManager = new ColumnHeader();
            colHourlySalary = new ColumnHeader();
            colUsername = new ColumnHeader();
            colPassword = new ColumnHeader();
            lvwEmployees = new ListView();
    
            grpNewEmployee = new GroupBox();
    
            lblEmployeeNumber = new Label();
            txtEmployeeNumber = new MaskedTextBox();
            lblFirstName = new Label();
            txtFirstName = new TextBox();
            txtLastName = new TextBox();
            lblLastName = new Label();
            lblTitle = new Label();
            txtTitle = new TextBox();
            btnReset = new Button();
    
            chkManager = new CheckBox();
            lblHourlySalary = new Label();
            txtHourlySalary = new TextBox();
            btnSubmit = new Button();
    
            lblUsername = new Label();
            txtUsername = new TextBox();
            lblPassword = new Label();
            txtPassword = new TextBox();
    
            btnClose = new Button();
    
            grpNewEmployee.SuspendLayout();
            SuspendLayout();
    
            colEmployeeNumber.Text = "Employee #";
            colEmployeeNumber.Width = 70;
            colFirstName.Text = "First Name";
            colFirstName.Width = 80;
            colLastName.Text = "Last Name";
            colLastName.Width = 80;
            colTitle.Text = "Title";
            colTitle.Width = 120;
            colManager.Text = "Manager";
            colHourlySalary.Text = "Salary";
            colHourlySalary.TextAlign = HorizontalAlignment.Right;
            colHourlySalary.Width = 50;
            colUsername.Text = "Username";
            colPassword.Text = "Password";
    
            lvwEmployees.Columns.AddRange(new ColumnHeader[] {
                colEmployeeNumber, colFirstName, colLastName, colTitle,
                colManager, colHourlySalary, colUsername, colPassword});
            lvwEmployees.FullRowSelect = true;
            lvwEmployees.GridLines = true;
            lvwEmployees.Location = new Point(12, 12);
            lvwEmployees.Size = new Size(606, 191);
            lvwEmployees.TabIndex = 0;
            lvwEmployees.UseCompatibleStateImageBehavior = false;
            lvwEmployees.View = System.Windows.Forms.View.Details;
    
            lblEmployeeNumber.AutoSize = true;
            lblEmployeeNumber.Location = new Point(42, 29);
            lblEmployeeNumber.Size = new Size(66, 13);
            lblEmployeeNumber.TabIndex = 0;
            lblEmployeeNumber.Text = "Employee #:";
     
            txtEmployeeNumber.Location = new Point(124, 26);
            txtEmployeeNumber.Mask = "00-000";
            txtEmployeeNumber.Size = new Size(52, 20);
            txtEmployeeNumber.TabIndex = 1;
     
            lblFirstName.AutoSize = true;
            lblFirstName.Location = new Point(42, 55);
            lblFirstName.Size = new Size(60, 13);
            lblFirstName.TabIndex = 2;
            lblFirstName.Text = "First Name:";
    
            txtFirstName.Location = new Point(124, 52);
            txtFirstName.Size = new Size(100, 20);
            txtFirstName.TabIndex = 3;
    
            txtLastName.Location = new Point(327, 52);
            txtLastName.Size = new Size(100, 20);
            txtLastName.TabIndex = 5;
    
            lblLastName.AutoSize = true;
            lblLastName.Location = new Point(245, 55);
            lblLastName.Size = new Size(61, 13);
            lblLastName.TabIndex = 4;
            lblLastName.Text = "Last Name:";
     
            lblTitle.AutoSize = true;
            lblTitle.Location = new Point(42, 81);
            lblTitle.Size = new Size(30, 13);
            lblTitle.TabIndex = 6;
            lblTitle.Text = "Title:";
    
            txtTitle.Location = new Point(124, 78);
            txtTitle.Size = new Size(303, 20);
            txtTitle.TabIndex = 7;
    
            btnReset.Location = new Point(447, 104);
            btnReset.Size = new Size(97, 23);
            btnReset.TabIndex = 15;
            btnReset.Text = "Reset";
            btnReset.UseVisualStyleBackColor = true;
            btnReset.Click += new System.EventHandler(btnResetClicked);
    
            chkManager.AutoSize = true;
            chkManager.CheckAlign = ContentAlignment.MiddleRight;
            chkManager.Location = new Point(45, 107);
            chkManager.Size = new Size(91, 17);
            chkManager.TabIndex = 8;
            chkManager.Text = "Is a Manager:";
            chkManager.UseVisualStyleBackColor = true;
    
            txtHourlySalary.Location = new Point(327, 104);
            txtHourlySalary.Size = new Size(100, 20);
            txtHourlySalary.TabIndex = 10;
            txtHourlySalary.Text = "0.00";
            txtHourlySalary.TextAlign = HorizontalAlignment.Right;
    
            lblHourlySalary.AutoSize = true;
            lblHourlySalary.Location = new Point(245, 107);
            lblHourlySalary.Size = new Size(72, 13);
            lblHourlySalary.TabIndex = 9;
            lblHourlySalary.Text = "Hourly Salary:";
    
            btnSubmit.Location = new Point(447, 132);
            btnSubmit.Size = new Size(97, 23);
            btnSubmit.TabIndex = 16;
            btnSubmit.Text = "Submit";
            btnSubmit.UseVisualStyleBackColor = true;
            btnSubmit.Click += new System.EventHandler(btnSubmitClicked);
    
            lblUsername.AutoSize = true;
            lblUsername.Location = new Point(42, 133);
            lblUsername.Size = new Size(58, 13);
            lblUsername.TabIndex = 11;
            lblUsername.Text = "Username:";
    
            txtUsername.Location = new Point(124, 130);
            txtUsername.Size = new Size(100, 20);
            txtUsername.TabIndex = 12;
    
            lblPassword.AutoSize = true;
            lblPassword.Location = new Point(245, 132);
            lblPassword.Size = new Size(56, 13);
            lblPassword.TabIndex = 13;
            lblPassword.Text = "Password:";
    
            txtPassword.Location = new Point(327, 130);
            txtPassword.PasswordChar = '*';
            txtPassword.Size = new Size(100, 20);
            txtPassword.TabIndex = 14;
    
            btnClose.Location = new Point(459, 384);
            btnClose.Size = new Size(97, 23);
            btnClose.TabIndex = 17;
            btnClose.Text = "Close";
            btnClose.UseVisualStyleBackColor = true;
            btnClose.Click += new System.EventHandler(btnCloseClicked);
    
            grpNewEmployee.Controls.Add(lblEmployeeNumber);
            grpNewEmployee.Controls.Add(txtEmployeeNumber);
            grpNewEmployee.Controls.Add(lblFirstName);
            grpNewEmployee.Controls.Add(txtFirstName);
            grpNewEmployee.Controls.Add(lblLastName);
            grpNewEmployee.Controls.Add(txtLastName);
            grpNewEmployee.Controls.Add(lblTitle);
            grpNewEmployee.Controls.Add(txtTitle);
            grpNewEmployee.Controls.Add(btnReset);
            grpNewEmployee.Controls.Add(chkManager);
            grpNewEmployee.Controls.Add(lblHourlySalary);
            grpNewEmployee.Controls.Add(txtHourlySalary);
            grpNewEmployee.Controls.Add(btnSubmit);
            grpNewEmployee.Controls.Add(lblUsername);
            grpNewEmployee.Controls.Add(txtUsername);
            grpNewEmployee.Controls.Add(lblPassword);
            grpNewEmployee.Controls.Add(txtPassword);
    
            grpNewEmployee.Location = new Point(12, 209);
            grpNewEmployee.Size = new Size(605, 165);
            grpNewEmployee.TabIndex = 1;
            grpNewEmployee.TabStop = false;
            grpNewEmployee.Text = "New Employee";
    
            ClientSize = new Size(629, 414);
            Controls.Add(grpNewEmployee);
            Controls.Add(lvwEmployees);
            Controls.Add(btnClose);
    
            FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            MaximizeBox = false;
            MinimizeBox = false;
            ShowInTaskbar = false;
            StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            Text = "Fun Department Store - Employees";
            Load += new System.EventHandler(Employees_Load);
            grpNewEmployee.ResumeLayout(false);
            grpNewEmployee.PerformLayout();
            ResumeLayout(false);
    
        }
    
        private void ShowEmployees()
        {
            FileStream fsEmployees = null;
            List<Employee> lstEmployees = new List<Employee>();
            BinaryFormatter bfEmployees = new BinaryFormatter();
    
            // If there were some items in the list view, remove them before filling it up
            lvwEmployees.Items.Clear();
    
            string strFileName = @"\\Expression\\Fun Department Store\\Employees.fds";
    
            if (File.Exists(strFileName))
            {
                fsEmployees = new FileStream(strFileName, FileMode.Open,
                                             FileAccess.Read, FileShare.Read);
    
                try
                {
                    lstEmployees = (List<Employee>)(bfEmployees.Deserialize(fsEmployees));
    
                    // Using the total number of records, display each in the list view
                    foreach (Employee empl in lstEmployees)
                    {
                        ListViewItem lviEmployee = new ListViewItem(empl.EmployeeNumber);
    
                        lviEmployee.SubItems.Add(empl.FirstName);
                        lviEmployee.SubItems.Add(empl.LastName);
                        lviEmployee.SubItems.Add(empl.Title);
                        lviEmployee.SubItems.Add(empl.Manager.ToString());
                        lviEmployee.SubItems.Add(empl.HourlySalary.ToString("F"));
                        lviEmployee.SubItems.Add(empl.Username);
                        lviEmployee.SubItems.Add(empl.Password);
    
                        lvwEmployees.Items.Add(lviEmployee);
                    }
                }
                finally
                {
                    fsEmployees.Close();
                }
            }
        }
    
        private void Employees_Load(object sender, EventArgs e)
        {
            ShowEmployees();
            btnResetClicked(sender, e);
        }
    
        private void btnResetClicked(object sender, EventArgs e)
        {
            Random rndNumber = new Random();
    
            txtEmployeeNumber.Text = rndNumber.Next(10000, 99999).ToString();
            txtFirstName.Text = "";
            txtLastName.Text = "";
            txtTitle.Text = "";
            chkManager.Checked = false;
            txtHourlySalary.Text = "0.00";
            txtUsername.Text = "";
            txtPassword.Text = "";
        }
    
        private void btnSubmitClicked(object sender, EventArgs e)
        {
            double hourlySalary = 0.00;
            FileStream fsEmployees = null;
            DateTime dtArrivalDate = DateTime.Today;
            List<Employee> lstEmployees = new List<Employee>();
            BinaryFormatter bfEmployees = new BinaryFormatter();
            string strFileName = @"\\Expression\\Fun Department Store\\Employees.fds";
    
            // Make sure the user entered an employeee number.
            // If not, don't do anything
            if (txtEmployeeNumber.Text.Length == 0)
            {
                MessageBox.Show("You must provide a (unique) employee number.",
                                "Fun Department Store",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
    
            // Make sure the user entered a last name for the new employee.
            // If not, don't do anything
            if (txtLastName.Text.Length == 0)
            {
                MessageBox.Show("You must provide a last name for the employee.",
                                "Fun Department Store",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
    
            // Check if the user provided a valid hourly salary...
            try
            {
                hourlySalary = double.Parse(txtHourlySalary.Text);
            }
            catch (FormatException)
            {
                // ... if not, use 0.00
            }
    
            if (File.Exists(strFileName))
            {
                fsEmployees = new FileStream(strFileName, FileMode.Open,
                                             FileAccess.Read, FileShare.Read);
                try
                {
                    lstEmployees = (List<Employee>)(bfEmployees.Deserialize(fsEmployees));
                }
                finally
                {
                    fsEmployees.Close();
                }
            }
    
            Employee empl = new Employee();
    
            empl.EmployeeNumber = txtEmployeeNumber.Text;
            empl.FirstName = txtFirstName.Text;
            empl.LastName = txtLastName.Text;
            empl.Title = txtTitle.Text;
            empl.Manager = chkManager.Checked;
    
            if (txtHourlySalary.Text != "")
                empl.HourlySalary = hourlySalary;
    
            empl.Username = txtUsername.Text;
            empl.Password = txtPassword.Text;
            lstEmployees.Add(empl);
    
            try
            {
                fsEmployees = new FileStream(strFileName, FileMode.OpenOrCreate,
                                             FileAccess.Write, FileShare.Write);
                bfEmployees.Serialize(fsEmployees, lstEmployees);
    
                // Once the employee record has been created, let the user know
                MessageBox.Show("The employee's record has been created",
                                "Fun Department Store",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
    
                btnResetClicked(sender, e);
            }
            finally
            {
                fsEmployees.Close();
            }
    
            // If there were some items in the list view, remove them before filling it up
            lvwEmployees.Items.Clear();
    
            if (File.Exists(strFileName))
            {
                fsEmployees = new FileStream(strFileName, FileMode.Open,
                                             FileAccess.Read, FileShare.Read);
    
                try
                {
                    lstEmployees = (List<Employee>)(bfEmployees.Deserialize(fsEmployees));
    
                    // Using the total number of records, display each in the list view
                    foreach (Employee empl1 in lstEmployees)
                    {
                        ListViewItem lviEmployee = new ListViewItem(empl1.EmployeeNumber);
    
                        lviEmployee.SubItems.Add(empl1.FirstName);
                        lviEmployee.SubItems.Add(empl1.LastName);
                        lviEmployee.SubItems.Add(empl1.Title);
                        lviEmployee.SubItems.Add(empl1.Manager.ToString());
                        lviEmployee.SubItems.Add(empl1.HourlySalary.ToString("F"));
                        lviEmployee.SubItems.Add(empl1.Username);
                        lviEmployee.SubItems.Add(empl1.Password);
    
                        lvwEmployees.Items.Add(lviEmployee);
                    }
                }
                finally
                {
                    fsEmployees.Close();
                }
            }
        }
    
        private void btnCloseClicked(object sender, EventArgs e)
        {
            Close();
        }
    }
  57. In the Solution Explorer, double-click the Employees.cs
     
    Employees
  58. To execute, press F5
  59. Click Employees
  60. Create a few records (let the application generate employees numbers)
  61. Close the employees table
  62. Click Create Store Item
  63. Create a few records (let the application generate the items numbers)
  64. Close the Create Store Item form
  65. Click the Store Inventory button
    Fun Department Store - Store Items
  66. Close the
  67. Store Inventory form
  68. Close the Switchboard form

Introduction to Implementing Authentication

To implement our authentication, we will create a C# application. Normally, you can use Microsoft Visual C# 2010 Express but we will use Microsoft Visual Studio 2010 Professional. To establish a connection to the Microsoft Access database, we will use the .NET Framework.

As always, you can first create the application and then take care of authentication later.

 
 
 

Implementing Authentication

There is always more than one way to solve a problem in logic and in  math. When it comes to an application also, you have many options:

  • You can create the first form of your application as the log in dialog box. In this case, if the employee successfully logs, then the actual application would display
  • You can add the code to call a log in dialog box to the first form. If the employee successfully logs in, then the rest of the application would show

In all cases, you must decide when and how the employee would log in and what to do in case of successful or unsuccessful log in.

Practical LearningPractical Learning: Implementing Authentication

  1. To create a file, on the main menu, click Project -> Add New Item...
  2. In the middle list, click Code File
  3. Set the Name to Authenticator
  4. Click Add
  5. In the empty document, type the following:
    using System;
    using System.Data;
    using System.Drawing;
    using System.Windows.Forms;
    using System.ComponentModel;
    
    public class Authenticator : Form
    {
        private Label lblUsername;
        public TextBox txtUsername;
        private Label lblPassword;
        public TextBox txtPassword;
        private Button btnOK;
        private Button btnCancel;
    
        public Authenticator()
        {
            InitializeComponent();
        }
    
        private void InitializeComponent()
        {
            lblUsername = new Label();
            txtUsername = new TextBox();
            txtPassword = new TextBox();
            lblPassword = new Label();
            btnOK = new Button();
            btnCancel = new Button();
    
            this.SuspendLayout();
    
            lblUsername.AutoSize = true;
            lblUsername.Location = new Point(12, 19);
            lblUsername.Size = new Size(58, 13);
            lblUsername.TabIndex = 0;
            lblUsername.Text = "Username:";
    
            txtUsername.Location = new Point(87, 16);
            txtUsername.Size = new Size(100, 20);
            txtUsername.TabIndex = 1;
    
            lblPassword.AutoSize = true;
            lblPassword.Location = new Point(12, 45);
            lblPassword.Size = new Size(56, 13);
            lblPassword.TabIndex = 2;
            lblPassword.Text = "Password:";
    
            txtPassword.Location = new Point(87, 42);
            txtPassword.PasswordChar = '*';
            txtPassword.Size = new Size(100, 20);
            txtPassword.TabIndex = 3;
    
            btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
            btnOK.Location = new Point(31, 78);
            btnOK.Size = new Size(75, 23);
            btnOK.TabIndex = 4;
            btnOK.Text = "OK";
            btnOK.UseVisualStyleBackColor = true;
    
            btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            btnCancel.Location = new Point(112, 78);
            btnCancel.Size = new Size(75, 23);
            btnCancel.TabIndex = 5;
            btnCancel.Text = "Cancel";
            btnCancel.UseVisualStyleBackColor = true;
    
            Controls.Add(lblUsername);
            Controls.Add(txtUsername);
            Controls.Add(lblPassword);
            Controls.Add(txtPassword);
            Controls.Add(btnOK);
            Controls.Add(btnCancel);
    
            AcceptButton = btnOK;
            CancelButton = btnCancel;
            ClientSize = new Size(206, 115);
            FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            MaximizeBox = false;
            MinimizeBox = false;
            ShowInTaskbar = false;
            StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            Text = "Fun Department Store - Log In";
            ResumeLayout(false);
        }
    }
  6. In the Solution Explorer, double-click Authenticator.cs
     
    Fun Department Store - Log In Dialog Box
  7. Display the Switchboard.cs file
  8. Implement the LogInToTheApplication() method and change the Load event as follows:
    private void LogInToTheApplication()
    {
        FileStream fsEmployees = null;
        DateTime dtArrivalDate = DateTime.Today;
        bool usernamePasswordMatch = false;
        bool currentEmployeeIsManager = false;
        Authenticator dlgLogIn = new Authenticator();
        string strPasswordFromDialogBox = "", strPasswordFromDatabase = "";
        string strUsernameFromDialogBox = "", strUsernameFromDatabase = "";
        List<Employee> lstEmployees = new List<Employee>();
        BinaryFormatter bfEmployees = new BinaryFormatter();
        string strFileName = @"\\Expression\\Fun Department Store\\Employees.fds";
    
        // Display the Autheticator dialog box.
        // If the user clicks Cancel, simply close the application
        if (dlgLogIn.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            Close();
        else // If the user clicks OK
        {
            // If the employee doesn't enter a username, display a message box...
            if (dlgLogIn.txtUsername.Text == "")
            {
                MessageBox.Show("You must enter a user name.",
                                "Fun Department Store",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                // ... and close the application
                Close();
            }
    
            // If the employee doesn't enter a password, display a message box...
            if (dlgLogIn.txtPassword.Text == "")
            {
                MessageBox.Show("You must type a password.",
                                "Fun Department Store",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                // ... and close the application
                Close();
            }
    
            // Get the user name of the dialog box
            strUsernameFromDialogBox = dlgLogIn.txtUsername.Text;
            // Get the password of the dialog box
            strPasswordFromDialogBox = dlgLogIn.txtPassword.Text;
    
            if (File.Exists(strFileName))
            {
                fsEmployees = new FileStream(strFileName, FileMode.Open,
                                              FileAccess.Read, FileShare.Read);
    
                lstEmployees = (List<Employee>)(bfEmployees.Deserialize(fsEmployees));
    
                foreach (Employee empl in lstEmployees)
                {
                    // Get the managing status of the employee
                    currentEmployeeIsManager = empl.Manager;
                    // When you are on a record, get the username of the employee
                    strUsernameFromDatabase = empl.Username;
                    // and the password
                    strPasswordFromDatabase = empl.Password;
    
                    // Compare the current username to the username of the dialog box
                    // and the current password to the password of the dialog box.
                    // If they match, ...
                    if (strUsernameFromDatabase.Equals(strUsernameFromDialogBox) &&
                        strPasswordFromDatabase.Equals(strPasswordFromDialogBox))
                    {
                        usernamePasswordMatch = true;
    
                        // ... display the switchboard
                        break;
                    }
    
                    // If there is no match, continue to the next record, 
                    // up to the end of the table
                }
    
                // If there was a match for username/password, display the Switchboard
    
                // If there was no match for username/password, 
                // Let the employee know ...
                if (usernamePasswordMatch == false)
                {
                    MessageBox.Show("The username and password combination did " +
                                    "not match any of the employees",
                                    "Fun Department Store",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                    // ... and close the application
                    Close();
                }
            }
        }
    }
    
    private void SwitchboardLoaded(object sender, EventArgs e)
    {
        LogInToTheApplication();
    }
  9. To test the application, press F5
  10. When the dialog box comes up, click Cancel
  11. Execute the application again
  12. When the dialog box displays, type the user name as Pasquale and press Enter
  13. Read the message box and click OK
  14. Execute the application again
  15. When the dialog box displays, type the user name as opasquale and press Tab
  16. Type the password as L'Italiano and press Enter
     
    Message Box
  17. Read the message box and press Enter
  18. Execute the application again
  19. Type the username as mtownsend and press Tab
  20. Type the password as Password5 and pass Enter
  21. Read the message box and click OK
  22. Execute the application again
  23. In the username of the dialog box, type mtownsend and press Tab
  24. Type the password as Password5
  25. Click OK
  26. Click the Store Inventory button
  27. Close the forms

Contextual Access

We refer to contextual the ability to grant access or some operations to one or more objects of an application to one or more people. This may sound complicated but it really is not. Or the real difficulty lies, not in programming, but in logic and organization (design). One way to solve the problem would consist of making a list of objects in your application, another list of people in your organization, then specify who will have access to what and who would be denied access to what. This would work perfectly fine in a small organization and a small application that hardly changes, but this may not be practical in larger scenarios. Another solution consists of creating groups of people, adding people to those groups, and then deciding what group has access to what.

In this example, we will use a field of the Employees table to identify who can have access to the form used to create a new store item.

Practical LearningPractical Learning: Implementing Contextual Access

  1. On the Switchboard form, double-click Create Store Item
  2. Change the file as follows:
    using System;
    using System.IO;
    using System.Data;
    using System.Drawing;
    using System.Windows.Forms;
    using System.ComponentModel;
    using System.Collections.Generic;
    using System.Runtime.Serialization.Formatters.Binary;
    
    public class Switchboard : Form
    {
        private Button btnStoreInventory;
        private Button btnCreateStoreItem;
        private Button btnEmployees;
        private Button btnLogInUser;
        private Button btnClose;
    
        private bool employeeIsAManager;
    
        public Switchboard()
        {
            InitializeComponent();
        }
    
        private void InitializeComponent()
        {
            btnStoreInventory = new Button();
            btnCreateStoreItem = new Button();
            btnEmployees = new Button();
            btnLogInUser = new Button();
            btnClose = new Button();
    
            SuspendLayout();
    
            btnStoreInventory.Font = new Font("Georgia", 18F,
                FontStyle.Bold, GraphicsUnit.Point, 0);
            btnStoreInventory.Location = new Point(12, 12);
            btnStoreInventory.Size = new Size(227, 98);
            btnStoreInventory.TabIndex = 23;
            btnStoreInventory.Text = "View Store Inventory";
            btnStoreInventory.UseVisualStyleBackColor = true;
            btnStoreInventory.Click +=
                new System.EventHandler(btnStoreInventoryClicked);
    
            btnCreateStoreItem.Font = new Font("Georgia", 18F,
                FontStyle.Bold, GraphicsUnit.Point, 0);
            btnCreateStoreItem.Location = new Point(255, 13);
            btnCreateStoreItem.Size = new Size(227, 98);
            btnCreateStoreItem.TabIndex = 25;
            btnCreateStoreItem.Text = "Create Store Item";
            btnCreateStoreItem.UseVisualStyleBackColor = true;
            btnCreateStoreItem.Click +=
                new System.EventHandler(btnCreateStoreItemClicked);
    
            btnEmployees.Font = new Font("Georgia", 18F,
                FontStyle.Bold, GraphicsUnit.Point, 0);
            btnEmployees.Location = new Point(12, 128);
            btnEmployees.Size = new Size(227, 98);
            btnEmployees.TabIndex = 27;
            btnEmployees.Text = "Employees";
            btnEmployees.UseVisualStyleBackColor = true;
            btnEmployees.Click +=
                new System.EventHandler(btnEmployeesClicked);
    
            btnLogInUser.Font = new Font("Georgia", 18F,
                FontStyle.Bold, GraphicsUnit.Point, 0);
            btnLogInUser.Location = new Point(255, 128);
            btnLogInUser.Size = new Size(227, 98);
            btnLogInUser.TabIndex = 26;
            btnLogInUser.Text = "Log in as a Different Employee";
            btnLogInUser.UseVisualStyleBackColor = true;
            btnLogInUser.Click +=
                new System.EventHandler(btnLogInUserClicked);
    
            btnClose.Font = new Font("Georgia", 18F,
                FontStyle.Bold, GraphicsUnit.Point, 0);
            btnClose.Location = new Point(11, 241);
            btnClose.Size = new Size(471, 67);
            btnClose.TabIndex = 24;
            btnClose.Text = "Close Application";
            btnClose.UseVisualStyleBackColor = true;
            btnClose.Click += new System.EventHandler(btnCloseClicked);
    
            ClientSize = new Size(494, 319);
            Controls.Add(btnEmployees);
            Controls.Add(btnLogInUser);
            Controls.Add(btnCreateStoreItem);
            Controls.Add(btnClose);
            Controls.Add(btnStoreInventory);
            Name = "Switchboard";
            StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            Load += new EventHandler(SwitchboardLoaded);
    
            Text = "Fun Department Store";
    
            ResumeLayout(false);
        }
    
        private void LogInToTheApplication()
        {
            FileStream fsEmployees = null;
            bool usernamePasswordMatch = false;
            bool currentEmployeeIsManager = false;
            DateTime dtArrivalDate = DateTime.Today;
            Authenticator dlgLogIn = new Authenticator();
            List lstEmployees = new List();
            BinaryFormatter bfEmployees = new BinaryFormatter();
            string strPasswordFromDialogBox = "", strPasswordFromDatabase = "";
            string strUsernameFromDialogBox = "", strUsernameFromDatabase = "";
            string strFileName = @"\\Expression\\Fun Department Store\\Employees.fds";
    
            // Display the Autheticator dialog box.
            // If the user clicks Cancel, simply close the application
            if (dlgLogIn.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
                Close();
            else // If the user clicks OK
            {
                // If the employee doesn't enter a username, display a message box...
                if (dlgLogIn.txtUsername.Text == "")
                {
                    MessageBox.Show("You must enter a user name.",
                                    "Fun Department Store",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                    // ... and close the application
                    Close();
                }
    
                // If the employee doesn't enter a password, display a message box...
                if (dlgLogIn.txtPassword.Text == "")
                {
                    MessageBox.Show("You must type a password.",
                                    "Fun Department Store",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                    // ... and close the application
                    Close();
                }
    
                // Get the user name of the dialog box
                strUsernameFromDialogBox = dlgLogIn.txtUsername.Text;
                // Get the password of the dialog box
                strPasswordFromDialogBox = dlgLogIn.txtPassword.Text;
    
                if (File.Exists(strFileName))
                {
                    fsEmployees = new FileStream(strFileName, FileMode.Open,
                                                  FileAccess.Read, FileShare.Read);
    
                    lstEmployees = (List)(bfEmployees.Deserialize(fsEmployees));
    
                    foreach (Employee empl in lstEmployees)
                    {
                        // Get the managing status of the employee
                        currentEmployeeIsManager = empl.Manager;
                        // When you are on a record, get the username of the employee
                        strUsernameFromDatabase = empl.Username;
                        // and the password
                        strPasswordFromDatabase = empl.Password;
    
                        // Compare the current username to the username of the dialog box
                        // and the current password to the password of the dialog box.
                        // If they match, ...
                        if (strUsernameFromDatabase.Equals(strUsernameFromDialogBox) &&
                            strPasswordFromDatabase.Equals(strPasswordFromDialogBox))
                        {
                            usernamePasswordMatch = true;
    
                            // Find out whether this employee is a manager.
                            // If so, make a reference...
                            if (currentEmployeeIsManager == true)
                                employeeIsAManager = true;
                            else
                                employeeIsAManager = false;
    
                            // ... display the switchboard
                            break;
                        }
    
                        // If there is no match, continue to the next record, 
                        // up to the end of the table
                    }
    
                    // If there was a match for username/password, display the Switchboard
    
                    // If there was no match for username/password, 
                    // Let the employee know ...
                    if (usernamePasswordMatch == false)
                    {
                        MessageBox.Show("The username and password combination did " +
                                        "not match any of the employees",
                                        "Fun Department Store",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                        // ... and close the application
                        Close();
                    }
                }
            }
        }
    
        private void SwitchboardLoaded(object sender, EventArgs e)
        {
            LogInToTheApplication();
        }
    
    
        private void btnStoreInventoryClicked(object sender, EventArgs e)
        {
            StoreInventory si = new StoreInventory();
            si.ShowDialog();
        }
    
        private void btnCreateStoreItemClicked(object sender, EventArgs e)
        {
            CreateStoreItem csi = new CreateStoreItem();
    
            // Using the global canCreateStoreItem variable, find out
            // whether the current user is a manager.
            // If the user is, then display the Create Store Item form
            if (employeeIsAManager == true)
                csi.ShowDialog();
            else // If the user is not, diaplay a message box
                MessageBox.Show("You are not authorized to create store items.",
                                "Fun Department Store",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    
        private void btnEmployeesClicked(object sender, EventArgs e)
        {
            Employees staff = new Employees();
    
            // If the user is a manager, enable the controls in the group box.
            if (employeeIsAManager == true)
                staff.grpNewEmployee.Enabled = true;
            else // Otherwise, disable them
                staff.grpNewEmployee.Enabled = false;
    
            staff.ShowDialog();
        }
    
        private void LogInAsADifferentEmployee()
        {
            FileStream fsEmployees = null;
            bool usernamePasswordMatch = false;
            bool currentEmployeeIsManager = false;
            Authenticator dlgLogIn = new Authenticator();
            List lstEmployees = new List();
            BinaryFormatter bfEmployees = new BinaryFormatter();
            string strPasswordFromDialogBox = "", strPasswordFromDatabase = "";
            string strUsernameFromDialogBox = "", strUsernameFromDatabase = "";
            string strFileName = @"\\Expression\\Fun Department Store\\Employees.fds";
    
            // Display the Autheticator dialog box.
            // If the user clicks Cancel, simply close the application
            if (dlgLogIn.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
                return;
            else // If the user clicks OK
            {
                // If the employee doesn't enter a username, display a message box...
                if (dlgLogIn.txtUsername.Text == "")
                    MessageBox.Show("You must enter a user name.",
                                    "Fun Department Store",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                // If the employee doesn't enter a password, display a message box...
                else if (dlgLogIn.txtPassword.Text == "")
                    MessageBox.Show("You must type a password.",
                                    "Fun Department Store",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                {
                    // Get the user name of the dialog box
                    strUsernameFromDialogBox = dlgLogIn.txtUsername.Text;
                    // Get the password of the dialog box
                    strPasswordFromDialogBox = dlgLogIn.txtPassword.Text;
    
                    if (File.Exists(strFileName))
                    {
                        fsEmployees = new FileStream(strFileName, FileMode.Open,
                                                      FileAccess.Read, FileShare.Read);
    
                        lstEmployees = (List)(bfEmployees.Deserialize(fsEmployees));
    
                        // Navigate to each record
                        foreach (Employee empl in lstEmployees)
                        {
                            // Get the managing status of the employee
                            currentEmployeeIsManager = empl.Manager;
                            // When you are on a record, get the username of the employee
                            strUsernameFromDatabase = empl.Username;
                            // and the password
                            strPasswordFromDatabase = empl.Password;
    
                            // Compare the current username to the username of the dialog box
                            // and the current password to the password of the dialog box.
                            // If they match, ...
                            if (strUsernameFromDatabase.Equals(strUsernameFromDialogBox) &&
                                strPasswordFromDatabase.Equals(strPasswordFromDialogBox))
                            {
                                usernamePasswordMatch = true;
    
                                // Find out whether this employee is a manager.
                                // If so, make a reference.
                                if (currentEmployeeIsManager == true)
                                    employeeIsAManager = true;
                                else
                                    employeeIsAManager = false;
    
                                // ... display the switchboard
                                break;
                            }
    
                            // If there is no match, continue to the next record, 
                            // up to the end of the table
                        }
    
                        // If there was a match for username/password, return to the Switchboard
    
                        // If there was no match for username/password, 
                        // Let the employee know ...
                        if (usernamePasswordMatch == false)
                        {
                            MessageBox.Show("The username and password combination did " +
                                            "not match any of the employees",
                                            "Fun Department Store",
                                        MessageBoxButtons.OK, MessageBoxIcon.Information);
    
                            return;
                        }
                    }
                }
            }
        }
    
        private void btnLogInUserClicked(object sender, EventArgs e)
        {
            LogInAsADifferentEmployee();
        }
    
        private void btnCloseClicked(object sender, EventArgs e)
        {
            Close();
        }
    }
    
    public class DepartmentStore
    {
        public static int Main()
        {
            Application.Run(new Switchboard());
            return 0;
        }
    }
    To test the application, press F5
  3. When the dialog box comes up, click Cancel. Notice that the application did not continue
  4. Execute the application again
  5. When the dialog box displays, type the user name as stanley and press Enter
  6. Type the password as Password5 and press Enter
  7. Read the message box and press Enter
  8. Execute the application again
  9. Type the username as mtownsend and press Tab
  10. Type the password as Password5 and pass Enter
  11. Click View Store Inventory
  12. Close the form
  13. Click Create Store Item
     
    Message Box
  14. Read the message and click OK
  15. Click Log in as a Different Employees
  16. In the username of the dialog box, type msamson and press Tab
  17. Type the password as password16 and press Enter
  18. Click Log in as a Different Employees
  19. In the username of the dialog box, type msamson and press Tab
  20. Type the password as Password6 and press Enter
  21. Click Create Store Item
  22. Enter some values for the record
     
    Create Store Item
  23. Click Create
     
    Create Store Item
  24. Read the message box and click OK
  25. Close the form
  26. Click Log in as a Different Employees
  27. Click Cancel
  28. Click Log in as a Different Employees
  29. In the username of the dialog box, type kdavids and press Tab
  30. Type the password as Password9 and press Enter
  31. Click View Store Inventory
    Fun Department Store - Store Items
  32. Close the form
  33. Cick Create Store Iteam
  34. Read the message and click OK
  35. Close the Switchboard form
 
 
   
 

Home Copyright © 2010-2016, FunctionX