When you buy this book you support this site! - Thank You for your support!

Dec 29

Written by: Michael Washington
12/29/2019 1:03 PM  RssIcon

The primary benefit we have when using server-side Blazor is that we do not have to make web http calls from the client code to the server code. This reduces the code we need to write and eliminates many security concerns.

In this article, we will demonstrate how a list of Weather forecasts can be added to the database by each user. A user will only have the ability to see their own forecasts.

 

image

You can watch the YouTube video for this tutorial at the following link:

https://www.youtube.com/watch?v=dSW23gkQLP4

 

Use SQL Server

image

The new project template in Visual Studio will allow you to create a database using SQL Server Express LocalDB. However, it can be problematic to install and configure. Using the free SQL Server 2019 Developer server (or the full SQL Server) is recommended.

Download and install SQL Server 2019 Developer Edition from the following link:

https://www.microsoft.com/en-us/sql-server/sql-server-downloads

 

Create The Blazor Application

image

Open Visual Studio.

 

image

Select Create a new Project.

 

image

Select Blazor App and click Next.

 

image

Name it EndToEnd and click Create.

 

image

Select Blazor Server App.

 

image

Click the Change link under Authentication.

 

image

Select Individual User Accounts and Store user accounts in-app.

 

image

Click Create.

 

image

The project will be created.

 

Create The Database

image

Open the SQL Server Object Explorer.

 

image

Add a connection to your local database server if you don’t already have it in the SQL Server list.

For this tutorial, we do not want to use the SQL Express server on (localdb) that you may already see in the list.

 

image

You will specify just the server and Connect.

 

image

Expand the tree under the local SQL server, right-click on the Databases folder and select Add New Database.

 

image

Give the database a name and press Enter.

The database will be created.

image

Right-Click on the Database node and select Properties.

 

image

Open the Properties window if it is not already opened.

The Properties window for the database will display.

Copy the Connection string for the database.

 

image

Open the appsettings.json file.

 

image

Paste in the connection string for the DefaultConnection and save the file.

 

image

Hit F5 to run the application.

 

image

The application will open in your web browser.

Click the Register link.

 

image

Enter the information to create a new account.

Click the Register button.

 

image

Because this is the first time the database is being used, you will see a message asking you to run the migration scripts that will create the database objects needed to support the user membership code.

Click the Apply Migrations button.

 

image

After the message changes to Migrations Applied, refresh the page in the web browser.

 

image

After clicking refresh in your web browser, a popup will require you to click Continue.

 

image

Click the Click here to confirm your account link.

 

image

On the Confirm email page, click the name of the application to navigate to the home page.

 

image

Now you can click the Log in link to log in using the account you just created.

 

image

You will now be logged into the application.

You can click around the application and see that it works.

 

image

The Fetch data page currently shows random data. We will alter the application to allow us to add, update, and delete this data in the database.

Close the web browser to stop the application.

 

Do Not Require Account Confirmation

image

