BLAZOR ,REACT JS & ANGULAR JS

Are you tired of using JavaScript for building web applications? Have you ever wished that there was a better way to build web applications without having to deal with the complexities of JavaScript? Well, there is! Blazor is a new web development framework that allows developers to build interactive web applications using C# instead of JavaScript.

In this blog post, we will explore some of the reasons why Blazor is better than JavaScript for web development. We’ll discuss the advantages of using Blazor, including its simplified development process, increased performance, and code reusability etc.

What Does Blazor Offer?

Compatibility with various operating systems – The code which is written in Visual Studio improves overall Blazor app development and offers mixtures of operating systems like macOS, Linus, and Windows. 

Exchanging .NET code and libraries -The Blazor based apps use the existing .NET libraries. All credit goes to the standardized format of .NET for building an official explicit .NET libraries and .NET code.

  • Blazor shares the server-side code and client-side code: Blazor allows developers to reuse code between the front end and back end.
  • Dependency injection: Dependency injection is a usable object that can act as a service in Blazor. Blazor uses dependency injection in its applications to achieve inversion of control. It allows providing objects with dependencies. In Blazor, dependency injection can be divided into classes: injector, client, and service. Blazor also features different injectors such as constructors, properties, and methods.
  • Visual Studio Code: We can develop Blazor apps using visual studio code since both are Microsoft products. When you develop an app in the Blazor framework, VS Code will help you utilize its features easily.
  • Interoperability with JavaScript: Blazor uses interop functionality in Blazor WebAssembly to handle DOM manipulations. Also, this JavaScript functionality can use browser API calls in Blazor WebAssembly. Therefore, Blazor apps can use .NET methods with JavaScript functions.
  • Unrestricted access and open source: Blazor is connected to the open-source.NET platform, which has a strong and reliable network of almost 60,000 supporters from over 3,700 distinct companies. 

While both Blazor and JavaScript can be used to build web applications, they have different strengths and use cases. Blazor is particularly useful for developers who are already familiar with C# and want to build web applications without having to learn JavaScript. JavaScript, on the other hand, is more widely used and has a larger community of developers and resources available. Ultimately, the choice between Blazor and JavaScript will depend on the specific requirements of your project and the skillset of your development team.

Blazor Vs React JS

Blazor and React are two different web development frameworks that can be used to build modern web applications.Blazor is a web framework developed by Microsoft that allows developers to build interactive web applications using C# instead of JavaScript, while React is a JavaScript library for building user interfaces.

One of the main differences between Blazor and React is the language used to build applications. Blazor uses C#, while React uses JavaScript. This means that developers who are already familiar with C# may find it easier to work with Blazor, while those who are more experienced with JavaScript may prefer to use React.

Another difference between Blazor and React is the way they handle user interface rendering. Blazor uses a server-side rendering model, where the HTML for the user interface is generated on the server and sent to the client, while React uses a client-side rendering model, where the HTML is generated on the client-side using JavaScript.

ReactBlazor
TypeFront-End Library – focuses on the client UI and interactions of your website.Full Framework – client side (WASM) and server side (ASP.NET)
DeveloperFacebookMicrosoft
LicenseMITApache
LanguageJavaScript/JSX/TypeScriptC#
PerformanceLight weight with great performance.WASM client-side apps have a heavier first-time load. Server-side highly performant
Learning CurveEasy to LearnEasy to Learn
PWA (Progressive Web App) SupportYesYes (Blazor WebAssembly)
RoutingNot includedYes
Http ClientNot includedYes
Dependency InjectionNot includedYes
Requires an active connection per clientNoYes
Stores the component state server-side for each clientNoYes (Blazor Server)
Scoped styles for componentsYesYes
Static DeploymentYesYes (Blazor WebAssembly)
Server-Side RenderingYesYes
Optimized for SEO / CrawlersYesYes
Bundle Size12KB gzipped, but only a client render framework, not full stack.Minimal for Blazor Server.  As low as 393kb, up to 780kb  for .NET Framework in a Client-side WASM app.
ToolingCLI plus many 3rd party options.CLI, Visual Studio and 3rd party options.
Production ReadyReact is production-ready today with years of battle-tested deployments from companies such as Uber, Drop Box, Twitter, Paypal, Netflix, Walmart, and more.Yes, considering the major enhancements release in November 2021 with NET 6.

Ultimately, the choice between Blazor and React will depend on the specific requirements of your project, the skillset of your development team, and the available resources and tools. Both frameworks have their strengths and use cases, and choosing the right one for your project will require careful consideration and evaluation.

