Authentication & Authorization - Code

Startup.cs

using BlazorPurchaseOrders.Areas.Identity;
using BlazorPurchaseOrders.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Syncfusion.Blazor;

namespace BlazorPurchaseOrders
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            //Syncfusion support
            services.AddSyncfusionBlazor();
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddRoles <IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>();
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();
            services.AddDatabaseDeveloperPageExceptionFilter();
            services.AddSingleton<WeatherForecastService>();
            var sqlConnectionConfiguration = new SqlConnectionConfiguration(Configuration.GetConnectionString("SqlDBContext"));
            services.AddSingleton(sqlConnectionConfiguration);
            services.AddScoped<IPOHeaderService, POHeaderService>();
            services.AddScoped<IPOLineService, POLineService>();
            services.AddScoped<IProductService, ProductService>();
            services.AddScoped<ISupplierService, SupplierService>();
            services.AddScoped<ITaxService, TaxService>();

            //services.AddHttpContextAccessor();  //used for getting logged in user
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //Register Syncfusion license
            Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("**** Syncfusion Licence Key Goes Here *****");
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseMigrationsEndPoint();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });
        }

        
    }
}
<div class="top-row pl-4 navbar navbar-dark">
    <a class="navbar-brand" href="">Blazor Purchase Orders</a>
    <button class="navbar-toggler" @onclick="ToggleNavMenu">
        <span class="navbar-toggler-icon"></span>
    </button>
</div>

<div class="@NavMenuCssClass" @onclick="ToggleNavMenu">
    <ul class="nav flex-column">
        <li class="nav-item px-3">
            <NavLink class="nav-link" href="" Match="NavLinkMatch.All">
                <span class="oi oi-home" aria-hidden="true"></span> Purchase Orders
            </NavLink>
        </li>
        <AuthorizeView Roles="Admin">
            <li class="nav-item px-3">
                <NavLink class="nav-link" href="tax">
                    <span class="oi oi-list-rich" aria-hidden="true"></span> Tax Rates
                </NavLink>
            </li>
            <li class="nav-item px-3">
                <NavLink class="nav-link" href="supplier">
                      <span class="oi oi-list-rich" aria-hidden="true"></span> Suppliers
                  </NavLink>
            </li>
            <li class="nav-item px-3">
                <NavLink class="nav-link" href="product">
                    <span class="oi oi-list-rich" aria-hidden="true"></span> Products
                </NavLink>
            </li>
        </AuthorizeView>

</ul>
</div>

@code {
    private bool collapseNavMenu = true;

    private string NavMenuCssClass => collapseNavMenu ? "collapse" : null;

    private void ToggleNavMenu()
    {
        collapseNavMenu = !collapseNavMenu;
    }
}

TaxPage.razor

@page "/tax"
@using BlazorPurchaseOrders.Data
@inject ITaxService TaxService
@using Syncfusion.Blazor.Navigations

@attribute [Authorize(Roles = "Admin")]

<h3>Tax Rates</h3>
<br />

<SfGrid DataSource="@tax"
        Toolbar="@Toolbaritems">
    <GridColumns>
        <GridColumn Field="@nameof(Tax.TaxDescription)"
                    HeaderText="Description"
                    TextAlign="TextAlign.Left"
                    Width="60">
        </GridColumn>
        <GridColumn Field="@nameof(Tax.TaxRate)"
                    HeaderText="Rate %"
                    TextAlign="TextAlign.Right"
                    Format="p2"
                    Width="40">
        </GridColumn>
    </GridColumns>
    <GridEvents RowSelected="RowSelectHandler" OnToolbarClick="ToolbarClickHandler" TValue="Tax"></GridEvents>
</SfGrid>

<SfDialog @ref="DialogAddEditTax" IsModal="true" Width="500px" ShowCloseIcon="true" Visible="false">
    <DialogTemplates>
        <Header> @HeaderText </Header>
    </DialogTemplates>
    <EditForm Model="@addeditTax" OnValidSubmit="@TaxSave">
        <DataAnnotationsValidator />
        <div>
            <SfTextBox Enabled="true" Placeholder="Description"
                       FloatLabelType="@FloatLabelType.Always"
                       @bind-Value="addeditTax.TaxDescription"></SfTextBox>
            <ValidationMessage For="@(() => addeditTax.TaxDescription)" />
            <SfNumericTextBox Enabled="true" Placeholder="Tax Rate" Width="50"
                              Format="p2"
                              FloatLabelType="@FloatLabelType.Always"
                              @bind-Value="addeditTax.TaxRate"></SfNumericTextBox>

            <ValidationMessage For="@(() => addeditTax.TaxRate)" />
        </div>
        <br /><br />
        <div class="e-footer-content">
            <div class="button-container">
                <button type="submit" class="e-btn e-normal e-primary">Save</button>
                <button type="button" class="e-btn e-normal" @onclick="@CloseDialog">Cancel</button>
            </div>
        </div>
    </EditForm>
</SfDialog>