If we do not intend to configure email account verification (using the directions at this link: https://bit.ly/2tf2ym4), we can open the Startup.cs file and change the following line:

 

            services.AddDefaultIdentity<IdentityUser>(
                options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();

 

To:

 

            services.AddDefaultIdentity<IdentityUser>(
                options => options.SignIn.RequireConfirmedAccount = false)
                .AddEntityFrameworkStores<ApplicationDbContext>();

 

 

 

Create The Database

image

In the SQL Server Object Explorer window, in Visual Studio, we see the tables that the migration scripts added.

 

image

Right-click on the Tables node and select Add New Table.

 

image

Paste the following script in the T-SQL window and then click the Update button:

 

CREATE TABLE [dbo].[WeatherForecast] (
    [Id]           INT           IDENTITY (1, 1) NOT NULL,
    [Date]         DATETIME      NULL,
    [TemperatureC] INT           NULL,
    [TemperatureF] INT           NULL,
    [Summary]      NVARCHAR (50) NULL,
    [UserName]     NVARCHAR (50) NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

 

image

The script will prepare.

Click the Update Database button.

 

image

Back in the Server Explorer window, right-click on Tables and select Refresh.

 

image

The WeatherForecast table will display.

Right-click on the table and select Show Table Data.

 

image

We will enter some sample data so that we will be able to test the data connection in the next steps.

Set the UserName field to the username of the user that we registered an account for earlier.

 

Create The Data Context

image

If you do not already have it installed, install EF Core Power Tools from:

https://marketplace.visualstudio.com/items?itemName=ErikEJ.EFCorePowerTools

 

image

(Note: Before installing, close Visual Studio)

(Note: Please give this project a 5 star review on marketplace.visualstudio.com!)

 

image

Right-click on the project node in the Solution Explorer and select EF Core Power Tools then Reverse Engineer.

 

image

Click the Add button.

 

image

Connect to the database.

 

 

image

Select the database connection in the dropdown and click OK.

 

image

Select the WeatherForecast table and click OK.

 

image

Set the values and click OK.

 

image

In the Solution Explorer, you will see the Data Context has been created.

Click the OK button to close the popup.

 

image

Open the Startup.cs file.

Add the following code to the ConfigureServices section:

 

    // Read the connection string from the appsettings.json file
    // Set the database connection for the EndtoEndContext
    services.AddDbContext<EndToEndDB.Data.EndToEnd.EndtoEndContext>(options =>
    options.UseSqlServer(
        Configuration.GetConnectionString("DefaultConnection")));

 

Also, change this line:

 

            services.AddSingleton<WeatherForecastService>();

 

to this:

 

            // Scoped creates an instance for each user
            services.AddScoped<WeatherForecastService>();

 

image

Save the file.

Select Build, then Rebuild Solution.

 

Read From The Database

image

Delete the Data/WeatherForecast.cs file in the project.

We will use the Data/EndToEnd/WeatherForcast.cs class file created by the EF Core Tools instead.

 

image

Open the WeatherForecastService.cs file.

Replace all the code with the following code:

 

using EndToEndDB.Data.EndToEnd;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EndToEnd.Data
{
    public class WeatherForecastService
    {
        private readonly EndtoEndContext _context;
        public WeatherForecastService(EndtoEndContext context)
        {
            _context = context;
        }
        public async Task<List<WeatherForecast>>
            GetForecastAsync(string strCurrentUser)
        {
            // Get Weather Forecasts  
            return await _context.WeatherForecast
                 // Only get entries for the current logged in user
                 .Where(x => x.UserName == strCurrentUser)
                 // Use AsNoTracking to disable EF change tracking
                 // Use ToListAsync to avoid blocking a thread
                 .AsNoTracking().ToListAsync();
        }
    }
}

 

This:

 

        private readonly EndtoEndContext _context;
        public WeatherForecastService(EndtoEndContext context)
        {
            _context = context;
        }

 

 

Connects to the database using the datacontext we created with the EF Core tools.

 

image

Finally, open the FetchData.razor file.

Replace all the code with the following code:

 

@page "/fetchdata"
@using EndToEnd.Data
@using EndToEndDB.Data.EndToEnd
@inject AuthenticationStateProvider AuthenticationStateProvider
@*
    Using OwningComponentBase ensures that the service and related services
    that share its scope are disposed with the component.
    Otherwise DbContext in ForecastService will live for the life of the
    connection, which may be problematic if clients stay
    connected for a long time.
    We access WeatherForecastService using @Service
*@
@inherits OwningComponentBase<WeatherForecastService>
<h1>Weather forecast</h1>
<!-- AuthorizeView allows us to only show sections of the page -->
<!-- based on the security on the current user -->
<AuthorizeView>
    <!-- Show this section if the user is logged in -->
    <Authorized>
        <h4>Hello, @context.User.Identity.Name!</h4>
        @if (forecasts == null)
        {
            <!-- Show this if the current user has no data... yet... -->
            <p><em>Loading...</em></p>
        }
        else
        {
            <!-- Show the forecasts for the current user -->
            <table class="table">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Temp. (C)</th>
                        <th>Temp. (F)</th>
                        <th>Summary</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var forecast in forecasts)
                    {
                        <tr>
                            <td>@forecast.Date.Value.ToShortDateString()</td>
                            <td>@forecast.TemperatureC</td>
                            <td>@forecast.TemperatureF</td>
                            <td>@forecast.Summary</td>
                        </tr>
                    }
                </tbody>
            </table>
        }
    </Authorized>
    <!-- Show this section if the user is not logged in -->
    <NotAuthorized>
        <p>You're not signed in.</p>
    </NotAuthorized>
</AuthorizeView>
@code {
    // AuthenticationState is available as a CascadingParameter
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }
    List<WeatherForecast> forecasts;
    protected override async Task OnInitializedAsync()
    {
        // Get the current user
        var user = (await authenticationStateTask).User;
        // Get the forecasts for the current user
        // We access WeatherForecastService using @Service
        forecasts = await @Service.GetForecastAsync(user.Identity.Name);
    }
}

 

This code simply calls the GetForecastAsync method we created in the previous step, passing the username of the currently logged in user.

In a normal web application we would have to make a http web call from this client code to the code that connects to the database.

With server-side Blazor we don’t have to do that, yet the call is still secure because the pages are rendered on the server.

 

image

Build and run the project.

If we are not logged in, and we go to the Fetch data page, we will see a message indicating we are not signed in.

 

image

Click the Login button.

 

image

Log in as the user we created data for earlier.

 

image

After you are logged in, switch to the Fetch data page and you will see the data for the user we entered earlier.

 

Inserting Data Into The Database

image

Open the WeatherForecastService.cs file and add the following method:

 

        public Task<WeatherForecast>
            CreateForecastAsync(WeatherForecast objWeatherForecast)
        {
            _context.WeatherForecast.Add(objWeatherForecast);
            _context.SaveChanges();
            return Task.FromResult(objWeatherForecast);
        }

 

image

Open the FetchData.razor file.

Add the following HTML markup directly under the existing table element:

 

            <p>
                <!-- Add a new forecast -->
                <button class="btn btn-primary"
                        @onclick="AddNewForecast">
                    Add New Forecast
                </button>
            </p>

 

This adds a button to allow a new forecast to be added.

Add the following code below the previous code:

 

   @if (ShowPopup)
            {
                <!-- This is the popup to create or edit a forecast -->
                <div class="modal" tabindex="-1" style="display:block" role="dialog">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h3 class="modal-title">Edit Forecast</h3>
                                <!-- Button to close the popup -->
                                <button type="button" class="close"
                                        @onclick="ClosePopup">
                                    <span aria-hidden="true">X</span>
                                </button>
                            </div>
                            <!-- Edit form for the current forecast -->
                            <div class="modal-body">
                                <input class="form-control" type="text"
                                       placeholder="Celsius forecast"
                                       @bind="objWeatherForecast.TemperatureC" />
                                <input class="form-control" type="text"
                                       placeholder="Fahrenheit forecast"
                                       @bind="objWeatherForecast.TemperatureF" />
                                <input class="form-control" type="text"
                                       placeholder="Summary"
                                       @bind="objWeatherForecast.Summary" />
                                <br />
                                <!-- Button to save the forecast -->
                                <button class="btn btn-primary"
                                        @onclick="SaveForecast">
                                    Save
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            }

 

This adds a form (that will be displayed a popup because the class for the DIV is modal), that allows the user to enter (and later edit) data for a forecast.

We do not need JavaScript to make this popup show. We only need to wrap this code with:

 

            @if (ShowPopup)
            {
                ...
            }

 

When the ShowPopup value is true the popup will show. When the value is false, the popup will disappear.

Add the following code to the @code section:

 

    WeatherForecast objWeatherForecast = new WeatherForecast();
    bool ShowPopup = false;
    void ClosePopup()
    {
        // Close the Popup
        ShowPopup = false;
    }
    void AddNewForecast()
    {
        // Make new forecast
        objWeatherForecast = new WeatherForecast();
        // Set Id to 0 so we know it is a new record
        objWeatherForecast.Id = 0;
        // Open the Popup
        ShowPopup = true;
    }
    async Task SaveForecast()
    {
        // Close the Popup
        ShowPopup = false;
        // Get the current user
        var user = (await authenticationStateTask).User;
        // A new forecast will have the Id set to 0
        if (objWeatherForecast.Id == 0)
        {
            // Create new forecast
            WeatherForecast objNewWeatherForecast = new WeatherForecast();
            objNewWeatherForecast.Date = System.DateTime.Now;
            objNewWeatherForecast.Summary = objWeatherForecast.Summary;
            objNewWeatherForecast.TemperatureC =
            Convert.ToInt32(objWeatherForecast.TemperatureC);
            objNewWeatherForecast.TemperatureF =
            Convert.ToInt32(objWeatherForecast.TemperatureF);
            objNewWeatherForecast.UserName = user.Identity.Name;
            // Save the result
            var result =
            @Service.CreateForecastAsync(objNewWeatherForecast);
        }
        else
        {
            // This is an update
        }
        // Get the forecasts for the current user
        forecasts =
        await @Service.GetForecastAsync(user.Identity.Name);
    }

 

 

image

When you run the project, you can click the Add New Forecast button to add an entry.

 

image

The form only requires a Fahrenheit, Celsius, and a summary, because the other values (date and username), will be set by the code.

 

image

After clicking the Save button, the entry is saved to the database and displayed.

 

Updating The Data

image

Open the WeatherForecastService.cs file and add the following method:

 

     public Task<bool>
            UpdateForecastAsync(WeatherForecast objWeatherForecast)
        {
            var ExistingWeatherForecast =
                _context.WeatherForecast
                .Where(x => x.Id == objWeatherForecast.Id)
                .FirstOrDefault();
            if (ExistingWeatherForecast != null)
            {
                ExistingWeatherForecast.Date =
                    objWeatherForecast.Date;
                ExistingWeatherForecast.Summary =
                    objWeatherForecast.Summary;
                ExistingWeatherForecast.TemperatureC =
                    objWeatherForecast.TemperatureC;
                ExistingWeatherForecast.TemperatureF =
                    objWeatherForecast.TemperatureF;
                _context.SaveChanges();
            }
            else
            {
                return Task.FromResult(false);
            }
            return Task.FromResult(true);
        }

 

image

Open the FetchData.razor file.

Replace the existing table element with the following markup that adds an edit button in the last column (that calls the EditForecast method we will add in the next step):

 

           <table class="table">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Temp. (C)</th>
                        <th>Temp. (F)</th>
                        <th>Summary</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var forecast in forecasts)
                    {
                        <tr>
                            <td>@forecast.Date.Value.ToShortDateString()</td>
                            <td>@forecast.TemperatureC</td>
                            <td>@forecast.TemperatureF</td>
                            <td>@forecast.Summary</td>
                            <td>
                                <!-- Edit the current forecast -->
                                <button class="btn btn-primary"
                                        @onclick="(() => EditForecast(forecast))">
                                    Edit
                                </button>
                            </td>
                        </tr>
                    }
                </tbody>
            </table>

 

