Saturday, November 30, 2019

Create A Simple Blazor Server Application With .NET Core 3.0

Blazor is a new framework built by Microsoft for creating interactive client-side web UI with .NET codebase. Microsoft have recently launched .NET Core 3.0 framework. They have shipped Blazor framework along with this version. In Blazor, we can use C# for both server-side and client-side logic.
Using .NET for client-side web development offers the following advantages:
  • Write code in C# instead of JavaScript.
  • Leverage the existing .NET ecosystem of .NET libraries.
  • Share app logic across server and client.
  • Build on a common set of languages, frameworks, and tools that are stable, feature-rich, and easy to use.
Currently, two types of Blazor applications are available.
  • Blazor Web Assembly and
  • Blazor Server
Blazor WebAssembly is a single-page app framework for building interactive client-side web apps with .NET. Running .NET code inside web browsers is made possible by WebAssembly (abbreviated wasm). WebAssembly is a compact bytecode format optimized for fast download and maximum execution speed. WebAssembly is an open web standard and supported in web browsers without plugins.
 
While, Blazor server decouples component rendering logic from how UI updates are applied. Blazor server provides the support for hosting Razor components on the server in an ASP.NET Core app. UI updates are handled over a SignalR connection.
 
The runtime handles sending UI events from the browser to the server and applies UI updates sent by the server back to the browser after running the components.
 
The connection used by Blazor server to communicate with the browser is also used to handle JavaScript interop calls.
 
Please note that, Blazor WebAssembly is still under preview mode and will be ready by May 2020 as per Microsoft.
 
Please refer to this official Microsoft link to get more details about Blazor framework.
 
We can see, how to create a Blazor server app with .NET Core 3.0 SDK step by step.
 
To develop .NET Core 3.0 SDK applications, you must have Visual Studio 2019 version 16.3 or higher. Blazor server template is already shipped with .NET Core 3.0 SDK. No need to install it separately.

Create a Blazor server app using Visual Studio 2019


Open Visual Studio 2019 and choose “Create a new project” option. It will show the available project templates and we can choose “Blazor App” template.
 
 
 
We can give a valid name and physical location to the project. After giving the project name, we can choose the default “Blazor Server App” template and to click “Create” button.
 
 
 
 
Our new Blazor project will be ready shortly. You can see the below project folder structure.
 
 
 
There is a “wwwroot” folder contains css, bootstrap and favicon files. You can see a “Data” folder which contains a model class and service class for default weather forecast component. “Page” folder contains the “_Host.cshtml” and other four razor component files. We can see a “Shared” folder which contains “MainLayout” and “NavMenu” shared components files. You can also see a “App” component file. Like other .NET Core applications, we have both Program.cs and Startup.cs files as well.
 
As I mentioned earlier, we are going to fetch the latest post details from C# Corner, using their RSS feeds. We can create a “Feed” model class under “Data” folder and define properties.
 
Feed.cs
  1. using System;  
  2.   
  3. namespace BlazorSample.Data  
  4. {  
  5.     public class Feed  
  6.     {  
  7.         public string Link { getset; }  
  8.         public string Title { getset; }  
  9.         public string FeedType { getset; }  
  10.         public string Author { getset; }  
  11.         public string Content { getset; }  
  12.         public DateTime PubDate { getset; }  
  13.         public string PublishDate { getset; }  
  14.   
  15.         public Feed()  
  16.         {  
  17.             Link = "";  
  18.             Title = "";  
  19.             FeedType = "";  
  20.             Author = "";  
  21.             Content = "";  
  22.             PubDate = DateTime.Today;  
  23.             PublishDate = DateTime.Today.ToString("dd-MMM-yyyy");  
  24.         }  
  25.     }  
  26. }  
We can create the service class for getting RSS feed data from C# Corner and add the business logic inside the service.
 