<SfDialog @ref="DialogDeleteTax" IsModal="true" Width="500px" ShowCloseIcon="true" Visible="false">
    <DialogTemplates>
        <Header> Confirm Delete </Header>
        <Content>
            <SfTextBox Enabled="false" Placeholder="Description"
                       FloatLabelType="@FloatLabelType.Always"
                       @bind-Value="addeditTax.TaxDescription"></SfTextBox>
            <SfNumericTextBox Enabled="false" Placeholder="Tax Rate" Width="50"
                              Format="p2"
                              FloatLabelType="@FloatLabelType.Always"
                              @bind-Value="addeditTax.TaxRate"></SfNumericTextBox>
            <br />
            <br />
            <span class="text-danger">Please confirm that you want to delete this record</span>
        </Content>
    </DialogTemplates>
    <DialogButtons>
        <DialogButton Content="Delete" IsPrimary="true" OnClick="@ConfirmDeleteYes" />
        <DialogButton Content="Cancel" IsPrimary="false" OnClick="@ConfirmDeleteNo" />
    </DialogButtons>
</SfDialog>

<WarningPage @ref="Warning" WarningHeaderMessage="@WarningHeaderMessage" WarningContentMessage="@WarningContentMessage" />

@code {

    IEnumerable<Tax> tax;
    private List<ItemModel> Toolbaritems = new List<ItemModel>();

    SfDialog DialogAddEditTax;
    Tax addeditTax = new Tax();
    string HeaderText = "";

    WarningPage Warning;
    string WarningHeaderMessage = "";
    string WarningContentMessage = "";

    public int SelectedTaxId { get; set; } = 0;

    SfDialog DialogDeleteTax;


    protected override async Task OnInitializedAsync()
    {
        //Populate the list of Tax objects from the Tax table.
        tax = await TaxService.TaxList();

        Toolbaritems.Add(new ItemModel() { Text = "Add", TooltipText = "Add a new Tax Rate", PrefixIcon = "e-add" });
        Toolbaritems.Add(new ItemModel() { Text = "Edit", TooltipText = "Edit selected Tax Rate", PrefixIcon = "e-edit" });
        Toolbaritems.Add(new ItemModel() { Text = "Delete", TooltipText = "Delete selected Tax Rate", PrefixIcon = "e-delete" });
    }

    public async Task ToolbarClickHandler(Syncfusion.Blazor.Navigations.ClickEventArgs args)
    {
        if (args.Item.Text == "Add")
        {
            //Code for adding goes here
            addeditTax = new Tax();             // Ensures a blank form when adding
            HeaderText = "Add Tax Rate";
            await this.DialogAddEditTax.Show();
        }
        if (args.Item.Text == "Edit")
        {
            //Code for editing goes here
            //Check that a Tax Rate has been selected
            if (SelectedTaxId == 0)
            {
                WarningHeaderMessage = "Warning!";
                WarningContentMessage = "Please select a Tax Rate from the grid.";
                Warning.OpenDialog();
            }
            else
            {
                //populate addeditTax (temporary data set used for the editing process)
                HeaderText = "Edit Tax Rate";
                addeditTax = await TaxService.Tax_GetOne(SelectedTaxId);
                await this.DialogAddEditTax.Show();
            }

        }
        if (args.Item.Text == "Delete")
        {
            //code for deleting goes here
            if (SelectedTaxId == 0)
            {
                WarningHeaderMessage = "Warning!";
                WarningContentMessage = "Please select a Tax Rate from the grid.";
                Warning.OpenDialog();
            }
            else
            {
                //populate addeditTax (temporary data set used for the editing process)
                HeaderText = "Delete Tax Rate";
                addeditTax = await TaxService.Tax_GetOne(SelectedTaxId);
                await this.DialogDeleteTax.Show();
            }
        }
    }

    protected async Task TaxSave()
    {
        if (addeditTax.TaxID == 0)
        {
            int Success = await TaxService.TaxInsert(addeditTax.TaxDescription, addeditTax.TaxRate);
            if (Success != 0)
            {
                //Tax Rate already exists
                WarningHeaderMessage = "Warning!";
                WarningContentMessage = "This Tax Description already exists; it cannot be added again.";
                Warning.OpenDialog();
                // Data is left in the dialog so the user can see the problem.
            }
            else
            {
                // Clears the dialog and is ready for another entry
                // User must specifically close or cancel the dialog
                addeditTax = new Tax();
            }
        }
        else
        {
            // Item is being edited
            int Success = await TaxService.TaxUpdate(addeditTax.TaxDescription, addeditTax.TaxRate, SelectedTaxId, addeditTax.TaxIsArchived);
            if (Success != 0)
            {
                //Tax Rate already exists
                WarningHeaderMessage = "Warning!";
                WarningContentMessage = "This Tax Description already exists; it cannot be added again.";
                Warning.OpenDialog();
            }
            else
            {
                await this.DialogAddEditTax.Hide();
                this.StateHasChanged();
                addeditTax = new Tax();
                SelectedTaxId = 0;
            }
        }

        //Always refresh datagrid
        tax = await TaxService.TaxList();
        StateHasChanged();
    }

    private async Task CloseDialog()
    {
        await this.DialogAddEditTax.Hide();
    }

    public void RowSelectHandler(RowSelectEventArgs<Tax> args)
    {
        //{args.Data} returns the current selected records.
        SelectedTaxId = args.Data.TaxID;
    }

    public async void ConfirmDeleteNo()
    {
        await DialogDeleteTax.Hide();
        SelectedTaxId = 0;
    }

    public async void ConfirmDeleteYes()
    {
        int Success = await TaxService.TaxUpdate(addeditTax.TaxDescription, addeditTax.TaxRate, SelectedTaxId, addeditTax.TaxIsArchived = true);
        if (Success != 0)
        {
            //Tax Rate already exists - THis should never happen when marking a record 'IsArchived'.
            WarningHeaderMessage = "Warning!";
            WarningContentMessage = "Unknown error has occurred - the record has not been deleted!";
            Warning.OpenDialog();
        }
        else
        {
            await this.DialogDeleteTax.Hide();
            tax = await TaxService.TaxList();
            this.StateHasChanged();
            addeditTax = new Tax();
            SelectedTaxId = 0;
        }
    }
}