Add the following code to the @code section:

 

    void EditForecast(WeatherForecast weatherForecast)
    {
        // Set the selected forecast
        // as the current forecast
        objWeatherForecast = weatherForecast;
        // Open the Popup
        ShowPopup = true;
    }

 

This sets the current record to the objWeatherForecast object that the popup is bound to, and opens the popup.

Finally, change the existing SaveForecast method to the following:

 

    async Task SaveForecast()
    {
        // Close the Popup
        ShowPopup = false;
        // Get the current user
        var user = (await authenticationStateTask).User;
        // A new forecast will have the Id set to 0
        if (objWeatherForecast.Id == 0)
        {
            // Create new forecast
            WeatherForecast objNewWeatherForecast = new WeatherForecast();
            objNewWeatherForecast.Date = System.DateTime.Now;
            objNewWeatherForecast.Summary = objWeatherForecast.Summary;
            objNewWeatherForecast.TemperatureC =
            Convert.ToInt32(objWeatherForecast.TemperatureC);
            objNewWeatherForecast.TemperatureF =
            Convert.ToInt32(objWeatherForecast.TemperatureF);
            objNewWeatherForecast.UserName = user.Identity.Name;
            // Save the result
            var result =
            @Service.CreateForecastAsync(objNewWeatherForecast);
        }
        else
        {
            // This is an update
            var result =
            @Service.UpdateForecastAsync(objWeatherForecast);
        }
        // Get the forecasts for the current user
        forecasts =
        await @Service.GetForecastAsync(user.Identity.Name);
    }

 

