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.

Soft Skills: Mastery for Career Development

As a working Human resource professional, I realized that Soft skills have become a must-have quality in today’s corporate world and to-die-for skills for business leaders, human resource personnel, and individuals looking for professional development or employment.

Soft skills are termed as behavioral skills, and they represent all the skills that human beings possess and apply in a professional setting. Soft skills are also known as power skills, common skills, or core skills, are attributes that are applicable to all professions. These skills are often related to your ability to interact effectively with others.

Soft Skill Definition: What are they?

These are non-technical skills that influence how you work, interact with colleagues, manage your work, and approach problem solving. Some top-tier soft skills include listening skills, communication skills and interpersonal skills, among others.

When we hire a candidate, for example, a HR manager or Recruitment officer prefers candidates with soft skills. Employers recognize the importance of soft skills in the workplace, as they believe that having these skills can make an individual more successful and valuable. Simply being proficient in technical skills is not enough if one cannot effectively work in a team or manage time well.

Why are soft skills important?

While hard skills are important to employers, in a world where learning these quantifiable skills can be as simple as watching a quick video, soft skills have come into focus. While everyone applying to a job may know how to code or how to write, soft skills are what can help set you apart.

Soft skills make it easier to form relationships, create trust and dependability, and lead teams. Showing employers that you have mastered the right soft skills shows that you can handle whatever they throw at you, even if it’s a hard skill you don’t yet know.

List of essential soft skills you must have:

  • Communication

The ability to convey or share ideas and feelings effectively and it’s among the top soft skills employers require across all fields.  Alongside this is the necessary development of active listening – a technique where you focus on what the other person is saying rather than just waiting for your turn to speak.

  • Teamwork 

Teamwork will never cease to be a must-have soft skill. Employers want to see their employees excellent at teamwork to create a better operating work environment. The quality of work improves when people use their individual strengths and skills together in collaboration.

  • Adaptability

Adaptability shows how well you can embrace change and adjusts to it. Being flexible is an important soft skill. The workplace is always changing – there are constantly shifting trends. Employers will feel more comfortable if they have employees that can adapt to this change and are proactive in learning how to deal with it. Remain positive if there is a change and accept it rather than resist it. An employee that can work in this way is very valuable.

  • Problem solving

Finding effective solutions for work-related problems is a huge asset, as employers want to see you solving issues and keeping the organization moving forward. Being able to analytically and creatively solve problems will come in handy no matter your job. That is why creative problem-solvers are always in high demand. 

  • Critical thinking

The ability to think critically has become a hot topic for employers. Critical thinking is inextricably connected to both problem solving and decision making.  It always has a goal – usually, to solve a problem or come to a decision.

  • Creativity

Creativity comes in different forms, but the end result in a professional environment is usually an innovative solution for the organization. We’re used to linking creativity with fields like art, or design, but creativity is a broad term that involves several sub-skills from questioning to experimenting. As such, any professional can make just as much use of creative skills as artists.

  • Time Management

The essence of time management in corporate culture is immense. Time management involves the ability to use your time wisely to work as efficiently as possible. Besides, every time you perform a task on time, you enhance your growth chances. It would not be wrong to say that time management is one of the ladders to success. 

  • Leadership

Effective leadership means getting the best out of the people around you and bringing diverse skills and personalities together in pursuit of a common goal. Employers prefer to hire applicants who show they have leadership potential for 2 reasons:

1. Employees with leadership skills show more initiative and are more likely to invest themselves in helping the company grow.

2. The company can eventually promote employees with strong leadership roles to better management positions.

  • Work Ethics

Workplace ethics are an incredibly important part of forming a successful organization with satisfied and loyal team members. Work ethic relates to valuing work and putting in the effort to yield results. It’s a soft skill that employers in literally every job you’ll ever apply for will appreciate.

  • Digital literacy

Being digital Literate means knowing how to use technology to create, find, use in a productive manner to communicate. Employers are looking for people who can pick up any digital tool quickly like a new task. With digital literacy skills, you’re telling an employer it doesn’t matter if you’ve used a specific tool before because you can learn quickly.

Conclusion:

Soft skills are universally needed in today’s workforce for any job profile. Learn to cultivate yours and display them for employers to see – and you’ll keep yourself ahead of the pack. Think of your soft skills as accessories to your hard, job-related skills. They alone cannot qualify you for a job, but when paired with solid credentials they can make you a much more attractive candidate. Soft skills help you to strive for excellence in your workplace, as they help you to work more effectively and efficiently, thus, yielding excellent results. These skills are a prerequisite for building a healthy productive environment.  These skills not only boost your personality but also accelerate your career development process.