Blazor Vs Angular JS

Blazor and Angular are two popular web development frameworks that can be used to build modern web applications. Blazor is a web framework developed by Microsoft that allows developers to build interactive web applications using C# instead of JavaScript, while Angular is a JavaScript framework for building dynamic, single-page web applications.

One of the main differences between Blazor and Angular is the language used to build applications. Blazor uses C#, while Angular uses TypeScript, which is a superset of JavaScript. This means that developers who are already familiar with C# may find it easier to work with Blazor, while those who are more experienced with JavaScript may prefer to use Angular.

Another difference between Blazor and Angular is the way they handle user interface rendering. Blazor uses a server-side rendering model, where the HTML for the user interface is generated on the server and sent to the client, while Angular uses a client-side rendering model, where the HTML is generated on the client-side using JavaScript.

Ultimately, the choice between Blazor and Angular will depend on the specific requirements of your project, the skillset of your development team, and the available resources and tools. Both frameworks have their strengths and use cases, and choosing the right one for your project will require careful consideration and evaluation.

How to Integrate Stripe into a .NET 6 C# Application

Stripe is a popular payment gateway that makes it easy to accept credit card payments.Stripe enables businesses to accept online payments, process subscriptions, and manage their finances. It provides a secure and easy-to-use platform for processing credit card transactions, bank transfers, and other forms of online payments. Stripe offers a range of features and integrations, including support for over 135 currencies and a variety of payment methods. Stripe also provides robust APIs and developer tools that make it easy to customize payment flows and integrate with other systems. With Stripe, businesses of all sizes can accept payments online and grow their business.

Following are the steps to integrate Stripe into your .NET 6 C# application

In order to move on and accept Stripe payments in .NET, we have to get some API keys to authenticate with. This is possible when you got a Stripe account.

STEP 1 : Signup for/Create a new Stripe account

 If you do not already have an account, you can register for one here. https://dashboard.stripe.com/register

Fill details and click on register .After register this type of dashboard will appear.

Once you’ve created your account, go to the Developers section and navigate to the API keys page to get the stripe API keys: Publishable Key and Secret Key.

What are the keys used for?

  • The Publishable key is used by the client application. This could be a web or mobile app making connections.
  • The Secret key is used in the authentication process at the backend server (API Server). By default, we use this key to perform any of the requests between our Web API and Stripe.

STEP 2 : Install the Stripe.NET library using NuGet package manager In Visual Studio, right-click on your project in the Solution Explorer and select Manage NuGet Packages. In the NuGet Package Manager window, search for Stripe.NET and install the latest version.

STEP 3: Add the necessary configuration settings in the appsettings.json file .In your appsettings.json file, add the following configuration settings:

Replace <your-publishable-key> and <your-secret-key> with the values you obtained from the Stripe API keys page.

RegisterServices

Now create Checkout form in blazor for entering CustomerDetails

when we click on PlaceOrder button Checkout method will call .On the server side we call Stripe Services .

First, create an object of credit card to generate token. While creating customer object we need this token.Set StripeTokenID to the customer object. This code will add customer on Stripe.

PaymentIntentCreateOptions is a class in the Stripe API that contains various options for creating a new Payment Intent.

In Stripe, a Payment Intent represents the process of collecting a payment from a customer. When creating a Payment Intent, you can specify various options such as the amount to charge, the currency to use, the payment method to attach to the intent, and other details.

Integrate Chatgpt in Blazor

.

Integrating ChatGPT into a Blazor Server app can be done by following these steps

1.Create a new Blazor Server app in Visual Studio.

2.Choose a Project Name

3.Select the Framework:6.0

4.Project is created

5.Install a Package :OpenAI-DotNet(6.4.1)

6.ApiKey is Taken from Chatgpt

Output: Insert Text into TextBox And See the results

Access Modifiers in C#

“Access Modifiers are keywords in C# which are used to restrict avaibility of object,method,class and its members into the program or in application”.
These access modifiers are mainly used to define the scopes of types and members and prevent external programs from accidentally changing data.

Types of Access Modifiers in C# –

  • Public
  • Protected
  • Internal
  • Protected Internal
  • Private
  • Private Protected

Public Access Modifier-

The public access modifier allows unrestricted access to the class, method, or variable, including external code, from anywhere in the program.
Any code can access the class, method, or variable without restrictions.