This simply adds one line:

 

            // This is an update
            var result =
            @Service.UpdateForecastAsync(objWeatherForecast);

 

To the existing method to handle an update rather than an insert.

 

image

When we run the application, we now have an Edit button to edit the existing record.

 

image

The existing record will display in the popup, allowing us to edit the data and save it.

 

image

The updated record is then displayed in the table.

 

Deleting The Data

image

Open the WeatherForecastService.cs file and add the following method:

 

        public Task<bool>
            DeleteForecastAsync(WeatherForecast objWeatherForecast)
        {
            var ExistingWeatherForecast =
                _context.WeatherForecast
                .Where(x => x.Id == objWeatherForecast.Id)
                .FirstOrDefault();
            if (ExistingWeatherForecast != null)
            {
                _context.WeatherForecast.Remove(ExistingWeatherForecast);
                _context.SaveChanges();
            }
            else
            {
                return Task.FromResult(false);
            }
            return Task.FromResult(true);
        }

 

image

Open the FetchData.razor file.

Add code markup for a Delete button under the code markup for the current Save button in the popup:

 

            <!-- Only show delete button if not a new record -->
            @if (objWeatherForecast.Id > 0)
            {
                <!-- Button to delete the forecast -->
                <button class="btn btn-primary"
                        @onclick="DeleteForecast">
                    Delete
                </button>
            }

 