ASP.NET Core MVC(.NET6) CRUD Operations using EntityFrameworkCore

MVC stands for Model-View-Controller, it’s a software architectural pattern that separates an application into three main components: Model, View and Controller. The Model represents the data and business logic of the application, the View is responsible for rendering the data into a user interface and the Controller handles user interactions and updates the Model accordingly.

Step-1 Open Visual Studio and click on Create New Project

Step-2 Select ASP.NET Core Web App (Model-View-Controller) and click next button

Step-3 Enter the project name and click on next button

Step-4 Select .Net 6.0 , authentication type None and click on create button

Step-5 Open Models folder and create a Employee class

Enter the following code in the student class

Step-6 Install the following packages according to your .NET Core version

Step-7 Create a subclass ApplicationDbContext of DBContext Class to link the database with data model class

A. Create one folder and name it Data

B. Create ApplicaitonDbContext class and enter the following code

In the above code we are passing parameter DbContextOptions<ApplicationDbContext> using constructor, Using this we are passing context configuration from AddDbContext to DbContext

Step-8 Open appsettings.json and configure the connection string

Step-9 Open the program.cs file and add the required services

A. Register ApplicationDbContext subclass as scoped service in application service provider / dependency injection container.

B. Enter the following lines of code to register the ApplicaitonDbContext

Program.cs

Step-10 Run the migration

A. Open the package manager console

Type the following command to run the migration

add-migration ‘initial’

Migration file

Step-11 Run the following update command to update the database as per this migration file

update-database

Step-12 Add Employee Controller

A. Right click on Employee folder

B. Click on add

C. Click on controller

D. Select MVC Controller Empty and click on Add button

E. Enter the Controller name and press add button

Step-13 Paste the following code in your StudentControler.cs file

Step-14 Add view files

Create one Student folder under View folder and create the following files

A. Index.cshtml

B. Create.cshtml

C. Edit.cshtml

D. Delete.cshtml

Index.cshtml

@model IEnumerable<StudentInformation.Models.Studentcs>
<div class="container">
    <div class="row">
        <div class="col-8 offset-2 mb-2">
            <h1 class="text-center text-primary"><marquee>Student Record</marquee></h1>
            <div class="text-left">
            <a class="btn btn-outline-success text-left" asp-controller="Student" asp-action="Create">Create</a>
            </div>
        </div>
        <table class="table table-bordered">
            <tr class="text-center">
                <th>StudentId</th>
                <th>Name</th>
                <th>Standard</th>
                <th>Address</th>
                <th>Hobby</th>
                <th>Action</th>
            </tr>
            @foreach(var d in Model)
            {
                <tr class="text-center">
                <td>@d.Id</td>
                <td>@d.Name</td>
                <td>@d.Standard</td>
                <td>@d.Address</td>
                <td>@d.Hobby</td>
                <td>
                    <a class="btn btn-outline-primary"asp-controller="Student"asp-action="Edit"asp-route-id="@d.Id">Edit</a>
                    <a class="btn btn-outline-danger" asp-controller="Student"asp-action="Delete" asp-route-id="@d.Id" onclick="javascript: return CheckConfirm();">Delete</a>
                </td>
                </tr>
            }
        </table>
    </div>
</div>

Create.cshtml

@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}
@model StudentInformation.Models.Studentcs

<div class="conatiner">
    <div class="row">
        <div class="col-6 offset-3">
            <div class="card">
                <div class="card-header">
                    <h1 class="text-center" text-primary>Add Student</h1>
                </div>

                <form method="post" asp-action="Create">
                    <div class="form-group">
                        <label asp-for="Name"></label>
                        <input type="text" asp-for="Name" class="form-control" placeholder="Enter student name">
                        <label asp-for="Standard"></label>
                        <input type="text" asp-for="Standard" class="form-control" placeholder="Enter student standard">
                        <label asp-for="Address"></label>
                        <input type="text" asp-for="Address" class="form-control" placeholder="Enter student address">
                        <label asp-for="Hobby"></label>
                        <input type="text" asp-for="Hobby" class="form-control" placeholder="Enter student hobby">
                    </div>
                    <div class="form-group">
                        <input type="submit" value="submit" class="btn btn-sm btn-outline-success floatright mt-2" />
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

Edit.cshtml


