How to implement logging Framework in Asp.net Core Blazor ?


Tracing logging is one of the critical part of any application to fix the issue or bugs quickly without spending more time to debug application.

There are so many logging framework for blazor, but i will show one of the most popular framework i.e log4Net. Currently i am using in one of my personal demo project.

These are the following steps to implement in Blazor application.

Step 1. Install this 2 packages in project from Nuget Package like this

Step 2. Go to the startup.cs file and inject this package like this

Step3: Create the log4net.xml in parent folder and write the code like this

 <log4net>
	<appender name="Console" type="log4net.Appender.ConsoleAppender">
		<layout type="log4net.Layout.PatternLayout">
			<!-- Pattern to output the caller's file name and line number -->
			<conversionPattern value="%5level [%thread] (%file:%line) - %message%newline" />
		</layout>
	</appender>

	<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
		<file value="logFiles\CarInspectionLog.log" />
		<appendToFile value="true" />
		<maximumFileSize value="100KB" />
		<maxSizeRollBackups value="2" />

		<layout type="log4net.Layout.PatternLayout">
			<conversionPattern value="%level %thread %logger - %message%newline" />
		</layout>
	</appender>

	<root>
		<level value="DEBUG" />
		<appender-ref ref="Console" />
		<appender-ref ref="RollingFile" />
	</root>
</log4net>

 

Step 4: Now use the Log method by using ILogger interface like this

Step 5: Run the application, to see the log message

State Management in Asp.net Core Blazor Server


State Management is the process of maintaining state in one page to other page or entire application page. In each framework there would be separate approach to achieve statement.

Blazor Server is a stateful app framework. Most of the time, the app maintains an ongoing connection to the server.

There are so many approach to implement statement in Blazor Server. But I will show you one of the best and easy approach using AppState pattern.

In this demo we create CurrentCount as global variable to access in other page of blazor.

Step 1: Create the default blazor server demo project and go project folder >> Create CounterState.cs file, Create CurrentCount properties like this.

Step 2: Register in Startup file of blazor like this

Step 3: Go to the index.razor component file and inject the Counter Component like this

Step 4: Go to the Couter.razor component file write the code like this

@page "/counter"
@inject CounterState State;

<h1>Counter</h1>

<p>Current count: @State.CurrentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>


@code {

    private void IncrementCount()
    {
        State.CurrentCount++;
    }
}
 

Step 5: Run the application and click on counter button and verify it on Home page.

Summary

In this small demo we saw that how to maintain the state in two Blazor page using one of the simplest approach.

Cascading Values & Cascading Parameters in Asp.net core Blazor


Today i was working on one blazor POC project, there i got a requirement to pass some value to all the child components which one i was using on the parent component.

Then i found one of the best approach to pass in all the child component using Cascading Values & Cascading Parameters

Let see this concept one small example.

Step 1: Create the parent component like this

@page "/home"

<CascadingValue Value="@FirstFruit" IsFixed="true" Name="FirstFruit">
    
        <Fruit></Fruit>
    
</CascadingValue>

@code {
    string FirstFruit { get; set; } = "Apple";
    
}

In the above code, i m passing FirstFruit property to all the child component, There could be multiple child component. For simplicity i have taken only one.

IsFixed=”true” means Blazor will not monitor it for changes. It is good practice to improve the performance when there will be multiple child component.

Step 2: Create the Fruit Component like this.

<h5>Demo for Cascading Value and Cascading Parameter</h5><br />

<p>The fruit Name is: @Name </p>

@code {
    [CascadingParameter(Name = "FirstFruit")] 
    string Name { get; set; }
}

In the above code CascadingParameter means which field will receive the Cascading Value.
(Name = “FirstFruit”): Means which field we are going to bind from parent component.

Summary

In this sample we saw that how pass the value from parent component to multiple child component with a very minimal coding.

QueryString in Asp.net Core Blazor


Querystring is generally used for passing data from one page to other page. But in Asp.net Core Blazor very straight forward to read the query string.

Step 1: Create the page from where you will pass the query string data. I have created in index page like this.

@page "/"

<h3>Query string Demo</h3>
<a href="/querystringpage?a=2&b=4">Click Here</a> <br />


<br />
<form action="querystringpage">
    First Num1 : <input name="a" /> 
    Second Num2 : <input name="b" />
    <input type="submit" />
</form>

Step 2: Create the page where you are going to read the query string data.

@page "/querystringpage"
@inject NavigationManager nav
@using Microsoft.AspNetCore.WebUtilities

URI: @uri;
<br />

Num1 :@a <br />
Num2 :@b <br />
Sum of Two Num: <b>@c</b>


@code {
    System.Uri uri;
    int a;
    int b;
    int c;
    protected override void OnInitialized()
    {
        uri = nav.ToAbsoluteUri(nav.Uri);
        if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("a", out var aVal))
        {
            a = int.Parse(aVal);
        }
        if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("b", out var bVal))
        {
            b = int.Parse(bVal);
        }
        c = a + b;
    }

}

In the above code, we saw that we are using Microsoft.AspNetCore.WebUtilities namespace, which has the helper method i.e. QueryHelpers to extract the query string value. We have also injected the NavigationManager the url path of page.

Summary:

In this small demo, we saw that how QueryHelpers method of Microsoft.AspNetCore.WebUtilities namespace simplified our code to read the query string in asp.net core Blazor.

Data binding in Asp.net Core Blazor


There are two type of data binding in asp.net core blazor

1. One way data binding
2. Two way data binding

One way data binding

In this approach data communication will happen in one way. In blazor case data will be bind from the component class to the component view.

Example of one way data binding

@page "/oneway"
<h3>One way Data binding Example</h3> <br />

 Message: @msg 

@functions {
    string msg = "This is one ways data binding message.";
}

Two way data binding

In this approach data can pass in both ways. We can use this type of data binding on text-box to label or text-box depending on our requirement.

Example of Two way data binding

@page "/twoWay"
<h3>Two-way Data Binding Example</h3>

    Enter your name:
<input @bind=@Name   @bind:event="oninput" />
<br />
<br />
    Is it intresting to Learn Blazor ?
<input type="checkbox" @bind="IsTry" />
<br />
<br />
<br />

<p><b>Summary</b></p>
    You have entered:@Name
    <br />
    Your Answer: @(IsTry ? "Yes" : "No")

    @functions {
        public string Name { get; set; }
        public bool IsTry { get; set; }
    }  

Summary
In this small post we saw the example of data-binding in Blazor.