Add the following code to the @code section:

 

    async Task DeleteForecast()
    {
        // Close the Popup
        ShowPopup = false;
        // Get the current user
        var user = (await authenticationStateTask).User;
        // Delete the forecast
        var result = @Service.DeleteForecastAsync(objWeatherForecast);
        // Get the forecasts for the current user
        forecasts =
        await @Service.GetForecastAsync(user.Identity.Name);
    }

 

image

When we run the code and click the Edit button…

 

image

… we now see a Delete button that will delete the record.

 

image

However, when we click the Add New Forecast button that opens the same popup

 

image

The delete button does not display (because there is no record to delete at this point).

 

Use Code Behind Method Using Partial Class Support

image

We can code our .razor pages using an @code block with HTML markup in a single file, or with the C# code placed in a code-behind file defined as a partial class.

Create a new class called FetchData.razor.cs using the following code:

 

using EndToEndDB.Data.EndToEnd;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace EndToEnd.Pages
{
    public partial class FetchData
    {
        // AuthenticationState is available as a CascadingParameter
        [CascadingParameter]
        private Task<AuthenticationState> authenticationStateTask { get; set; }
        List<WeatherForecast> forecasts;
        protected override async Task OnInitializedAsync()
        {
            // Get the current user
            var user = (await authenticationStateTask).User;
            // Get the forecasts for the current user
            // We access WeatherForecastService using @Service
            forecasts = await @Service.GetForecastAsync(user.Identity.Name);
        }
        WeatherForecast objWeatherForecast = new WeatherForecast();
        bool ShowPopup = false;
        void ClosePopup()
        {
            // Close the Popup
            ShowPopup = false;
        }
        void AddNewForecast()
        {
            // Make new forecast
            objWeatherForecast = new WeatherForecast();
            // Set Id to 0 so we know it is a new record
            objWeatherForecast.Id = 0;
            // Open the Popup
            ShowPopup = true;
        }
        async Task SaveForecast()
        {
            // Close the Popup
            ShowPopup = false;
            // Get the current user
            var user = (await authenticationStateTask).User;
            // A new forecast will have the Id set to 0
            if (objWeatherForecast.Id == 0)
            {
                // Create new forecast
                WeatherForecast objNewWeatherForecast = new WeatherForecast();
                objNewWeatherForecast.Date = System.DateTime.Now;
                objNewWeatherForecast.Summary = objWeatherForecast.Summary;
                objNewWeatherForecast.TemperatureC =
                Convert.ToInt32(objWeatherForecast.TemperatureC);
                objNewWeatherForecast.TemperatureF =
                Convert.ToInt32(objWeatherForecast.TemperatureF);
                objNewWeatherForecast.UserName = user.Identity.Name;
                // Save the result
                var result =
                @Service.CreateForecastAsync(objNewWeatherForecast);
            }
            else
            {
                // This is an update
                var result =
                @Service.UpdateForecastAsync(objWeatherForecast);
            }
            // Get the forecasts for the current user
            forecasts =
            await @Service.GetForecastAsync(user.Identity.Name);
        }
        void EditForecast(WeatherForecast weatherForecast)
        {
            // Set the selected forecast
            // as the current forecast
            objWeatherForecast = weatherForecast;
            // Open the Popup
            ShowPopup = true;
        }
        async Task DeleteForecast()
        {
            // Close the Popup
            ShowPopup = false;
            // Get the current user
            var user = (await authenticationStateTask).User;
            // Delete the forecast
            var result = @Service.DeleteForecastAsync(objWeatherForecast);
            // Get the forecasts for the current user
            forecasts =
            await @Service.GetForecastAsync(user.Identity.Name);
        }
    }
}
Remove the entire @code bock from the FetchData.razor page.