@model StudentInformation.Models.Studentcs
<div class="conatiner">
    <div class="row">
        <div class="col-6 offset-3">
            <div class="card">
                <div class="card-header">
                    <h1 class="text-center" text-primary>Edit Employee</h1>
                </div>

                <form method="post" asp-action="Edit">
                    <div class="form-group">
                        <label asp-for="Name"></label>
                        <input type="hidden" asp-for="Id"/>
                        <input type="text" asp-for="Name" class="form-control" placeholder="Enter student name">
                          <label asp-for="Standard"></label>
                         <input type="text" asp-for="Standard" class="form-control" placeholder="Enter student Standard">
                          <label asp-for="Address"></label>
                         <input type="text" asp-for="Address" class="form-control" placeholder="Enter student Address">
                           <label asp-for="Hobby"></label>
                         <input type="text" asp-for="Hobby" class="form-control" placeholder="Enter student Hobby">
                    </div>
                    <div class="form-group">
                        <input type="submit"value="submit"class="btn btn-sm btn-outline-success floatright" />
                    </div>
                </form>
            </div>
        </div>
    </div

Step-15 Finally run the app and test all functionalities

API & REST API

What is an API?

Api is short for Application Programming Interface. It is used in computer programs to communicate with other applications and/or services.
It acts as a bridge between different softwares and devices.
Each time we use an app like Facebook or Instagram, send an instant message or check the weather on our phone, we use nothing but an API.

Everything from sharing photos to shopping online, booking a cab, a flight or a hotel, playing games is all done via APIs.
It is API because the technology is innovating at a faster than the predicted rate.

If we look at the below diagram, which is a basic information flow diagram depicting the position of an Application Programming Interface in the whole schema of system integration.

Importance of API is –

When we search for nearby restaurants on any browser, it lays out their locations on Google Maps instead of creating separate maps.
Thus, via the Google Map API, the browser passes the information it wants – restaurant addresses, rating, timings, and a lot more –
to an internal Google Maps function that then returns a Map object with restaurant pins in it at the proper locations.
It allows programmers to create apps without having to learn how to code.

Take some examples –

So let’s take Instagram for example. When you open up Instagram, there’s this bar at the top of the screen where you can search through different hashtags or accounts. There’s also another bar at the bottom which has these buttons like “Follow”, “Like” etc. These are all links to third

Why Should You Use APIs?

It is easy to understand that APIs can allow different computer programs to share or request features, services, and other content.
Suppose you think that why different businesses are using APIs comes down to the range of benefits of APIs to consumers and providers.
The API consumers can request access to different server resources or automate different tasks internally.

Advantages of API –

The key advantages of APIs to consumers include improved operations, increased innovation, and improved customer satisfaction.
It is easy to unlock business opportunities and increase business revenue.

Rest API?

REST stands for Representational State Transfer.
So, REST means using HTTP (HyperText Transport Protocol) to transfer resources such as HTML documents, images, audio files,
A REST API is a web service (a server) which accepts requests from client applications using HTTP (HyperText Transfer Protocol).
The clients use a common protocol such as XML or JSON to send data to the server.
The server processes the request, generates a response and sends it back to the client.

Methods of Rest Api –

GET –

The GET method is used to retrieve resources from a server.
Example – HTTP GET ‘http://www.apidomain.com/users/123’

POST –

POST method is used to create a new resource into the collection of resources on a server.
Example – HTTP POST ‘http://www.apidomain.com/users’

PUT –

PUT is used to update the existing resource on the server and it updates the full resource.
Example – HTTP PUT ‘http://www.apidomain.com/users/123’

PATCH –

PATCH is used to update the existing resource on the server and it updates a portion of the resource.
Example – HTTP PATCH ‘http://www.apidomain.com/users/123’

DELETE –

DELETE Method is used to delete the resources from a server. It deletes resource identified by the Request-URI.

Creating a Web API Project

We need the following tools installed on our computer:

Open Visual Studio 2022 and select Create a new project and then select ASP.NET Core Web API:

and give a name to your project in the following screen and then click Next.

In the next screen, select .NET 6.0 as the framework and click Create:

At this point we have a starter project as follows:

In the Program.cs we see that Swagger support is added automatically to our project:

Now, let’s run (Ctlr+F5) the project to see the default output. When the browser opens and the Swagger UI is shown, select the GET method in the WeatherForecast part and then select Try It Out and Execute:

Also, you can use the curl URL shown in the Swagger UI for this method and see the result of the URL in the browser:

When we run the application, the default URL comes from the launchSettings.json:

And the result values come from the GET method of the WeatherForecastController:

As you see, values here are hard coded and randomness is added to generate different values.

In our Web API, we will create our own records in an SQL server database and will be able to view, update and delete them through REST API endpoints.

If you feel my blogs are useful then please share, follow and comment on it. Also, you can connect with me over linkedIn: https://www.linkedin.com/in/neeni-bharti-b64b9a252/