SupplierPage.razor

@page "/supplier"
@using BlazorPurchaseOrders.Data
@inject ISupplierService SupplierService
@using Syncfusion.Blazor.Navigations

@attribute [Authorize(Roles = "Admin")]

<h3>Suppliers</h3>
<br />

<SfGrid DataSource="@supplier"
        Toolbar="@Toolbaritems"
        AllowResizing="true">
    <GridColumns>
        <GridColumn Field="@nameof(Supplier.SupplierName)"
                    HeaderText="Name"
                    TextAlign="TextAlign.Left"
                    Width="40">
        </GridColumn>
        <GridColumn Field="@nameof(Supplier.CombinedAddress)"
                    HeaderText="Address"
                    TextAlign="TextAlign.Left"
                    Width="60">
        </GridColumn>
        <GridColumn Field="@nameof(Supplier.SupplierEmail)"
                    HeaderText="Email"
                    TextAlign="TextAlign.Left"
                    Width="40">
        </GridColumn>
    </GridColumns>
    <GridEvents RowSelected="RowSelectHandler" OnToolbarClick="ToolbarClickHandler" TValue="Supplier"></GridEvents>
</SfGrid>

<SfDialog @ref="DialogAddEditSupplier" IsModal="true" Width="500px" ShowCloseIcon="true" Visible="false">
    <DialogTemplates>
        <Header> @HeaderText </Header>
    </DialogTemplates>
    <EditForm Model="@addeditSupplier" OnValidSubmit="@SupplierSave">
        <DataAnnotationsValidator />
        <div>
            <SfTextBox Enabled="true" Placeholder="Supplier Name"
                       FloatLabelType="@FloatLabelType.Auto"
                       @bind-Value="addeditSupplier.SupplierName"></SfTextBox>
            <ValidationMessage For="@(() => addeditSupplier.SupplierName)" />
            <SfTextBox Enabled="true" Placeholder="Address"
                       FloatLabelType="@FloatLabelType.Auto"
                       @bind-Value="addeditSupplier.SupplierAddress1"></SfTextBox>
            <ValidationMessage For="@(() => addeditSupplier.SupplierAddress1)" />
            <SfTextBox Enabled="true" Placeholder=""
                       FloatLabelType="@FloatLabelType.Never"
                       @bind-Value="addeditSupplier.SupplierAddress2"></SfTextBox>
            <ValidationMessage For="@(() => addeditSupplier.SupplierAddress2)" />
            <SfTextBox Enabled="true" Placeholder=""
                       FloatLabelType="@FloatLabelType.Never"
                       @bind-Value="addeditSupplier.SupplierAddress3"></SfTextBox>
            <ValidationMessage For="@(() => addeditSupplier.SupplierAddress3)" />
            <SfTextBox Enabled="true" Placeholder="Post Code"
                       FloatLabelType="@FloatLabelType.Auto"
                       CssClass="ToUpperCase"
                       @bind-Value="addeditSupplier.SupplierPostCode"></SfTextBox>
            <ValidationMessage For="@(() => addeditSupplier.SupplierPostCode)" />
            <SfTextBox Enabled="true" Placeholder="Email"
                       FloatLabelType="@FloatLabelType.Auto"
                       @bind-Value="addeditSupplier.SupplierEmail"></SfTextBox>
            <ValidationMessage For="@(() => addeditSupplier.SupplierEmail)" />
        </div>
        <br /><br />
        <div class="e-footer-content">
            <div class="button-container">
                <button type="submit" class="e-btn e-normal e-primary">Save</button>
                <button type="button" class="e-btn e-normal" @onclick="@CloseDialog">Cancel</button>
            </div>
        </div>
    </EditForm>
</SfDialog>