The application will still behave the same.

 

Links

Blazor.net

ASP.NET Core Blazor authentication and authorization

EF Core Power Tools

OwningComponentBase (background)

 

Download

The project is available at http://BlazorHelpWebsite.com/Downloads.aspx

You must have Visual Studio 2019 Version 16.3 (or higher) installed to run the code.

Tags: Blazor
Categories:

29 comment(s) so far...


Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

Great work.

Everyone should use your project as a template, for any business web app.

Cheers

By kalvin on   12/29/2019 2:20 PM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

@kalvin - Thank you for the support!

By Michael Washington on   12/29/2019 2:20 PM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

Hi, many, many thanks for this tutorial. Very helpful.
But how can I use an own loging page or can change the default? (I don't find it in project).
Greetings
Andy

By Andy on   12/30/2019 5:30 AM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

@Andy - See this link to scaffold identity pages so you can customize them: https://docs.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-3.1&tabs=visual-studio

By Michael Washington on   12/30/2019 5:31 AM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

Thanks you!!! :)

By Andy on   12/31/2019 4:36 AM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

Hi Michael,
thank you for the article! It is very useful.

To the sample: how to replace Identity functionality (Register, Login) with PostgreSQL identity implementation :
https://github.com/Robynhu/AspNetCore.Identity.PostgreSQL

It uses PG as a Storage, it does not use EF, and it is light and comfortable.

By Oleg on   1/3/2020 4:28 AM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

@Oleg - I have no way of trying it myself because I don't use PostgreSQL, but, it should work.

By Michael Washington on   1/3/2020 4:29 AM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

Great example .. thank you.

Have enjoy your work for years back to the DNN days.

However download link for this article seems to be broken. - I got the Blazor Cookie download instead ??

Thanks
Paul.

By Paul Scarlett on   1/6/2020 12:52 PM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

@Paul Scarlett - "BlazorCookieAuthInsertDatabase.zip" is the correct version :)

By Michael Washington on   1/6/2020 12:54 PM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

Muchas gracias, me ayudo bastante.

Te mando saludos desde Lima - Peru.

By Fredy Gonzales on   1/7/2020 4:57 AM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

Tried a few times, but got Error..

An unhandled exception occurred while processing the request.
SqlException: Invalid object name 'WeatherForecast'.
Microsoft.Data.SqlClient.SqlCommand+c.b__164_0(Task result)
....
+ 22 return await _context.WeatherForecast
...
+23 forecasts = await @Service.GetForecastAsync(user.Identity.Name);

Any help?
ty.

By Mabaega on   1/26/2020 8:56 AM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

@Mabaega - It appears you did not create the database table properly, or your database connection string is incorrect.

By Michael Washington on   1/26/2020 8:57 AM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