RssFeedService.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Globalization;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6. using System.Xml.Linq;  
  7.   
  8. namespace BlazorSample.Data  
  9. {  
  10.     public class RssFeedService  
  11.     {  
  12.         public async Task<List<Feed>> GetFeedsAsyc()  
  13.         {  
  14.             CultureInfo culture = new CultureInfo("en-US");  
  15.   
  16.             try  
  17.             {  
  18.                 XDocument doc = XDocument.Load("https://www.c-sharpcorner.com/rss/latestcontentall.aspx");  
  19.                 var entries = from item in doc.Root.Descendants().First(i => i.Name.LocalName == "channel").Elements().Where(i => i.Name.LocalName == "item")  
  20.                               select new Feed  
  21.                               {  
  22.                                   Content = item.Elements().First(i => i.Name.LocalName == "description").Value,  
  23.                                   Link = (item.Elements().First(i => i.Name.LocalName == "link").Value).StartsWith("/") ? "https://www.c-sharpcorner.com" + item.Elements().First(i => i.Name.LocalName == "link").Value : item.Elements().First(i => i.Name.LocalName == "link").Value,  
  24.                                   PubDate = Convert.ToDateTime(item.Elements().First(i => i.Name.LocalName == "pubDate").Value, culture),  
  25.                                   PublishDate = Convert.ToDateTime(item.Elements().First(i => i.Name.LocalName == "pubDate").Value, culture).ToString("dd-MMM-yyyy"),  
  26.                                   Title = item.Elements().First(i => i.Name.LocalName == "title").Value,  
  27.                                   FeedType = (item.Elements().First(i => i.Name.LocalName == "link").Value).ToLowerInvariant().Contains("blog") ? "Blog" : (item.Elements().First(i => i.Name.LocalName == "link").Value).ToLowerInvariant().Contains("news") ? "News" : "Article",  
  28.                                   Author = item.Elements().First(i => i.Name.LocalName == "author").Value  
  29.                               };  
  30.   
  31.                 return await Task.FromResult(entries.OrderByDescending(o => o.PubDate).ToList());  
  32.             }  
  33.             catch  
  34.             {  
  35.                 List<Feed> feeds = new List<Feed>();  
  36.                 Feed feed = new Feed();  
  37.                 feeds.Add(feed);  
  38.                 return await Task.FromResult(feeds);  
  39.             }  
  40.         }  
  41.   
  42.     }  
  43. }  
We have added the business logic for getting latest post details from C# Corner RSS feeds.
 
We can create a new razor component “FetchFeeds” under “Pages” folder.
 
 
 
Like the traditional razor views in classic MVC application, we can add client-side and server-side logic inside the razor component.
 
FetchFeeds.razor
  1. @page "/fetchfeeds"  
  2.   
  3. @using BlazorSample.Data  
  4. @inject RssFeedService FeedService  
  5.   
  6. <h1>C# Corner RSS Feeds</h1>  
  7.   
  8. <p>Getting latest post details from C# Corner RSS Feeds</p>  
  9. @if (feeds == null)  
  10. {  
  11.     <p><em>Loading...</em></p>  
  12. }  
  13. else  
  14. {  
  15.     <table class="table">  
  16.         <thead>  
  17.             <tr>  
  18.                 <th>Title</th>  
  19.                 <th>Post Type</th>  
  20.                 <th>Published Date</th>  
  21.                 <th>Author</th>  
  22.             </tr>  
  23.         </thead>  
  24.         <tbody>  
  25.             @foreach (var feed in feeds)  
  26.             {  
  27.                 <tr>  
  28.                     <td><NavLink href=@feed.Link target="_blank">@feed.Title</NavLink></td>  
  29.                     <td>@feed.FeedType</td>  
  30.                     <td>@feed.PublishDate</td>  
  31.                     <td>@feed.Author</td>  
  32.                 </tr>  
  33.             }  
  34.         </tbody>  
  35.     </table>  
  36. }  
  37.   
  38. @code {  
  39.     List<Feed> feeds;  
  40.     protected override async Task OnInitializedAsync()  
  41.     {  
  42.         feeds = await FeedService.GetFeedsAsyc();  
  43.     }  
  44.   
  45. }  
We can add the routing for FetchFeeds component inside the shared component NavMenu under “Shared” folder.
 
We have not yet registered the RssFeedService inside startup class. It is deliberate. Anyway, we can run the application and see, what will happen now.
 
 
 
We can click the “C# Corner Posts” menu link and see, what are happening. You can now notice that, our component will not be loaded successfully. You can check the developer console and will see the below error message.
 
 
We have not received a detailed error message in the console. We must enable the detailed error for circuit options in Startup class.
 
 
 
 
We can run the application and click the menu again.
 
 
 
This time, we have got the exact error message as we have not yet registered the “RssFeedService”. We can register this service inside the startup class.
 
 
 
We can run the application and click the menu again.
 
 
 
We have now successfully fetched the recent post details from C# Corner RSS feeds.

No comments:

Post a Comment

Lab 09: Publish and subscribe to Event Grid events

  Microsoft Azure user interface Given the dynamic nature of Microsoft cloud tools, you might experience Azure UI changes that occur after t...