<SfDialog @ref="DialogDeleteSupplier" IsModal="true" Width="500px" ShowCloseIcon="true" Visible="false">
    <DialogTemplates>
        <Header> Confirm Delete </Header>
        <Content>
            <SfTextBox Enabled="false" Placeholder="Supplier Name"
                       FloatLabelType="@FloatLabelType.Auto"
                       @bind-Value="addeditSupplier.SupplierName"></SfTextBox>
            <SfTextBox Enabled="false" Placeholder="Address"
                       FloatLabelType="@FloatLabelType.Auto"
                       @bind-Value="addeditSupplier.SupplierAddress1"></SfTextBox>
            <SfTextBox Enabled="false" Placeholder="Address"
                       FloatLabelType="@FloatLabelType.Never"
                       @bind-Value="addeditSupplier.SupplierAddress2"></SfTextBox>
            <SfTextBox Enabled="false" Placeholder="Address"
                       FloatLabelType="@FloatLabelType.Never"
                       @bind-Value="addeditSupplier.SupplierAddress3"></SfTextBox>
            <SfTextBox Enabled="false" Placeholder="Post Code"
                       FloatLabelType="@FloatLabelType.Auto"
                       @bind-Value="addeditSupplier.SupplierAddress3"></SfTextBox>
            <SfTextBox Enabled="false" Placeholder="Email"
                       FloatLabelType="@FloatLabelType.Auto"
                       @bind-Value="addeditSupplier.SupplierEmail"></SfTextBox>
            <br />
            <br />
            <span class="text-danger">Please confirm that you want to delete this record</span>
        </Content>
    </DialogTemplates>
    <DialogButtons>
        <DialogButton Content="Delete" IsPrimary="true" OnClick="@ConfirmDeleteYes" />
        <DialogButton Content="Cancel" IsPrimary="false" OnClick="@ConfirmDeleteNo" />
    </DialogButtons>
</SfDialog>

<WarningPage @ref="Warning" WarningHeaderMessage="@WarningHeaderMessage" WarningContentMessage="@WarningContentMessage" />

<style>
    .e-control-wrapper.ToUpperCase .e-textbox {
        text-transform: uppercase;
    }
</style>

@code {

    IEnumerable<Supplier> supplier;
    private List<ItemModel> Toolbaritems = new List<ItemModel>();

    SfDialog DialogAddEditSupplier;
    Supplier addeditSupplier = new Supplier();
    string HeaderText = "";

    WarningPage Warning;
    string WarningHeaderMessage = "";
    string WarningContentMessage = "";

    public int SelectedSupplierId { get; set; } = 0;

    SfDialog DialogDeleteSupplier;


    protected override async Task OnInitializedAsync()
    {
        //Populate the list of Supplier objects from the Supplier table.
        supplier = await SupplierService.SupplierList();

        Toolbaritems.Add(new ItemModel() { Text = "Add", TooltipText = "Add a new Supplier", PrefixIcon = "e-add" });
        Toolbaritems.Add(new ItemModel() { Text = "Edit", TooltipText = "Edit selected Supplier", PrefixIcon = "e-edit" });
        Toolbaritems.Add(new ItemModel() { Text = "Delete", TooltipText = "Delete selected Supplier", PrefixIcon = "e-delete" });
    }

    public async Task ToolbarClickHandler(Syncfusion.Blazor.Navigations.ClickEventArgs args)
    {
        if (args.Item.Text == "Add")
        {
            //Code for adding goes here
            addeditSupplier = new Supplier();             // Ensures a blank form when adding
            HeaderText = "Add Supplier";
            await this.DialogAddEditSupplier.Show();
        }
        if (args.Item.Text == "Edit")
        {
            //Code for editing goes here
            //Check that a Supplier Rate has been selected
            if (SelectedSupplierId == 0)
            {
                WarningHeaderMessage = "Warning!";
                WarningContentMessage = "Please select a Supplier from the grid.";
                Warning.OpenDialog();
            }
            else
            {
                //populate addeditSupplier (temporary data set used for the editing process)
                HeaderText = "Edit Supplier";
                addeditSupplier = await SupplierService.Supplier_GetOne(SelectedSupplierId);
                await this.DialogAddEditSupplier.Show();
            }

        }
        if (args.Item.Text == "Delete")
        {
            //code for deleting goes here
            if (SelectedSupplierId == 0)
            {
                WarningHeaderMessage = "Warning!";
                WarningContentMessage = "Please select a Supplier from the grid.";
                Warning.OpenDialog();
            }
            else
            {
                //populate addeditSupplier (temporary data set used for the editing process)
                HeaderText = "Delete Supplier";
                addeditSupplier = await SupplierService.Supplier_GetOne(SelectedSupplierId);
                await this.DialogDeleteSupplier.Show();
            }
        }
    }

    protected async Task SupplierSave()
    {
        if (addeditSupplier.SupplierID == 0)
        {
            int Success = await SupplierService.SupplierInsert(addeditSupplier.SupplierName,
                addeditSupplier.SupplierAddress1,
                addeditSupplier.SupplierAddress2,
                addeditSupplier.SupplierAddress3,
                addeditSupplier.SupplierPostCode,
                addeditSupplier.SupplierEmail
                );
            if (Success != 0)
            {
                //Supplier Rate already exists
                WarningHeaderMessage = "Warning!";
                WarningContentMessage = "This Supplier Description already exists; it cannot be added again.";
                Warning.OpenDialog();
                // Data is left in the dialog so the user can see the problem.
            }
            else
            {
                // Clears the dialog and is ready for another entry
                // User must specifically close or cancel the dialog
                addeditSupplier = new Supplier();
            }
        }
        else
        {
            // Item is being edited
            int Success = await SupplierService.SupplierUpdate(
                SelectedSupplierId,
                addeditSupplier.SupplierName,
                addeditSupplier.SupplierAddress1,
                addeditSupplier.SupplierAddress2,
                addeditSupplier.SupplierAddress3,
                addeditSupplier.SupplierPostCode,
                addeditSupplier.SupplierEmail,
                addeditSupplier.SupplierIsArchived);
            if (Success != 0)
            {
                //Supplier Rate already exists
                WarningHeaderMessage = "Warning!";
                WarningContentMessage = "This Supplier already exists; it cannot be added again.";
                Warning.OpenDialog();
            }
            else
            {
                await this.DialogAddEditSupplier.Hide();
                this.StateHasChanged();
                addeditSupplier = new Supplier();
                SelectedSupplierId = 0;
            }
        }

        //Always refresh datagrid
        supplier = await SupplierService.SupplierList();
        StateHasChanged();
    }

    private async Task CloseDialog()
    {
        await this.DialogAddEditSupplier.Hide();
    }

    public void RowSelectHandler(RowSelectEventArgs<Supplier> args)
    {
        //{args.Data} returns the current selected records.
        SelectedSupplierId = args.Data.SupplierID;
    }

    public async void ConfirmDeleteNo()
    {
        await DialogDeleteSupplier.Hide();
        SelectedSupplierId = 0;
    }

    public async void ConfirmDeleteYes()
    {
        int Success = await SupplierService.SupplierUpdate(

            SelectedSupplierId,
                addeditSupplier.SupplierName,
                addeditSupplier.SupplierAddress1,
                addeditSupplier.SupplierAddress2,
                addeditSupplier.SupplierAddress3,
                addeditSupplier.SupplierPostCode,
                addeditSupplier.SupplierEmail,
                addeditSupplier.SupplierIsArchived = true);
        if (Success != 0)
        {
            //Supplier Rate already exists - THis should never happen when marking a record 'IsArchived'.
            WarningHeaderMessage = "Warning!";
            WarningContentMessage = "Unknown error has occurred - the record has not been deleted!";
            Warning.OpenDialog();
        }
        else
        {
            await this.DialogDeleteSupplier.Hide();
            supplier = await SupplierService.SupplierList();
            this.StateHasChanged();
            addeditSupplier = new Supplier();
            SelectedSupplierId = 0;
        }
    }
}