Accessibility:
Any code in the same assembly or another assembly that references a type or member that has been declared public can access it.
The code is accessible to all classes.
The public members of a class can be accessed from any part of the code. As a result, they are the least safe. Any code logic can change the value, resulting in unexpected behaviour.So, extra care must be taken before making any object publicly available.

Protected Access Modifier-

The protected access modifier allows access to the class, method, or variable from within the class and any derived classes. It means that the class, method, or variable can be accessed by any code that is part of the class or any derived classes but not by external code.

Accessibility:

Protected members are only visible to their classes and their derived classes.
We can’t access protected members by the object of that class.

Internal Access Modifier-

The internal access modifier restricts access to the class, method, or variable within the same assembly.

Accessibility:

When a type or member is declared internal in C#, it can only be accessed by the current assembly and not by any other assemblies, according to the internal access modifier.

There is only current assembly access.

Example-

This example contains two files in two separate projects Program1.cs and Program.cs.  The first file contains an internal base class BaseClass. In the second file, an attempt to instantiate BaseClass will fail.

Protected Internal Access Modifier-

It is a combination of two other access modifiers: protected and internal.

The protected keyword means that a member (field, method, or property) is accessible only within its own class and any class derived from it. This means that the member is not accessible from outside the class or from non-derived classes.

The internal keyword means that a member is accessible within the same assembly (or module). This means that the member is not accessible from outside the assembly.

When you combine the protected and internal keywords using the protected internal modifier, you create a member that is accessible within its own assembly, as well as from any class that derives from the member’s class, whether the derived class is in the same assembly or not.

In other words, a protected internal member can be accessed from:

  • Any class within the same assembly.
  • Any derived class, regardless of whether it is in the same assembly or not.

Private Access Modifier-

It is used to restrict the access to a member (field, method, or property) to only the class in which it is declared. This means that the member cannot be accessed from outside the class, including any derived classes.

When you declare a member as private, it can only be accessed within the same class.

Accessibility:

The private keyword is just a member access modifier and cannot be explicitly used by classes or structures.
Nested types in the same body can also access these private members.
A compile-time error will be thrown when a private member is referenced outside of the class or structure in which it is declared.

Private Protected Access Modifier-

The private protected access modifier in C# is a combination of the private and protected access modifiers. It was introduced in C# 7.2 and is used to restrict access to a member to only the current class and any derived classes that are declared within the same assembly.

With the private protected access modifier, a member can only be accessed within its own class or any derived class that is declared within the same assembly. This means that it cannot be accessed from outside the assembly or from a derived class in a different assembly.

Unwrapping the Meaning and Differences Between Empathy, Sympathy, and Compassion in HR

As human resource professionals, empathy, sympathy, and compassion are essential skills to have in our toolkit, but they should be applied in different ways depending on the situation. These skills not only help us connect with our colleagues and employees but also play a crucial role to maintain objectivity, fairness in their decision-making and building a positive work culture.

Let’s understand empathy, sympathy, and compassion and how they differ from each other and how they can be applied in the context of Human Resources?

Empathy, sympathy, and compassion are three distinct concepts, although they are often used interchangeably. They all represent positive, altruistic traits, but they don’t refer to the exact same experience. It is helpful to consider the two distinct qualities of compassion: understanding what another is feeling, and the willingness to act to alleviate suffering for another. The following image visually distinguishes compassion from the similar experiences of empathy, sympathy:

What is empathy?

Empathy is the ability to understand and share the feelings of another person. It involves both emotional and cognitive components and is essential for building strong relationships and promoting social connection. Empathy is not the same as agreeing with someone or feeling the same way about a situation. It means putting yourself in someone else’s shoes and experiencing what they are feeling

One way to cultivate empathy is through mindfulness and active listening. This involves paying attention to the other person’s words and nonverbal cues, trying to see things from their perspective, and demonstrating understanding and validation of their feelings. For example, you might say something like, “I can see how that would be frustrating for you. I’m here to listen and see if there is anything I can do to help.”

Another way to practice empathy is through perspective-taking, which involves trying to understand and appreciate the thoughts, feelings, and experiences of others. This can be done through activities such as role-playing, where you imagine yourself in someone else’s shoes and try to understand their perspective.

What is sympathy?

Sympathy is the feeling of concern, sadness, or pity for someone else’s suffering or misfortune. It is a natural response to hearing about someone’s struggles and can be comforting to the person experiencing the hardship. While sympathy can also be a helpful quality for HR professionals to have. However, sympathy is a one-sided emotion and does not necessarily involve a deep understanding of the other person’s feelings or perspective.

What is compassion?