Hi, Michael, thank you for your post. I start to use "OwningComponentBase", but I have some problems related to db context. When I start the app and use different SignalR connections (two different browser tabs) when I change data from the one tab and retrieve it in another, there is no change, if I retrieve it in the first tab, data is changed. With your app, I don`t have this problem. Could be the problem found in that you use two db context one for "Identity" and one for data - EndToEndContext and the context is partial or in mixing async-await methods like you and return "Task.FromResult()", instead of using await and async versions of methods. Thank you for your time, again :)!

By Sashko on   2/5/2020 8:48 AM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

@Sashko - I think the difference is not in OwningComponentBase, but that the .razor page code is not holding the Entity Framework DataContext change tracking using code like "AsNoTracking". This 'breaks' the connection between what the person is doing and the particular SignalR connection and the database operations.

By Michael Washington on   2/5/2020 8:53 AM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

@Michael - Thank you for your answer, I try already with this approach in my project and everything is working fine. I don`t need to create different scopes for every request to get new data. Thank you very much :)!

By Sashko on   2/6/2020 4:32 AM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

Hi Michael:I bought your book and now I'm going through the tutorial for .Net Core 3.1. I am getting an error after I update the FetchData.razor File and run the solution. Here is the message I am getting with the error:Message=Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: ...

By Dan on   2/8/2020 5:10 AM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

@Dan - Your startup.cs file does not seem to have all needed elements. You will want to download the sample project from this site and compare the code to your own.

By Michael Washington on   2/8/2020 5:12 AM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

Very helpful, many thanks

By Santiago Sanchez Garcia on   2/17/2020 9:07 AM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

Hi am getting the following error

"Unable to find package Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore. No packages exist with this id in source(s): Microsoft Visual Studio Offline Packages"

Can some one help...

By Arjun on   3/11/2020 4:00 AM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

@Arjun - Please download the code from the Downloads page on this site and compare the code to your own.

By Michael Washington on   3/11/2020 4:01 AM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

Very good demo, thanks for the good post!
Could I know if it is good idea to use the demo work on local network only(windows 7 as server), stations(PC or Android device) accees by web browser?


By David W on   3/21/2020 5:40 PM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

@David W - I am sorry but I do not know if you can use a Windows 7 as a server. I have not tested it on windows 7 as server. However, I have tested it with PC and Android devices and it works fine.

By Michael Washington on   3/21/2020 5:41 PM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

@Michael - Thank you for your answer, it is very helpful.

By David W on   3/22/2020 5:14 PM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

Hi Michael, Just want to add my kudos to you. Fantastic job!
I have gone through a lot of your Blazor examples and, for a newbie like me, i have found these tremendously helpful to get started building my own site.

Question for you: regarding the @services functions for CRUD operations, do you have any suggestions for how i can modify them for SQL queries. i have looked at a number of sites for help on this but haven't had much luck. i know that i will need to use sql parameters. i also want to be able to call stored procedures. and suggestions would be much appreciated!!!

By Michael Lockitch on   3/25/2020 2:20 PM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

@Michael Lockitch - Sorry I have no examples :( You really want to find a good clear example for what you are trying to do.

By Michael Washington on   3/25/2020 2:21 PM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

I have tested the project in Visual Studio 2019, I bypassed the migration step as I wanted to point my sql connection to remote database (in fact , all these tutorials should be shown how to connect remotely, as your application is going to be used by users on the internet, right?). The weatherforecast table i created on my remote sql db, works fine with the CRUD and registration/login (with identity tables). But now I want to use my own table in the same database , whats the best way to tweaked the weatherforecastservice.cs, i see the weatherforecast.cs model can be simply revised to mytable. cs (the table in want to now use). This is not like the older EntityFramework in which you can go to the .edmx and do an "update model from database"

By mmx on   3/30/2020 4:49 PM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

@mmx - This tutorial should provide the experience you desire. The example points to (local) but it can be pointed to your external database.

By Michael Washington on   3/30/2020 4:55 PM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

Great explanation,swift and integrated ..Just what people need to step up in new Blazor framework.
Thank you very much

By Dzevad Gojak on   4/3/2020 12:28 PM
Gravatar

Re: Creating A Step-By-Step End-To-End Database Server-Side Blazor Application (updated to .Net Core 3.1)

@Dzevad Gojak - Thank you for the kind words.

By Michael Washington on   4/3/2020 12:29 PM

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
CAPTCHA image
Enter the code shown above in the box below
Add Comment   Cancel 
Microsoft Visual Studio is a registered trademark of Microsoft Corporation / LightSwitch is a registered trademark of Microsoft Corporation