ProductPage.razor

@page "/product"
@using BlazorPurchaseOrders.Data
@inject IProductService ProductService
@inject ISupplierService SupplierService

@attribute [Authorize(Roles = "Admin")]


<h3>Products</h3>
<br />

<SfGrid DataSource="@product"
        Toolbar="@Toolbaritems"
        AllowResizing="true">
    <GridColumns>
        <GridColumn Field="@nameof(Product.ProductCode)"
                    HeaderText="Code"
                    TextAlign="TextAlign.Left"
                    Width="40">
        </GridColumn>
        <GridColumn Field="@nameof(Product.ProductDescription)"
                    HeaderText="Description"
                    TextAlign="TextAlign.Left"
                    Width="60">
        </GridColumn>
        <GridColumn Field="@nameof(Product.ProductUnitPrice)"
                    HeaderText="Unit Price"
                    TextAlign="TextAlign.Right"
                    Format="C2"
                    Width="40">
        </GridColumn>
        <GridColumn Field="@nameof(Product.SupplierName)"
                    HeaderText="Supplier"
                    TextAlign="TextAlign.Left"
                    Width="60">
        </GridColumn>
    </GridColumns>
    <GridEvents RowSelected="RowSelectHandler" OnToolbarClick="ToolbarClickHandler" TValue="Product"></GridEvents>
</SfGrid>

<SfDialog @ref="DialogAddEditProduct" IsModal="true" Width="500px" ShowCloseIcon="true" Visible="false">
    <DialogTemplates>
        <Header> @HeaderText </Header>
    </DialogTemplates>
    <EditForm Model="@addeditProduct" OnValidSubmit="@ProductSave">
        <DataAnnotationsValidator />
        <div>
            <SfTextBox Enabled="true" Placeholder="Product Code"
                       FloatLabelType="@FloatLabelType.Auto"
                       @bind-Value="addeditProduct.ProductCode"></SfTextBox>
            <ValidationMessage For="@(() => addeditProduct.ProductCode)" />

            <SfTextBox Enabled="true" Placeholder="Description"
                       FloatLabelType="@FloatLabelType.Auto"
                       @bind-Value="addeditProduct.ProductDescription"></SfTextBox>
            <ValidationMessage For="@(() => addeditProduct.ProductDescription)" />

            <SfNumericTextBox Enabled="true" Placeholder="Unit Price"
                              FloatLabelType="@FloatLabelType.Auto"
                              ShowSpinButton="false"
                              Format="c2"
                              Decimals="2"
                              ValidateDecimalOnType="true"
                              @bind-Value="addeditProduct.ProductUnitPrice"></SfNumericTextBox>

            <SfDropDownList DataSource="@supplier"
                            TItem="Supplier"
                            TValue="int"
                            Text="SupplierID"
                            @bind-Value="addeditProduct.ProductSupplierID"
                            FloatLabelType="@FloatLabelType.Auto"
                            Placeholder="Select a Supplier"
                            Enabled="true">
                <DropDownListFieldSettings Text="SupplierName" Value="SupplierID"></DropDownListFieldSettings>
            </SfDropDownList>
        </div>
        <br /><br />
        <div class="e-footer-content">
            <div class="button-container">
                <button type="submit" class="e-btn e-normal e-primary">Save</button>
                <button type="button" class="e-btn e-normal" @onclick="@CloseDialog">Cancel</button>
            </div>
        </div>
    </EditForm>