Compassion is a deeper form of empathy that involves not only feeling the other person’s pain but also being moved to take action to alleviate it. Compassion is a combination of empathy and action; it involves a desire to help and a willingness to take steps to do so. Compassion involves understanding the other person’s experience and perspective and taking action to support them.

How can empathy, sympathy, and compassion be applied in HR?

As HR professionals, it is essential to practice empathy, sympathy, and compassion in our daily interactions with colleagues and employees. This can involve actively listening to their concerns and trying to see things from their perspective, demonstrating understanding and validation of their feelings, and taking action to support them.

For example, if an employee comes to you with a concern about a difficult situation they are experiencing at work, empathy might involve actively listening to their concerns and trying to feel what a employee is feeling, while sympathy might involve trying to understand their feelings and compassion might involve not only expressing your concern and understanding of their feelings but also taking action to help them find a solution or support them in any way you can to relieve them from suffering.

In conclusion, empathy, sympathy, and compassion are critical skills for HR professionals to possess, and incorporating them into their daily work can have a positive impact on both the employees and the organization as a whole. Empathy involves the ability to truly understand and experience the emotions of others, while sympathy is a one-sided feeling of concern or pity, and compassion involves both feeling sympathy and a desire to help alleviate suffering. Moreover, practicing empathy, sympathy, and compassion can also help HR professionals better understand the needs of their employees and create programs and policies that align with those needs. This can result in better retention rates, increased job satisfaction, and improved overall company culture. It can also be helpful in conflict resolution, as understanding the other person’s perspective and emotions can help us address and resolve.

Mud Blazor

MudBlazor is an open-source UI component library for Blazor, a .NET web framework for building web applications using C# instead of JavaScript. MudBlazor provides a collection of reusable UI components such as buttons, forms, dialogs, and more that can be easily integrated into Blazor applications.

MudBlazor aims to simplify the development process of web applications by providing a set of pre-built UI components that can be easily customized and extended. It also follows the Material Design guidelines, providing a consistent and modern look and feel across all components.

Both Blazor and MudBlazor are good technologies, but they serve different purposes.

Blazor is a web framework for building web applications using C# and Razor syntax. It provides a rich set of features for building interactive and responsive web applications, such as components, routing, and data binding. Blazor can be used to build full-stack web applications that run entirely in the browser, or server-side web applications that run on the server and communicate with the client using SignalR.

MudBlazor, on the other hand, is an open-source UI component library for Blazor that provides a collection of reusable UI components that can be easily integrated into Blazor applications. It follows the Material Design guidelines, providing a consistent and modern look and feel across all components. MudBlazor can help developers create high-quality and responsive web applications more quickly and efficiently by providing a set of pre-built UI components that are easy to use and customize.

So, the choice between Blazor and MudBlazor depends on your specific needs and requirements. If you are building a web application from scratch and need a full-stack web framework with rich features, Blazor would be a good choice. If you are already using Blazor and need a set of pre-built UI components to enhance your application’s look and feel, MudBlazor would be a good choice.

To install and configure MudBlazor in your project, you can follow these steps

First

1. Install-Package MudBlazor

2. Go in solution explorer—>right click on project name —>Manage Nuget Package–>browse MudBlazor—>install it.

3. Configure the MudBlazor services: In the Startup.cs file, add the following code to the ConfigureServices method:

This will configure the MudBlazor services in your application.

4. Add the MudBlazor CSS files: MudBlazor uses its own set of CSS files that need to be added to your project. You can add these files by adding the following line to the head section of your _Host.cshtml file (for Blazor Server) or index.html file (for Blazor WebAssembly):

5. Also you can add these files by adding the following two lines to the bottom just above the closing </body> tag of your _Host.cshtml file.

6. Open up the Shared/MainLayout.razor page and add the following code to the end of the file.

<MudThemeProvider/>

<MudSnackbarProvider/>

7. Use MudBlazor components in your Razor pages: You can now start using MudBlazor components in your Razor pages. For example, to add a MudButton component to your page, you can use the following code:


8. Run your project: Build and run your project to see the MudBlazor components in action.

These are the basic steps to get started with MudBlazor 7.0 in your project.

MudBlazor's Advanced Features