</SfDialog>



<SfDialog @ref="DialogDeleteProduct" IsModal="true" Width="500px" ShowCloseIcon="true" Visible="false">
    <DialogTemplates>
        <Header> Confirm Delete </Header>
        <Content>
            <SfTextBox Enabled="false" Placeholder="Product Code"
                       FloatLabelType="@FloatLabelType.Auto"
                       @bind-Value="addeditProduct.ProductCode"></SfTextBox>
            <SfTextBox Enabled="false" Placeholder="Description"
                       FloatLabelType="@FloatLabelType.Auto"
                       @bind-Value="addeditProduct.ProductDescription"></SfTextBox>
            <SfNumericTextBox Enabled="false" Placeholder="Unit Price"
                              FloatLabelType="@FloatLabelType.Auto"
                              @bind-Value="addeditProduct.ProductUnitPrice"></SfNumericTextBox>
            <SfDropDownList DataSource="@supplier"
                            TItem="Supplier"
                            TValue="int"
                            Text="SupplierID"
                            @bind-Value="addeditProduct.ProductSupplierID"
                            FloatLabelType="@FloatLabelType.Auto"
                            Placeholder="Select a Supplier"
                            Enabled="false">
                <DropDownListFieldSettings Text="SupplierName" Value="SupplierID"></DropDownListFieldSettings>
            </SfDropDownList>
            <br />
            <br />
            <span class="text-danger">Please confirm that you want to delete this record</span>
        </Content>
    </DialogTemplates>
    <DialogButtons>
        <DialogButton Content="Delete" IsPrimary="true" OnClick="@ConfirmDeleteYes" />
        <DialogButton Content="Cancel" IsPrimary="false" OnClick="@ConfirmDeleteNo" />
    </DialogButtons>
</SfDialog>

<WarningPage @ref="Warning" WarningHeaderMessage="@WarningHeaderMessage" WarningContentMessage="@WarningContentMessage" />

<style>
    .e-control-wrapper.ToUpperCase .e-textbox {
        text-transform: uppercase;
    }
</style>

@code {

    IEnumerable<Product> product;
    IEnumerable<Supplier> supplier;
    private List<ItemModel> Toolbaritems = new List<ItemModel>();

    SfDialog DialogAddEditProduct;
    Product addeditProduct = new Product();
    string HeaderText = "";

    WarningPage Warning;
    string WarningHeaderMessage = "";
    string WarningContentMessage = "";

    public int SelectedProductId { get; set; } = 0;

    SfDialog DialogDeleteProduct;


    protected override async Task OnInitializedAsync()
    {
        //Populate the list of Product objects from the Product table.
        product = await ProductService.ProductList();
        supplier = await SupplierService.SupplierList();

        Toolbaritems.Add(new ItemModel() { Text = "Add", TooltipText = "Add a new Product", PrefixIcon = "e-add" });
        Toolbaritems.Add(new ItemModel() { Text = "Edit", TooltipText = "Edit selected Product", PrefixIcon = "e-edit" });
        Toolbaritems.Add(new ItemModel() { Text = "Delete", TooltipText = "Delete selected Product", PrefixIcon = "e-delete" });
    }

    public async Task ToolbarClickHandler(Syncfusion.Blazor.Navigations.ClickEventArgs args)
    {
        if (args.Item.Text == "Add")
        {
            //Code for adding goes here
            addeditProduct = new Product();             // Ensures a blank form when adding
            HeaderText = "Add Product";
            await this.DialogAddEditProduct.Show();
        }
        if (args.Item.Text == "Edit")
        {
            //Code for editing goes here
            //Check that a Product Rate has been selected
            if (SelectedProductId == 0)
            {
                WarningHeaderMessage = "Warning!";
                WarningContentMessage = "Please select a Product from the grid.";
                Warning.OpenDialog();
            }
            else
            {
                //populate addeditProduct (temporary data set used for the editing process)
                HeaderText = "Edit Product";
                addeditProduct = await ProductService.Product_GetOne(SelectedProductId);
                await this.DialogAddEditProduct.Show();
            }

        }
        if (args.Item.Text == "Delete")
        {
            //code for deleting goes here
            if (SelectedProductId == 0)
            {
                WarningHeaderMessage = "Warning!";
                WarningContentMessage = "Please select a Product from the grid.";
                Warning.OpenDialog();
            }
            else
            {
                //populate addeditProduct (temporary data set used for the editing process)
                HeaderText = "Delete Product";
                addeditProduct = await ProductService.Product_GetOne(SelectedProductId);
                await this.DialogDeleteProduct.Show();
            }
        }
    }

    protected async Task ProductSave()
    {
        if (addeditProduct.ProductID == 0)
        {
            int Success = await ProductService.ProductInsert(
                addeditProduct.ProductCode,
                addeditProduct.ProductDescription,
                addeditProduct.ProductUnitPrice,
                addeditProduct.ProductSupplierID
                );
            if (Success != 0)
            {
                //Product Rate already exists
                WarningHeaderMessage = "Warning!";
                WarningContentMessage = "This Product Description already exists; it cannot be added again.";
                Warning.OpenDialog();
                // Data is left in the dialog so the user can see the problem.
            }
            else
            {
                // Clears the dialog and is ready for another entry
                // User must specifically close or cancel the dialog
                addeditProduct = new Product();
            }
        }
        else
        {
            // Item is being edited
            int Success = await ProductService.ProductUpdate(
                SelectedProductId,
                addeditProduct.ProductCode,
                addeditProduct.ProductDescription,
                addeditProduct.ProductUnitPrice,
                addeditProduct.ProductSupplierID,
                addeditProduct.ProductIsArchived);
            if (Success != 0)
            {
                //Product Rate already exists
                WarningHeaderMessage = "Warning!";
                WarningContentMessage = "This Product already exists; it cannot be added again.";
                Warning.OpenDialog();
            }
            else
            {
                await this.DialogAddEditProduct.Hide();
                this.StateHasChanged();
                addeditProduct = new Product();
                SelectedProductId = 0;
            }
        }

        //Always refresh datagrid
        product = await ProductService.ProductList();
        StateHasChanged();
    }

    private async Task CloseDialog()
    {
        await this.DialogAddEditProduct.Hide();
    }

    public void RowSelectHandler(RowSelectEventArgs<Product> args)
    {
        //{args.Data} returns the current selected records.
        SelectedProductId = args.Data.ProductID;
    }

    public async void ConfirmDeleteNo()
    {
        await DialogDeleteProduct.Hide();
        SelectedProductId = 0;
    }

    public async void ConfirmDeleteYes()
    {
        int Success = await ProductService.ProductUpdate(
            SelectedProductId,
            addeditProduct.ProductCode,
            addeditProduct.ProductDescription,
            addeditProduct.ProductUnitPrice,
            addeditProduct.ProductSupplierID,
            addeditProduct.ProductIsArchived = true);
        if (Success != 0)
        {
            //Product Rate already exists - THis should never happen when marking a record 'IsArchived'.
            WarningHeaderMessage = "Warning!";
            WarningContentMessage = "Unknown error has occurred - the record has not been deleted!";
            Warning.OpenDialog();
        }
        else
        {
            await this.DialogDeleteProduct.Hide();
            product = await ProductService.ProductList();
            this.StateHasChanged();
            addeditProduct = new Product();
            SelectedProductId = 0;
        }
    }
}

_Imports.cs

@using System.Net.Http
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.AspNetCore.Components.Web.Virtualization
@using Microsoft.JSInterop
@using BlazorPurchaseOrders
@using BlazorPurchaseOrders.Shared
@using Syncfusion.Blazor
@using Syncfusion.Blazor.Inputs
@using Syncfusion.Blazor.Popups
@using Syncfusion.Blazor.Data
@using Syncfusion.Blazor.DropDowns
@using Syncfusion.Blazor.Layouts
@using Syncfusion.Blazor.Calendars
@using Syncfusion.Blazor.Navigations
@using Syncfusion.Blazor.Lists
@using Syncfusion.Blazor.Grids
@using Syncfusion.Blazor.Buttons
@using Syncfusion.Blazor.Notifications
@attribute [Microsoft.AspNetCore.Authorization.Authorize]

Index.razor

@page "/"
@using BlazorPurchaseOrders.Data

@inject IPOHeaderService POHeaderService
@inject NavigationManager NavigationManager
@inject IJSRuntime IJS

@attribute [Microsoft.AspNetCore.Authorization.AllowAnonymous]