MudBlazor also offers advanced features that can help developers create powerful and responsive user interfaces. Some of MudBlazor’s advanced features and how they can be used in real-world scenarios.

  1. Form Validation One of the most important features of a web application is form validation. MudBlazor offers built-in form validation functionality that allows developers to ensure that user inputs meet certain criteria. The library provides several validation rules such as required, email, URL, range, and more. Developers can also create custom validation rules by implementing the IValidator interface. MudBlazor provides visual feedback to users when validation fails, making it easy for them to correct their inputs.
  2. Theming MudBlazor’s theming feature allows developers to customize the appearance of components to fit their application’s branding. The library provides a default theme, but developers can override it by creating a custom theme. The theme can be customized by setting the colors, fonts, and sizes of different components. MudBlazor’s theming feature is based on CSS variables, making it easy for developers to apply their styles consistently throughout the application.
  3. Charts MudBlazor’s chart components allow developers to visualize data in a variety of formats, such as pie charts, bar charts, and line charts. The library provides several chart types, including DoughnutChart, BarChart, LineChart, and more. Developers can customize the appearance of charts by setting colors, labels, and other properties. MudBlazor’s chart components are based on Chart.js, a popular open-source charting library.
  4. Toasts MudBlazor’s toast component allows developers to display notifications or messages to users. The toast component is highly customizable, allowing developers to set the position, duration, and appearance of the notification. Developers can also set the type of the notification, such as success, warning, or error, to provide additional context.

In conclusion, MudBlazor offers several advanced features that can help developers create powerful and responsive user interfaces. From form validation to theming, localization, charts, and toasts, MudBlazor provides a rich set of tools to build modern and efficient web applications.

SignalR in Blazor

SignalR is a real-time web communication library that allows server-side code to send asynchronous notifications to client-side web applications, and it can be used with Blazor to create interactive and responsive web applications. Here’s an overview of how you can use SignalR with Blazor.

Create your app

  1. Start Vs and select Create a new Project

2. Create a new project And Search Blazor Server App in search box

3.Choose a name of the app

4.Configure your new project

5. Select .net 6 in the Framework and click Create button

Project is Created Successfully

  1. In Solution Explorer, right-click the ChatApp project and select Manage NuGet Packages.
  2. In the Manage NuGet Packages dialog, confirm that the Package source is set to nuget.org.
  3. With Browse selected, type Microsoft.AspNetCore.SignalR.Client in the search box.
  4. In the search results, select the Microsoft.AspNetCore.SignalR.Client package. Set the version to match the shared framework of the app. Select Install.
  5. If the Preview Changes dialog appears, select OK.
  6. If the License Acceptance dialog appears, select I Accept if you agree with the license terms.
Add a SignalR hub

Create a Hubs  folder and add the following ChatHub class

Add services and an endpoint for the SignalR hub

  1. Open the Program.cs file.
  2. Add the namespaces for Microsoft.AspNetCore.ResponseCompression and the ChatHub class to the top of the file:

Create a Models folder and create class UserMessage

Add Razor component code for chat

  1. Open the Pages/Index.razor file.
  2. Replace the markup with the following code:

Run the app

Dynamic Layout

In web development, layouts play a crucial role in creating a consistent user experience across all the pages of a website. A layout is the structural and visual framework of a web page that helps to organize and display its content. Dynamic layouts take this a step further by allowing the layout to adapt and change based on user interactions or other conditions. In this blog post, we’ll explore dynamic layouts and how they are implemented in Blazor, a web framework for building interactive client-side web UIs using .NET.

What is a Dynamic Layout?

A dynamic layout is a layout that can change based on certain conditions or user interactions. This can include changes to the structure or visual presentation of the layout. Dynamic layouts are used to create more interactive and personalized user experiences. For example, a dynamic layout can change based on the user’s device type, screen size, or other preferences.

Dynamic Layouts in Blazor

Blazor is a web framework that allows developers to build interactive client-side web UIs using .NET. Blazor supports dynamic layouts through its component model. Components in Blazor are reusable pieces of UI that can be composed together to form a complete web page. Components can be created with dynamic layouts that change based on user interactions or other conditions.

Blazor provides two types of components: Razor components and Blazor components. Razor components are built using the Razor syntax, which is a markup syntax for creating HTML templates. Razor components can contain C# code that is executed at runtime. Blazor components are built using the Blazor component model, which provides a more advanced set of features for building dynamic UIs.

Blazor components can contain dynamic layouts by using conditional logic to control the display of UI elements. For example, a Blazor component can show or hide different sections of a layout based on user interactions or other conditions. Blazor components can also dynamically change the style or layout of UI elements based on user interactions or other conditions.

To create a dynamic layout in Blazor, you can use a combination of Razor syntax and C# code. Here’s an example of a Blazor component that uses dynamic layouts to display different content based on user interactions:

@page “/dynamic-layout-example”

<h1>Dynamic Layout Example</h1>

@if (showDetails)

{

    <div class=”details”>

        <p>Details about the item.</p>

    </div>

}

<button @onclick=”ToggleDetails”>Show Details</button>

@code {

    private bool showDetails = false;

    private void ToggleDetails()

    {

        showDetails = !showDetails;

    }

}

In this example, the component contains an @if statement that checks the value of a boolean variable called showDetails. If showDetails is true, the component displays a section with details about the item. The ToggleDetails method is called when the user clicks the “Show Details” button, which toggles the value of showDetails.

Dynamic layouts in Blazor offer a lot of flexibility for building interactive and personalized user interfaces. Here are some additional features and techniques you can use to create dynamic layouts in Blazor:

Conditional CSS classes: You can apply different CSS classes to elements based on conditions in your Blazor component. This allows you to dynamically change the style of UI elements based on user interactions or other conditions. For example:

<div class=”@ (isHighlighted ? “highlighted” : “”)”>

  <p>Some text</p>

</div>

In this example, the highlighted CSS class is applied to the div element only if the isHighlighted variable is true.

Templated components: Blazor allows you to create components with templated content that can be customized at runtime. This is useful for creating reusable components that can be used in different contexts with different layouts.

For example:

<Counter>

  <p>Current count: @currentCount</p>

</Counter>

In this example, the Counter component has a template that includes a p element with the current count displayed. This allows the Counter component to be used in different contexts with different templates.

Event handling: Blazor components can handle user interactions through events such as onclick, onkeyup, or onsubmit. You can use these events to trigger changes to the layout or other components.

For example:

<button @onclick=”IncrementCount”>Click me</button>

<p>Count: @count</p>

@code {

  private int count;

  private void IncrementCount()

  {

    count++;

  }

}

In this example, the IncrementCount method is called when the user clicks the button, which increments the count variable and updates the UI.

Dynamic data binding: Blazor components support dynamic data binding, which allows you to bind UI elements to properties or variables in your component. This enables the UI to update automatically when the underlying data changes. For example:

<input type=”text” @bind-value=”@username” />

<p>Hello, @username</p>

@code {

  private string username;

}

In this example, the @bind-value directive binds the value of the input element to the username variable. When the user types into the input field, the username variable is updated automatically, and the greeting in the p element is updated accordingly.

In summary, dynamic layouts in Blazor provide a lot of flexibility for creating interactive and personalized web UIs. By using a combination of conditional logic, templated components, event handling, and dynamic data binding, you can create complex and dynamic UIs that adapt to user interactions and other conditions.

Conclusion

Dynamic layouts are a powerful tool for creating more interactive and personalized user experiences on the web. In Blazor, dynamic layouts can be created using a combination of Razor syntax and C# code in the form of components. By using dynamic layouts, developers can create more flexible and adaptable web pages that provide a better user experience for their audience.

LAMBDA EXPRESSION

Lambda Expressions

A lambda expression is a short block of code which takes in parameters and returns a value.
Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.
Lambda expressions are any expression that uses the operator =>, which we read aloud as “goes to”.

For example – num => num * 7

Here, num is an input parameter and num * 7 is a return value. The lambda expression does not execute on its own. Instead, we use it inside other methods or variables.

The Lambda Expressions can be of two types:

  1. Statement Lambda: Consists of the input and a set of statements to be executed.

Syntax:-
input => { statements };

Note: Does not return any value implicitly

  1. Expression Lambda: Consists of the input and the expression.

Syntax:-
input => expression;

Note: Returns the evaluated value implicitly

Lambda Expression in asp. net:-

C# 3.0 introduced the lambda expression. It is also works like an anonymous method.
The difference that in Lambda expressions you don’t need to specify the type of the value that you input thus making it more flexible to use. It means lambda expression simplifies the anonymous function or you can say that lambda expression is a shorthand for an anonymous function.
The => is the lambda operator which is used in all lambda expressions.
The Lambda expression is divided into two parts, the left side is the input and the right is the expression.

Use of Lambda Expression

Some of the uses of the lambda expression are:

  1. Writing Easy and Simple Delegate Code
    Using lambda expressions, we can write much easier and simpler code. Let’s see programs with and without using a lambda expression in a delegate.

Program Without Using Lambda Expression

In the above program, we have defined a delegate square of Func type that points to the Square() method.

Program With Using Lambda Expression