<div class="col-sm-12">
    <AuthorizeView>
        <NotAuthorized>
            <h5>Please Log in</h5>
            <h6>or</h6>
            <h5>Register to use Blazor Purchase Orders</h5>
        </NotAuthorized>
        <Authorized>
            <h3>Purchase Orders</h3>
            <br />
            <SfGrid DataSource="@poheader"
                    Toolbar="Toolbaritems">
                <GridEvents RowSelected="RowSelectHandler" OnToolbarClick="ToolbarClickHandler" TValue="POHeader"></GridEvents>
                <GridColumns>
                    <GridColumn Field="@nameof(POHeader.POHeaderOrderNumber)"
                                HeaderText="No"
                                TextAlign="@TextAlign.Left"
                                Width="10">
                    </GridColumn>
                    <GridColumn Field="@nameof(POHeader.POHeaderOrderDate)"
                                HeaderText="Date"
                                Format="d"
                                Type="ColumnType.Date"
                                TextAlign="@TextAlign.Center"
                                Width="15">
                    </GridColumn>
                    <GridColumn Field="@nameof(POHeader.SupplierName)"
                                HeaderText="Supplier"
                                TextAlign="@TextAlign.Left"
                                Width="40">
                    </GridColumn>
                    <GridColumn Field="@nameof(POHeader.TotalOrderValue)"
                                HeaderText="Value"
                                TextAlign="@TextAlign.Right"
                                Format="C2"
                                Width="20">
                    </GridColumn>
                    <GridColumn Field="@nameof(POHeader.POHeaderRequestedBy)"
                                HeaderText="Requested by"
                                TextAlign="@TextAlign.Left"
                                Width="40">
                    </GridColumn>
                </GridColumns>
            </SfGrid>

            <WarningPage @ref="Warning" WarningHeaderMessage="@WarningHeaderMessage" WarningContentMessage="@WarningContentMessage" />

            <ConfirmPage @ref="ConfirmOrderDelete" ConfirmHeaderMessage="@ConfirmHeaderMessage" ConfirmContentMessage="@ConfirmContentMessage" ConfirmationChanged="ConfirmOrderArchive" />

        </Authorized>
    </AuthorizeView>
</div>

@code {

    // Create an empty list, named poheader, of empty POHeader objects.
    IEnumerable<POHeader> poheader;
    POHeader orderHeader = new POHeader();

    private List<ItemModel> Toolbaritems = new List<ItemModel>();

    int POHeaderID = 0;

    private int selectedPOHeaderID { get; set; } = 0;

    WarningPage Warning;
    string WarningHeaderMessage = "";
    string WarningContentMessage = "";

    ConfirmPage ConfirmOrderDelete;
    string ConfirmHeaderMessage = "";
    string ConfirmContentMessage = "";
    public bool ConfirmationChanged { get; set; } = false;

    protected override async Task OnInitializedAsync()
    {
        //Populate the list of orders objects from the Purchase Order Header table.
        poheader = await POHeaderService.POHeaderList();

        Toolbaritems.Add(new ItemModel() { Text = "Add", TooltipText = "Add a new order", PrefixIcon = "e-add" });
        Toolbaritems.Add(new ItemModel() { Text = "Edit", TooltipText = "Edit selected order", PrefixIcon = "e-edit" });
        Toolbaritems.Add(new ItemModel() { Text = "Delete", TooltipText = "Delete selected order", PrefixIcon = "e-delete" });
        Toolbaritems.Add(new ItemModel() { Text = "Preview", TooltipText = "Preview selected order", PrefixIcon = "e-print" });
    }


    public async Task ToolbarClickHandler(Syncfusion.Blazor.Navigations.ClickEventArgs args)
    {
        if (args.Item.Text == "Add")
        {
            //Code for adding goes here
            POHeaderID = 0;
            NavigationManager.NavigateTo($"/purchaseorder/{POHeaderID}");
        }

        if (args.Item.Text == "Edit")
        {
            //Code for editing - Check that an Order has been selected from the grid
            if (selectedPOHeaderID == 0)
            {
                WarningHeaderMessage = "Warning!";
                WarningContentMessage = "Please select an Order from the grid.";
                Warning.OpenDialog();
            }
            else
            {
                NavigationManager.NavigateTo($"/purchaseorder/{selectedPOHeaderID}");
            }
        }

        if (args.Item.Text == "Delete")
        {
            //Code for deleting
            if (selectedPOHeaderID == 0)    //Check that an order has been selected
            {
                WarningHeaderMessage = "Warning!";
                WarningContentMessage = "Please select an Order from the grid.";
                Warning.OpenDialog();
            }
            else
            {
                //Populate orderHeader using selectedPOHeaderID
                orderHeader = await POHeaderService.POHeader_GetOne(selectedPOHeaderID);

                ConfirmHeaderMessage = "Confirm Deletion";
                ConfirmContentMessage = "Please confirm that this order should be deleted.";
                ConfirmOrderDelete.OpenDialog();
            }
        }

        if (args.Item.Text == "Preview")
        {

            //Code for editing - Check that an Order has been selected from the grid
            if (selectedPOHeaderID == 0)
            {
                WarningHeaderMessage = "Warning!";
                WarningContentMessage = "Please select an Order from the grid.";
                Warning.OpenDialog();
            }
            else
            {
                //NavigationManager.NavigateTo($"/previeworder/");
                //NavigationManager.NavigateTo($"/previeworder/{selectedPOHeaderID}");
                await IJS.InvokeAsync<object>("open", new object[] { "/previeworder/" + selectedPOHeaderID + "", "_blank" });
            }
        }
    }

    public void RowSelectHandler(RowSelectEventArgs<POHeader> args)
    {
        //{args.Data} returns the current selected records.
        selectedPOHeaderID = args.Data.POHeaderID;
    }

    protected async Task ConfirmOrderArchive(bool archiveConfirmed)
    {
        if (archiveConfirmed)
        {
            orderHeader.POHeaderIsArchived = true;
            bool Success = await POHeaderService.POHeaderUpdate(orderHeader);
            poheader = await POHeaderService.POHeaderList();
            StateHasChanged();
        }
    }

}