Here, we don’t need to define a separate method. We have replaced the pointer to the square() method with the lambda expression.
  1. Passing Parameter in Method
    We can pass a lambda expression as a parameter in a method call.

Let’s take a built-in Count() method of C# array and pass a lambda expression as its parameter.

In the above example, we have passed the lambda expression x => x == 13 as a method parameter.

Output-

The Count() method checks each element of the numbers array and counts the total number of 13 in the array.

Lambda Expression in Blazor-

Blazor is a web framework developed by Microsoft that allows developers to build web applications using C# and .NET instead of JavaScript. In ASP.NET, Blazor is typically used to build web applications with server-side rendering. Here are some examples of how lambda expressions can be used in Blazor in ASP.NET:

Event handlers:
In Blazor, you can use lambda expressions to define event handlers for components. For example: To handle an event in Blazor, you can use a lambda expression to define a method that will be called when the event occurs. Here’s an example of how to handle the “onclick” event of a button:

In the above code, the lambda expression () => HandleClick() defines a method that takes no parameters and calls the HandleClick() method when the button is clicked.

Data binding:
In Blazor, you can use lambda expressions for data binding to components. For example: you can bind a string variable to a component’s text property using a lambda expression:

Here, the lambda expression @(() => MyProperty) is used to bind the value of an input element to the MyProperty property.

Blazor

Introduction to Blazor

Are you tired of writing web applications in JavaScript? Are you a .NET developer looking for a way to create web applications using C#?

Look now further than Blazor! What it is ? and why so popular!

Blazor is a UI framework, it allows developers to design and develop interactive rich UI components with C#, HTML, CSS, plus it is open source and free. So technically now you can create web pages directly in C# instead of JavaScript. 

Blazor web application is nothing but a collection of web pagesor to be precise razor pages, then each razor page will host bunch of blazor components and get this, this blazor web application could run on both server or on client. Isn’t that cool?

In traditional architecture, server is designed with high level languages such as Java, C# and client is dominated by dynamic programming language such as javascript, now with blazor you can design both your server and client application in C#.

ASP.NET Core Blazor Hosting Models (Blazor WebAssembly and Blazor Server)
What is Blazor Server(Server side hosting model)?

With Blazor Server Hosting Model, the Blazor applications run on the server and the user interacts with the server through a SignalR connection. With SignalR we handle real-time communication that means with SignalR the client does not need to download the .NET Runtime, simply interact with the application remotely. As we don’t download the .NET Runtime in Blazor Server App to run the application, which makes the application serves on the server-side load faster for the user.

  • You might have played online games, those games run on a client machine or on a client browser but the data is coming from the server. So if you kill 3 enemies the counter is stored on the server, the moment you kill the 4th enemy counter increases to 4, that communication between server and client is so fast the user can hardly notice any lag. And this is enabled by SignalR in the blazor server app. So for every user interaction on browser signalR sends UI components and data from server to browser and then browser simply renders those changes.

 
In Blazor server app, UI components (razor components) are stored on the server. Every UI updates, event calls are handled by SignalR which sends the updated data/component to the browser on demand. In order to run app smoothly browser need to have consistent connection with server. The browser has script, blazor.server.js which establishes the SignalR connection with the server. 

Blazor Web assembly(client side hosting model)?

In Blazor WebAssembly Hosting Model, the application directly runs in the browser with the help of WebAssembly. So, the things which are required to run a .Net application such as the compiled application code, its dependencies, and the most important .NET runtime are downloaded to the client browser by WebAssembly from the server as shown in the below image.

  • Can work offline: As there is no server dependency, the client can work without being dependent on the server. so it doesn’t matter if you lose the connection with the server.
  • If you want an application that is supported by search engines, or has server-side support within the application, Blazor Server is your choice.

But, if you want an arguably quicker application that works offline, then you will be looking at Blazor WebAssembly.

Build your first Blazor app

  1. Start Visual Studio and select Create a new project.

2. In the Create a new project window, type Blazor on the search box and hit Enter.

3. Select the Blazor Server App template and select Next.

3. In the Configure your new project window, enter BlazorApp as the project name and select Next.

4.In the Additional information window, select .NET 7.0 (Standard Term Support) in the Framework drop-down if not already selected and click the Create button.

Your project is created and loaded in Visual Studio. Take a look at the contents of your project using Solution Explorer.

Several files were created to give you a simple Blazor app that is ready to run.

  • Program.cs is the entry point for the app that starts the server and where you configure the app services and middleware.
  • App.razor is the root component for the app.
  • The Pages directory contains some example web pages for the app.

     This folder contains the _Host razor page and the         routable components that make up the Blazor app. The   components have the .razor extension.

  • Index component (Index.razor) – Rendered when we navigate to the root application URL.
  • Counter component (Counter.razor) – Rendered when we navigate to the path /counter.
  • FetchData component (FetchData.razor) – Rendered when we navigate to the path /fetchdata.
  • Error component (Error.razor) – Rendered when an unhandled exception occurs in the blazor app.
  • BlazorApp.csproj defines the app project and its dependencies and can be viewed by double-clicking the BlazorApp project node in the Solution Explorer.
  • The launchSettings.json file inside the Properties directory defines different profile settings for the local development environment. A port number is automatically assigned at project creation and saved on this file.
MainLayout component (MainLayout.razor)

The application’s main layout component

NavMenu component (NavMenu.razor)

Implements the navigation menu on the sidebar. The NavLink component renders navigation links to other Razor components like the index, counter, and fetchdata components. This NavLink component is intelligent enough to highlight the navigation menu item if its component is currently displayed.

_Imports.razor

This is like _ViewImports.cshtml file in an asp.net core MVC project. This file contains the common namespaces so we do not have to include them in every razor component.

The data folder (Blazor Server)

Contains code files related to the sample WeatherForecast service

appsettings.json (Blazor Server)

Just like an asp.net core MVC project, a Blazor project also uses this file to store the configuration settings.

Run your app

Click on the Start Debugging button (green arrow) in the Debug Toolbar in Visual Studio to run your app. Wait for the app to launch in the browser. Once you get to the following page, you have successfully run your first Blazor app.

The displayed page is defined by the Index.razor file located inside the Pages directory. This is what its contents look like:

Pages/Index.razor

@page "/"

<PageTitle>Index</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

It already contains the code that sets it as the homepage and displays the text Hello, world! and Welcome to your new app. It also includes a SurveyPrompt component that renders a link to the Blazor feedback survey.


Try the counter


In the running app, navigate to the Counter page by clicking the Counter tab in the sidebar on the left. The following page should then be displayed:

Select the Click me button to increment the count without a page refresh. Incrementing a counter in a webpage normally requires writing JavaScript, but with Blazor you can use C#.

You can find the implementation of the Counter component at Counter.razor file located inside the Pages directory.

Pages/Counter.razorCopy

@page "/counter"

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

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

@code {

    private int currentCount = 0;

    private void IncrementCount()

    {

        currentCount++;

    }

}

A request for /counter in the browser, as specified by the @page directive at the top, causes the Counter component to render its content.

Each time the Click me button is selected:

  • The onclick event is fired.
  • The IncrementCount method is called.
  • The currentCount is incremented.
  • The component is rendered to show the updated count.

Add a component

Razor component is a combination of two things i.e. HTML code and C# code. For example, please have a look at the following Counter.razor file i.e. the Counter Component.

Each of the .razor files defines a UI component that can be reused.

Open the Index.razor file in Visual Studio. The Index.razor file already exists, and it was created when you created the project. It’s located in the Pages folder inside the BlazorApp directory that was created earlier.

Add a Counter component to the app’s homepage by adding a <Counter /> element at the end of the Index.razor file.

Pages/Index.razorCopy

@page "/"

<PageTitle>Index</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

<Counter />

Click the Hot Reload button to apply the change to the running app. The Counter component will then show up on the home page.

Modify a component

Component parameters are specified using attributes or child content, which allow you to set properties on the child component. Define a parameter on the Counter component for specifying how much it increments with every button click:

  • Add a public property for IncrementAmount with a [Parameter] attribute.
  • Change the IncrementCount method to use the IncrementAmount when incrementing the value of currentCount.

The following code shows how to achieve that. The highlighted lines show the changes.

Pages/Counter.razorCopy

@page "/counter"

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p>Current count: @currentCount</p>

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

@code {

    private int currentCount = 0;

    [Parameter]

    public int IncrementAmount { get; set; } = 1;

    private void IncrementCount()

    {

        currentCount += IncrementAmount;

    }

}

In Index.razor, update the <Counter> element to add an IncrementAmount attribute that changes the increment amount to ten as shown by the highlighted line in the following code:

Pages/Index.razorCopy

@page "/"

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

<Counter IncrementAmount="10" />

Apply the change to the app by clicking the Hot Reload button. The Index component now has its own counter that increments by ten each time the Click me button is selected, as shown in the following image. The Counter component (Counter.razor) at /counter continues to increment by one.