Sunday, 27 March 2022

Enable tracing in WCF

 Put this section anywhere below configSections in web.config

<system.diagnostics>
    <sources>
      <source propagateActivity="true" name="System.ServiceModel" switchValue="Warning, Critical, Warning">
        <listeners>
          <add type="System.Diagnostics.DefaultTraceListener" name="Default">
            <filter type="" />
          </add>
          <add initializeData="trace.svclog"
            type="System.Diagnostics.XmlWriterTraceListener" name="sdt"
            traceOutputOptions="None">
            <filter type="" />
          </add>
        </listeners>
      </source>
      <source name="System.ServiceModel.MessageLogging" switchValue="Warning,ActivityTracing">
        <listeners>
          <add type="System.Diagnostics.DefaultTraceListener" name="Default">
            <filter type="" />
          </add>
          <add name="ServiceModelMessageLoggingListener">
            <filter type="" />
          </add>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add initializeData="web_messages.svclog"
        type="System.Diagnostics.XmlWriterTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
        name="ServiceModelMessageLoggingListener" traceOutputOptions="Timestamp">
        <filter type="" />
      </add>
    </sharedListeners>
    <trace autoflush="true" />
  </system.diagnostics>

---------------------------------------------------

Put this under system.ServiceModel section

<system.serviceModel>

 <diagnostics performanceCounters="Default">
      <messageLogging logEntireMessage="true" logKnownPii="true" logMalformedMessages="true"
        logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" />
      <endToEndTracing propagateActivity="true" activityTracing="true"
        messageFlowTracing="true" />

 </diagnostics>

</system.serviceModel>

using wsHttpBinding in WCF

<System.ServiceModel>
    <bindings>
        <wsHttpBinding>
            <binding name="wsHttpBinding"
                     openTimeout="10:01:00"
                     receiveTimeout="10:01:00"
                     sendTimeout="10:01:00"
                     maxBufferPoolSize="2147483646"
                     maxReceivedMessageSize="2147483646" />
        </wsHttpBinding>
    </bindings>
    <Services>
        <service behaviorConfiguration="BehaviorRelease" name="Halfpenny.InternalService.MasterService">
            <clear />
            <endpoint address="/ws" binding="wsHttpBinding"
              bindingConfiguration="wsHttpBinding" name="wsHttpBinding" contract="Halfpenny.Service.Contract.IMasterService" />
            <host>
                <baseAddresses>
                    <add baseAddress="http://localhost:59429/MasterService/" />
                </baseAddresses>
            </host>
        </service>
    </Services>
</System.ServiceModel>

Tuesday, 22 March 2022

ViewStart.cshtml in ASP.NET Core MVC

 # _ViewStart.cshtml in ASP.NET Core MVC

1. We use the Layout property to associate a view with a layout view. Without the _ViewStart.cshtml file, we set the Layout property in each and every view. This violates DRY (Don't Repeat Yourself) principle, and has the following disadvantages
    Redundant code.
    Maintenance overhead.
2. It's a special file in ASP.NET Core MVC. The code in this file is executed before the code in an individual view is executed. So this means, instead of setting the Layout property in each individual view, we can move that code into the _ViewStart.cshtml file.
@{
    Layout = "_Layout";
}
3. By setting the Layout property in _ViewStart.cshtml file maintaining our application becomes much easier. In the future, if we want to use a different layout file we just need to change the code in one place in _ViewStart.cshtml.
4. If you want to use a layout file that is different from what is specified in _ViewStart.cshtml, you can do so by setting the Layout property in an individual view. You can also set the Layout property to null, if you want your view to be rendered without a layout view.
5. We can also have different ViewStart file. Store it in different views folder. Only views present in that folder will get affected due to this.

Views in Asp.net core MVC

 # Views in Asp.net core MVC

1. return View()
    - asp.net mvc core looks for the view with name equal to 'action name'
       public ViewResult Details()
        {
            return View();
        }
        In this example it will try to load Details View in folder <Controller>Views\<Action>name
2. View(string viewName) method
    - It will try to load view with the name 'viewName'
    return View("Test");
    - it will look for view 'Test.cshtml'
3. Specifying view file path
    - return View("MyViews/Test.cshtml");
4. Relative View File Path
    - return View("../Test/Update");
5. View(object model) pass model data
6. View(string viewName, object model)     Pass both the view name and model data.

## Passing data to view in ASP.NET Core MVC

1. there are 3 ways to pass data from a controller to a view
    - Using ViewData - loosely typed view
    - Using ViewBag - loosely typed view
    - Using a strongly typed model object. This is also called Strongly typed view.

## Using ViewData to pass Data from a Controller to a View

1. in controller  ViewData["PageTitle"] = "Employee Details";
2. Accessing ViewData in a View  
    -  <h3>@ViewData["PageTitle"]</h3>


ViewImports file

 # ViewImports file

1. _ViewImports.cshtml file is usually placed in the Views folder. It is used to include the common namespaces so we do not have to include them in every view that needs those namespaces.  
2. Just like, _ViewStart file, _ViewImports file is also hierarchical. In addition to placing it in the Views folder, we can also place another _ViewImports in the "Home" sub-folder in the Views folder.

view data vs ViewBag vs strongly typed binding

 # view data vs ViewBag vs strongly typed binding

## ViewData

1. ViewData is a dictionary of weakly typed objects.
2. To store and retrieve data from the ViewData dictionary we use string keys.
3. String data can be accessed from ViewData dictionary without the need to cast the data to string type.
4. If we are accessing any other type of data, we need to explicitly cast it to the type we are expecting.
5. ViewData is dynamically resolved at runtime, so it does not provide compile-time type checking and as a result we do not get intellisense.
6. Since we do not have intellisense, the speed at which we write code is reduced and the chances of mis-spelling and making typographical errors are also high.
7. We will only come to know about these errors at run time.
8. For this reason we usually do not use ViewData.

## ViewBag

1. With ViewBag we use dynamic properties instead of string keys.
    - in controller, ViewBag.Employee = model;
    - using ViewBag in view, @ViewBag.Employee.Name
2. Even ViewBag creates loosely typed view
3. Both ViewData and ViewBag does not provide compile-time type checking and as a result we do not get intellisense
4. We will only come to know about these errors at run time.

## Strongly typed view

1. Controller Code
     public ViewResult Details()
    {
        Employee model = _employeeRepository.GetEmployee(1);
        ViewBag.PageTitle = "Employee Details";
        return View(model);
    }
2. In View
     @model EmployeeManagement.Models.Employee
   <h3>@ViewBag.PageTitle</h3>
3. Unlike ViewData and ViewBag, a strongly typed view provides compile-time type checking and intellisense.
4. With intellisense support we can be more productive and the chances of mis-spelling and making typographical errors are almost nill.
5. If we do make any errors we will come to know about them at compile time rather than at runtime. So always use a strongly typed view to pass data from a controller to a view.

## ViewModel

1. In some cases, a model object may not contain all the data a view needs. This is when we create a ViewModel. It contains all the data a view needs.
2. eg  
namespace EmployeeManagement.ViewModels
{
    public class HomeDetailsViewModel
    {
        public Employee Employee { get; set; }
        public string PageTitle { get; set; }
    }
}
3. Please note, @model directive has a lowercase "m" and @Model property has a capital letter "M"


UserClaims and Policy based authorization

 # UserClaims and Policy based authorization

1. we create policy using
     services.AddAuthorization(options =>
    {
        options.AddPolicy("DeleteRolePolicy",
            policy => policy.RequireClaim("Delete Role"));
    });
2. Using Claims Policy for Authorization Checks
     [HttpPost]
    [Authorize(Policy = "DeleteRolePolicy")]
    public async Task<IActionResult> DeleteRole(string id)
    {
        // Delete Role
    }
3. Adding Multiple Claims to Policy
    services.AddAuthorization(options =>
    {
        options.AddPolicy("DeleteRolePolicy",
            policy => policy.RequireClaim("Delete Role")
                            .RequireClaim("Create Role") .RequireRole("Super Admin")
                        
            );
    });
4. A claim is a name-value pair. It's really a piece of information about the user, not what the user can and cannot do. For example username, email, age, gender etc are all claims.
5. Claims are policy based. We create a policy and include one or more claims in that policy. The policy is then used along with the policy parameter of the Authorize attribute to implement claims based authorization.
6. Claims based authorization is relatively new and is the recommended approach. With it we can also use claims from external identity providers like Facebook, Google, Twitter etc. We will discuss using external identity providers and the claims they provide in our upcoming videos.
7. Role based authorization is still supported in asp.net core for backward compatibility. While Claims based authorization is the recommended approach, depending on your application authorization requirements you may use role based authorization, claims based authorization or a combination of both.

Tag helpers

 # Tag helpers

1. Tag Helpers are server side components. They are processed on the server to create and render HTML elements in Razor files.
2. There are many built-in Tag Helpers for common tasks such as generating links, creating forms, loading assets etc.
3. To make the built-in tag helpers available for all the views in our entire application, import the tag helpers using _ViewImports.cshtml file. To import tag helpers we use @addTagHelper directive.

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

4. Generating Links using Tag Helpers
    manual:  <a href="/home/details/@employee.Id">View</a>
    using tag helper: @Html.ActionLink("View", "details", new { id = employee.Id })

    manual: <a href="/hom/details/5">View</a>
    using tag helper: @Url.Action("details", "home", new { id = employee.Id })

    manual: <a href="/Home/details/5">View</a>
    using tag helper: <a asp-controller="home" asp-action="details" asp-route-id="@employee.Id">View</a>

## Environment Tag Helpers

1. This example loads the non-minified bootstrap css file, if the application environment is "Development"

<environment include="Development">
    <link href="~/lib/bootstrap/css/bootstrap.css" rel="stylesheet" />
</environment>

2. This example loads the minified bootstrap css file from the CDN (Content Delivery Network), if the application environment is "Staging" or "Production".

<environment include="Staging,Production">
    <link rel="stylesheet"
            href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
            integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
            crossorigin="anonymous">
</environment>

3. Like include on environment tag helper we also have exclude parameter
This example loads the minified bootstrap css file from the CDN (Content Delivery Network), if the application environment IS NOT "Development".

<environment exclude="Development">
    <link rel="stylesheet"
            href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
            integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
            crossorigin="anonymous">
</environment>

4. If the CDN is down or for some reason, our application is not able to reach the CDN, we want our application to fallback and load the minified bootstrap file (bootstrap.min.css) from our own application web server. Consider the following example

<environment include="Development">
    <link href="~/lib/bootstrap/css/bootstrap.css" rel="stylesheet" />
</environment>

<environment exclude="Development">
    <link rel="stylesheet"
            integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
            crossorigin="anonymous"
            href="https://sstackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
            asp-fallback-href="~/lib/bootstrap/css/bootstrap.min.css"
            asp-fallback-test-class="sr-only" asp-fallback-test-property="position"
            asp-fallback-test-value="absolute"
            asp-suppress-fallback-integrity="true" />
</environment>
The following 3 attributes and their associated values are used to check if the CDN is down
asp-fallback-test-class="sr-only"
asp-fallback-test-property="position"
asp-fallback-test-value="absolute"


Static Files

 # Static files

1. By default, an asp.net core application will not serve static files
2. The default directory for static files is wwwroot and this directory must be in the root project folder
2. Middleware which serves static files
   // Add Static Files Middleware
    app.UseStaticFiles();
    
## Serving Default document

1. // Add Default Files Middleware
    app.UseDefaultFiles();    
2. The following are the default files which UseDefaultFiles middleware looks for
index.htm
index.html
default.htm
default.html

## Directory Browsing middleware

1. DirectoryBrowser middleware, enables directory browsing and allows users to see files within a specified directory.

Routing

 # Routing

1. There are 2 routing techniques in ASP.NET Core MVC. Conventional Routing and Attribute Routing.
2. Default Route in ASP.NET Core MVC, is defined using method
 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseStaticFiles();
    app.UseMvcWithDefaultRoute();
}
This is what configured using above method
{controller=Home}/{action=Index}/{id?}
3. http://localhost:1234/Employees/Details/1
In the above example

Path Segment     Maps to
/Employees     EmployeesController class
/Details     Details(int id) action method
/1     id parameter of the Details(int id) action method

4. Attribute routing
  app.UseMvc();
    - With attribute routing, we use the Route attribute to define our routes. We could apply the Route attribute on the Controller or on the Controller Action Methods.
     [Route("")]
    [Route("Home")]
    [Route("Home/Index")]
    public ViewResult Index()
    {
        return View();
    }
    - With these 3 route templates in place, the Index() action method of the HomeController will be executed for any of the following 3 URL paths.
    /
    /Home
    /Home/Index
5. To make the route parameter "id" optional, simply include a "?" at the end.
    [Route("Home/Details/{id?}")]
    // ? makes id method parameter nullable
    public ViewResult Details(int? id)
6. Controller and Action Method Names
With attribute routing the controller name and action method names play no role in which action is selected. Consider the example below.
public class WelcomeController : Controller
{
    [Route("")]
    [Route("Home")]
    [Route("Home/Index")]
    public ViewResult Welcome()
    {
        return View();
    }
}
Since we have specified the route template directly on the action method, Welcome() action in the WelcomeController is executed for all the following 3 URL paths.
/
/Home
/Home/Index
7. To make attribute routing less repetitive, route attributes on the controller are combined with route attributes on the individual action methods.

8. Tokens in Attribute Routing
Attribute routes support token replacement by enclosing a token in square-braces ([ ]). The tokens [controller] and [action] are replaced with the values of the controller name and action name where the route is defined.

Repository Pattern

 # Repository Pattern

1. Repository Pattern is an abstraction of the Data Access Layer. It hides the details of how exactly the data is saved or retrieved from the underlying data source.
2. The details of how the data is stored and retrieved is in the respective repository.
3. For example, you may have a repository that stores and retrieves data from an in-memory collection. You may have another repository that stores and retrieves data from a database like SQL Server.


## Repository Pattern Interface specifies

1. What operations (i.e methods) are supported by the repository
2. The data required for each of the operations i.e the parameters that need to be passed to the method and the data the method returns
3. The repository interface contains what it can do, but not, how it does, what it can do
4. The implementation details are in the respective repository class that implements the repository Interface

## Benefits of Repository Pattern

1. The code is cleaner, and easier to reuse and maintain.
2. Enables us to create loosely coupled systems. For example, if we want our application to work with oracle instead of sql server, implement an OracleRepository that knows how to read and write to Oracle database and register OracleRepository with the dependency injection system.
3. In an unit testing project, it is easy to replace a real repository with a fake implementation for testing.


Project File

 # Project file

1. .net Core project file no longer contains file or folder reference
    - all files and folder present within the root folder by default part of project
2.    TargetFramework  - specifies the .net core version project belongs to, eg netcoreapp2.2
3. AspNetCoreHostingModel
    - This element specifies how the asp.net core application should be hosted.
    - Should it be hosted InProcess or OutOfProcess.
    - The value of InProcess specifies that we want to use in-process hosting model i.e host our asp.net core app inside of the IIS worker process (w3wp.exe)
    - The value of OutOfProcess specifies that we want to use out-of-process hosting model i.e forward web requests to a back-end ASP.NET Core app running the Kestrel server.
4.    PackageReference
    - Microsoft.AspNetCore.App : This NuGet package is called metapackage. A metapackage has no content of its own but is a list of dependencies (other packages).

Model Binding & Validation

 # Model Binding & Validation

1. Model binding maps data in an HTTP request to controller action method parameters
2. The action parameters may be simple types such as integers, strings, etc or complex types like Customer, Employee, Order etc.
3. Model binding is great, because without it we have to write lot of custom code to map request data to action method parameters which is not only tedious but also error prone.
4. To bind the request data to the controller action method parameters, model binding looks for data in the HTTP request in the following places in the order specified below.

    Form values
    Route values
    Query strings
    
## Model validation

1. Use ModelState.IsValid property to check if validation has failed or succeeded
If validation has failed we return the same view so the user can provide the required data and resubmit the form.
 public IActionResult Create(Employee employee)
{
    if (ModelState.IsValid)
    {
        Employee newEmployee = _employeeRepository.Add(employee);
        return RedirectToAction("details", new { id = newEmployee.Id });
    }
    return View();
}

## Displaying Model Validation Errors

1. To display a summary of all validation errors use asp-validation-summary tag helper on a <div> element as shown below.

<div asp-validation-summary="All">
</div>

## ASP.NET Core Built-in Model Validation Attributes

The following are some of the common built-in validation attributes in ASP.NET Core
Attribute     Purpose
Required     Specifies the field is required
Range     Specifies the minimum and maximum value allowed
MinLength     Specifies the minimum length of a string
MaxLength     Specifies the maximum length of a string
Compare     Compares 2 properties of a model. For example compare Email and ConfirmEmail properties
RegularExpression     Validates if the provided value matches the pattern specified by the regular expression

## Display Attribute

1. If you want the label to display Office Email instead, use the Display attribute
  [Display(Name = "Office Email")]
    public string Email { get; set; }
    
## Using Multiple Model Validation Attributes

1.  [Display(Name = "Office Email")]
    [RegularExpression(@"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$",
        ErrorMessage = "Invalid email format")]
    [Required]
    public string Email { get; set; }
    

Misc

 # Misc

## .Net Core CLI

1. The .NET Core CLI is a cross-platform tool for developing .NET core applications
2. Using the CLI we can

    - Create a new project, configuration file, or solution based on the specified template
    - Restore the dependencies and tools required for a .net core project
    - Build a project and all of its dependencies
    - Run a project etc...
    
## Can we run an asp.net core application without using the built in kestrel web server.

The answer is YES. If we use the InProcess hosting model, the application is hosted inside of the IIS worker process (w3wp.exe or iisexpress.exe). Kestrel is not used with InProcess hosting model.

## Environment Variable

1. If we have not explicitly set ASPNETCORE_ENVIRONMENT variable, it defaults to Production. This is done on purpose for better security and performance.

## Useful methods of IHostingEnvironment service

    - IsDevelopment()
    - IsStaging()
    - IsProduction()

Middleware in Asp.net Core

 # Middleware in Asp.net Core

1. In ASP.NET Core, Middleware is a piece of software that can handle an HTTP request or response. A given middleware component in ASP.NET Core has a very specific purpose.
2. For example we may have a middleware component that authenticates a user, another piece of middleware to handle errors, yet another middleware to serve static files such as JavaScript files, CSS files, Images etc.
3. The request pipeline is configured as part of the application startup by the Configure() method in Startup.cs file.
4. By default empty project template sets up a very simple request processing pipeline with just two pieces of middleware.
    - UseDeveloperExceptionPage is one middleware and the second middleware is setup using the Run() method.
5. In ASP.NET Core, a Middleware component has access to both - the incoming request and the outgoing response. So a Middleware component may process an incoming request and pass that request to the next piece of middleware in the pipeline for further processing.
6. A middleware component may handle the request and decide not to call the next middleware in the pipeline. This is called short-circuiting the request pipeline. Short-circuiting is often desirable because it avoids unnecessary work.
    - For example, if the request is for a static file like an image or css file, the StaticFiles middleware can handle and serve that request and short-circuit the rest of the pipeline. This means in our case, the StaticFiles middleware will not call the MVC middleware if the request is for a static file.
7. A middleware component may also process the outgoing response. For example, the logging middleware component may log the time the response is sent. In addition it may also calculate the over all time taken to process the request by computing the difference between request received and response sent times.
8. Middleware components are executed in the order they are added to the pipeline. Care should be taken to add the middleware in the right order, otherwise the application may not function as expected.
9. The middleware components are available as NuGet packages. This means updates are now handled by NuGet, providing the ability to update each middleware separately.

## Run middleware

1. a middleware that is registered using the Run() method cannot call the next middleware in the pipeline
2. So, the middleware that we register using Run() method is a terminal middleware
3. If you want your middleware to be able to call the next middleware in the pipeline, then register the middleware using Use() method as shown below.

app.Use(async (context, next) =>
{
    await context.Response.WriteAsync("Hello from 1st Middleware");
    await next();
});
app.Run(async (context) =>
{
    await context.Response.WriteAsync("Hello from 2nd Middleware");
});
4. Notice, Use() method has 2 parameters. The first parameter is the HttpContext context object and the second parameter is the Func type i.e it is a generic delegate that represents the next middleware in the pipeline.

## if u want to understand how same middleware handles request and response. See below code.
 public void Configure(IApplicationBuilder app, IHostingEnvironment env,
                ILogger<Startup> logger)
{
    app.Use(async (context, next) =>
    {
        logger.LogInformation("MW1: Incoming Request");
        await next();
        logger.LogInformation("MW1: Outgoing Response");
    });

    app.Use(async (context, next) =>
    {
        logger.LogInformation("MW2: Incoming Request");
        await next();
        logger.LogInformation("MW2: Outgoing Response");
    });

    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("MW3: Request handled and response produced");
        logger.LogInformation("MW3: Request handled and response produced");
    });
}

Main method

 # Main method

1. As the name specifies this is entry point for .net core application
2. This Main() method configures asp.net core and starts it and at that point it becomes an asp.net core web application.
3. Main() method calls CreateWebHostBuilder() method passing it the command line arguments. As you can see, CreateWebHostBuilder() method returns an object that implements IWebHostBuilder.
4. On this object, Build() method is called which builds a web host that hosts our asp.net core web application.
5. on the web host Run() method is called, which runs the web application and it begins listening for incoming HTTP requests.

## CreateWebHostBuilder() method

1. method calls CreateDefaultBuilder() static method of the WebHost class.
2. CreateDefaultBuilder() method creates a web host with pre-configured defaults.
3. As part of setting up a web host, Startup class is also configured using the UseStartup() extension method of IWebHostBuilder class.

## This CreateDefaultBuilder() method performs several tasks like
    
    1. Setting up the web server
    2. Loading the host and application configuration from various configuration sources and
    3. Configuring logging


## Startup class

1. class does the following 2 very important things
    - ConfigureServices() method configures services required by the application
    - Configure() method sets up the application's request processing pipeline

Logging

 # Logging

Getting started with ASP.NET Core 6 · NLog/NLog Wiki · GitHub


1. ASP.NET Core built-in logging providers

    Console
    Debug
    EventSource
    EventLog
    TraceSource
    AzureAppServicesFile
    AzureAppServicesBlob
    ApplicationInsights

2. Using NLog in ASP.NET Core
    - Install NLog.Web.AspNetCore nuget package
    - Create nlog.config file        
        <?xml version="1.0" encoding="utf-8" ?>
        <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

          <!-- the targets to write to -->
          <targets>
            <!-- write logs to file  -->
            <target name="allfile" xsi:type="File"
                    fileName="c:\DemoLogs\nlog-all-${shortdate}.log"/>
          </targets>

          <!-- rules to map from logger name to target -->
          <rules>
            <!--All logs, including from Microsoft-->
            <logger name="*" minlevel="Trace" writeTo="allfile" />
          </rules>
        </nlog>
    - Enable copy to bin folder for nlog.config
    - Enable NLog as one of the Logging Provider
        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
                logging.AddEventSourceLogger();
                // Enable NLog as one of the Logging Provider
                logging.AddNLog();
            })
            .UseStartup<Startup>();
            
    - If you want only NLog as the logging provider, clear all the logging providers and then add NLog.
        WebHost.CreateDefaultBuilder(args)
        .ConfigureLogging((hostingContext, logging) =>
        {
            // Remove all the default logging providers
            logging.ClearProviders();
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            // Add NLog as the Logging Provider
            logging.AddNLog();
        })
       .UseStartup<Startup>();
    - define different logLevel for each controller
        {
          "Logging": {
            "LogLevel": {
              "Default": "Warning",
              "EmployeeManagement.Controllers.HomeController": "Trace",
              "EmployeeManagement.Models.SQLEmployeeRepository": "Error",
              "Microsoft": "Warning"
            }
          }
        }

Layout View in ASP.NET Core MVC

 # Layout View in ASP.NET Core MVC

1. Just like a regular view a layout view is also a file on the file system with a .cshtml extension
2. You can think of a layout view as a master page in asp.net web forms.
3. Since a layout view is not specific to a controller, we usually place the layout view in a sub folder called "Shared" in the "Views" folder
4. By default, in ASP.NET Core MVC, the layout file is named _Layout.cshtml.
5. In ASP.NET Core MVC, the file names of other .cshtml files like _ViewStart.cshtml and _ViewImports.cshtml start with an underscore.
6. The leading underscore in the file name indicates that these files are not intended to be served directly by the browser.
7. It is also possible to have multiple layout files in a single application. Perhaps one layout file for all admin users and a different layout file for all non admin users.
8. @RenderBody() is the location where view specific content is injected. For example, if index.chtml view is rendered using this layout view, index.cshtml view content is injected at the location where we have @RenderBody() method call.
9. To render a view using the layout view (_Layout.cshtml) set the Layout property. For example, to use the Layout view with details.cshtml, modify the code in details.cshtml to include the Layout property as shown below.
10. set different layout for different role
 @{
    if (User.IsInRole("Admin"))
    {
        Layout = "_AdminLayout";
    }
    else
    {
        Layout = "_NonAdminLayout";
    }
}

## Section in a Layout View

1. A layout page in ASP.NET Core MVC can also include a section. A section can be optional or mandatory. It provides a way to organize where certain page elements should be placed.
2. If the custom script file is required by all the views then we could place it in the Layout page as shown below.
 <body>
    <div>
        @RenderBody()
    </div>

    <script src="~/js/CustomScript.js"></script>
</body>
3. In layout view,
 @if (IsSectionDefined("Scripts"))
{
    @RenderSection("Scripts", required: false)
}
4. in child view, we want the details view to include <script> tag in the "Scripts" section in the layout page. To achieve this we include "Scripts" section in Details.cshtml as shown below.
@section Scripts {
    <script src="~/js/CustomScript.js"></script>
}

Launchsettings file

 # launchsettings.json file

1. You will find this file in the "Properties" folder in the project root folder.
2. The settings in this file are used when we run this ASP.NET core project either from Visual Studio or by using .NET Core CLI.
3. This file is only used on local development machine. We do not need it for publishing our asp.net core application.
4. If there are certain settings that you want your asp.net core application to use when you publish and deploy your app, store them in appsettings.json file. We usually store our application configuration settings in this file.
5. We can also have environment specific appsettings.json files. For example, appsettings.Staging.json for the staging environment. In ASP.NET Core, in addition to appsettings.json file,
6. we also have other configuration sources like Environment variables, User Secrets, Command Line Arguments and even our own custom configuration source.




InProcess vs OutOfProcess hosting

 # InProcess vs OutOfProcess hosting

## InProcess Hosting

1. Default hosting model is InProcess in .net core
2. In case of InProcess hosting, CreateDefaultBuilder() method calls UseIIS() method and host the app inside of the IIS worker process (w3wp.exe or iisexpress.exe).
3. From a performance standpoint, InProcess hosting delivers significantly higher request throughput than OutOfProcess hosting
4. In the case of IIS, the process name that executes the app is w3wp and in the case of IIS Express it is iisexpress
5. To get the process name executing the app, use System.Diagnostics.Process.GetCurrentProcess().ProcessName

## OutOfProcess Hosting

1. There are 2 web servers involved here - An internal web server and an external web server.
2. The internal web server is Kestrel and the external web server can be IIS, Nginx or Apache
3. With InProcess hosting, there is only one web server i.e the IIS that hosts the asp.net core application. So, we do not have the performance penalty of proxying requests between internal and external web server.
4. With Out of Process Hosting, using a reverse proxy server is a good choice as it provides an additional layer of configuration and security.
5. It might integrate better with the existing infrastructure. It can also be used for load balancing.
6. So, with a reverse proxy server in place, it receives incoming HTTP requests from the network and forwards them to the Kestrel server for processing. Upon processing the request, the Kestrel server sends the response to the reverse proxy server which then ultimately sends the response to the requested client over the network.
7. With Out of Process Hosting, whether you use a reverse proxy server or not, it is the Kestrel server that hosts the application and process the request.

## What is Kestrel

1. Kestrel is a cross-platform web server for ASP.NET Core. It is supported on all platforms and versions that .NET Core supports.
2. It is included by default as internal server in ASP.NET Core.
3. Kestrel can be used, by itself as an edge server i.e Internet-facing web server that can directly process the incoming HTTP requests from the client.
4. In Kestrel, the process used to host the app is dotnet.exe.
5. When we run a .NET Core application using the .NET Core CLI (Command-Line Interface), the application uses Kestrel as the web server.


Form Tag Helpers

 # form tag Helpers

1. We use the following common tag helpers to create a form in ASP.NET Core

    Form Tag Helper
    Label Tag Helper
    Input Tag Helper
    Select Tag Helper
    Textarea Tag Helper
    Validation tag helpers.
    
2. <form asp-controller="home" asp-action="create" method="post">
</form>
is equal to
<form method="post" action="/home/create"></form>

3. <input asp-for="Name"> is same as
<input type="text" id="Name" name="Name" value="">

4. Label Tag Helper

<label asp-for="Name"></label>
<input asp-for="Name">

generates

<label for="Name">Name</label>
<input type="text" id="Name" name="Name" value="">

5. Select Tag Helper
 <select asp-for="Department"
        asp-items="Html.GetEnumSelectList<Dept>()"></select>
same as
 <select id="Department" name="Department">
    <option value="0">None</option>
    <option value="1">HR</option>
    <option value="2">Payroll</option>
    <option value="3">IT</option>
</select>

6.


Error/ exception handling

 # Error Handling

1.  There are 3 middleware components that deal with status code pages in asp.net core

    UseStatusCodePages
    UseStatusCodePagesWithRedirects
    UseStatusCodePagesWithReExecute

2. UseStatusCodePages middleware
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseStatusCodePages();
    }
    app.UseStaticFiles();
    app.UseMvc(routes =>
    {
        routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
    });

3. UseStatusCodePagesWithRedirects Middleware
    - In a production quality application we want to intercept these non-success http status codes and return a custom error view. To achieve this, we can either use UseStatusCodePagesWithRedirects middleware or UseStatusCodePagesWithReExecute middleware.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseStatusCodePagesWithRedirects("/Error/{0}");
        }
        app.UseStaticFiles();
        app.UseMvc(routes =>
        {
            routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
        });
    }
    With the following line in place, if there is a 404 error, the user is redirected to /Error/404.

4. Create custom ErrorController to handle different errors
    public class ErrorController : Controller
    {
        // If there is 404 status code, the route path will become Error/404
        [Route("Error/{statusCode}")]
        public IActionResult HttpStatusCodeHandler(int statusCode)
        {
            switch (statusCode)
            {
                case 404:
                    ViewBag.ErrorMessage = "Sorry, the resource you requested could not be found";
                    break;
            }

            return View("NotFound");
        }
    }
5.  For a non-development environment, add the Exception Handling Middleware to the request processing pipeline using UseExceptionHandler() method. We do this in the Configure() method of the Startup class.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
        }

        // Rest of the code
    }
    - Now implement ErrorController
    
    public class ErrorController : Controller
    {
        [AllowAnonymous]
        [Route("Error")]
        public IActionResult Error()
        {
            // Retrieve the exception Details
            var exceptionHandlerPathFeature =
                    HttpContext.Features.Get<IExceptionHandlerPathFeature>();

            ViewBag.ExceptionPath = exceptionHandlerPathFeature.Path;
            ViewBag.ExceptionMessage = exceptionHandlerPathFeature.Error.Message;
            ViewBag.StackTrace = exceptionHandlerPathFeature.Error.StackTrace;

            return View("Error");
        }
    }

   
6. UseDeveloperExceptionPage Middleware must be plugged into the request processing pipeline as early as possible, so it can handle the exception and display the Developer Exception Page if the subsequent middleware components in the pipeline raises an exception.

Entity Framework Core

 # Entity framework core

1. We create a class that derives from the DbContext class.
2. DbContext class is in Microsoft.EntityFrameworkCore namespace.
public class AppDbContext : DbContext
{ }
3. For the DbContext class to be able to do any useful work, it needs an instance of the DbContextOptions class.
4. The DbContextOptions instance carries configuration information such as the connection string, database provider to use etc.
5. To pass the DbContextOptions instance we use the constructor as shown in the example below.
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options)
            : base(options)
        {
        }
    }
6. The DbContext class includes a DbSet<TEntity> property for each entity in the model.
7. The LINQ queries against the DbSet<TEntity> will be translated into queries against the underlying database.
8. To inject ef core service use
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContextPool<AppDbContext>(
            options => options.UseSqlServer(_config.GetConnectionString("EmployeeDBConnection")));

        services.AddMvc().AddXmlSerializerFormatters();
        services.AddTransient<IEmployeeRepository, MockEmployeeRepository>();
    }
9. UseSqlServer() extension method is used to configure our application specific DbContext class to use Microsoft SQL Server as the database.
10. To connect to a database, we need the database connection string which is provided as a parameter to UseSqlServer() extension method
{
  "ConnectionStrings": {
    "EmployeeDBConnection": "server=(localdb)\\MSSQLLocalDB;database=EmployeeDB;Trusted_Connection=true"
  }
}

## Common entity framework core migration commands

1. Add-Migration     Adds a new migration
2. Update-Database     Updates the database to a specified migration

## Seed initial database data

1. In your application DbContext class, override OnModelCreating() method.

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }

    public DbSet<Employee> Employees { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>().HasData(
            new Employee
            {
                Id = 1,
                Name = "Mark",
                Department = Dept.IT,
                Email = "mark@pragimtech.com"
            }
        );
    }
}

.Net Core And Its benefits

 ## What is Asp.net core?

is a cross platform, high performance, open-source framework for building modern, cloud-based, internet-connected applications.
Asp.net core is a redesign of Asp.net 4.x

# ASP.net core benefits and features
1. Open source
2. Cross Platform - mac Os, windows, linux
3. Hosting - can be done in IIS, apache, docker, self hosted
4. Development can be done independent of Visual studio. We can use sublime, vs code, notepad.
5. One unified programming model for MVC and web api
    - Both the MVC controller class and the ASP.net web api controller class inherit from the same Controller base class & returns IActionResult.
6. Built in support for dependency injection
    - Dependency injections improves testability of the application. Unit tests can be written easily.
7. Modular - it provides modularity with help of middleware components.
    - Both request and response pipelines are configured using middleware components.
    - Rich set of built in components are present already, you can also write your own


Dependency Injection

 # Dependency Injection

1. AddSingleton() - As the name implies, AddSingleton() method creates a Singleton service. A Singleton service is created when it is first requested. This same instance is then used by all the subsequent requests. So in general, a Singleton service is created only one time per application and that single instance is used throughout the application life time.

2. AddTransient() - This method creates a Transient service. A new instance of a Transient service is created each time it is requested.

3. AddScoped() - This method creates a Scoped service. A new instance of a Scoped service is created once per request within the scope. For example, in a web application it creates 1 instance per each http request but uses the same instance in the other calls within that same web request.


Accessing Configuration Information

 # Accessing configuration information

1. To access configuration information in the Startup class, inject the IConfiguration service provided by the Framework.
2. IConfiguration service is setup to read configuration information from all the various configuration sources in asp.net core
3. If you have a configuration setting with the same key in multiple configuration sources, the later configuration sources override the earlier configuration sources
4. CreateDefaultBuilder() method of the WebHost class which is automatically invoked when the application starts, reads the configuration sources in a specific order.
5. Following is the default order in which the various configuration sources are read
    - appsettings.json,
    - appsettings.{Environment}.json
    - User secrets
    - Environment variables
    - Command-line arguments



ASP.NET Core Identity

 # ASP.NET Core Identity

1. ASP.NET Core Identity is a membership system.
2. It allows us to create, read, update and delete user accounts.
3. Supports account confirmation, authentication, authorisation, password recovery, two-factor authentication with SMS.
4. It also supports external login providers like Microsoft, Facebook, Google etc.

## Adding ASP.NET Core Identity Support in ASP.NET Core Application

1. Inherit from IdentityDbContext class
public class AppDbContext : IdentityDbContext
{
    // Rest of the code
}
Your application DbContext class must inherit from IdentityDbContext class instead of DbContext class. This is required because IdentityDbContext provides all the DbSet properties needed to manage the identity tables in SQL Server.
2. If you go through the hierarchy chain of IdentityDbContext class, you will see it inherits from DbContext class. So this is the reason you do not have to explicitly inherit from DbContext class if your class is inheriting from IdentityDbContext class.
3. Configure ASP.NET Core Identity Services
 services.AddIdentity<IdentityUser, IdentityRole>()
        .AddEntityFrameworkStores<AppDbContext>();
4. AddIdentity() method adds the default identity system configuration for the specified user and role types.
5. IdentityUser class is provided by ASP.NET core and contains properties for UserName, PasswordHash, Email etc. This is the class that is used by default by the ASP.NET Core Identity framework to manage registered users of your application.
6. If you want store additional information about the registered users like their Gender, City etc. Create a custom class that derives from IdentityUser. In this custom class add the additional properties you need and then plug-in this class instead of the built-in IdentityUser class.
7. Similarly, IdentityRole is also a builtin class provided by ASP.NET Core Identity and contains Role information.
8. We want to store and retrieve User and Role information of the registered users using EntityFrameWork Core from the underlying SQL Server database. We specify this using AddEntityFrameworkStores<AppDbContext>() passing our application DbContext class as the generic argument.
9. Add Authentication middleware to the request pipeline
 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseStatusCodePagesWithReExecute("/Error/{0}");
    }

    app.UseStaticFiles();
    app.UseAuthentication();
    app.UseMvc(routes =>
    {
        routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
    });
}
10. We want to be able to authenticate users before the request reaches the MVC middleware. So it's important we add authentication middleware before the MVC middleware in the request processing pipeline.
11. Add Identity Migration

## UserManager & SignInManager class

1. UserManager
    - CreateAsync, DeleteAsync, UpdateAsync
2. SignInManager
    - SignInAsync, SignOutAsync, IsSignedIn
    
## ASP.NET Core IdentityOptions

In this example, we are using the IdentityOptions object to configure PasswordOptions. We could also use this IdentityOptions object to configure

    UserOptions
    SignInOptions
    LockoutOptions
    TokenOptions
    StoreOptions
    ClaimsIdentityOptions

## Authentication & Authorization

1. Use [Authorize] attribute to apply secure endpoints
2. Use [AllowAnonymous] to provide anonymous access

### Possible Authorization based attributes
1. [Authorize(Roles = "Administrator")]
2. [Authorize(Roles = "Administrator,User")]

### Show hide menu based on role
   @if (SignInManager.IsSignedIn(User) && User.IsInRole("Admin"))
    {
        <li class="nav-item">
            <a class="nav-link" asp-controller="Administration" asp-action="ListRoles">
                Manage Roles
            </a>
        </li>
    }

## To check if the user is signedin, inject ASP.NET Core SignInManager service
 
@using Microsoft.AspNetCore.Identity
@inject SignInManager<ApplicationUser> SignInManager

@if (SignInManager.IsSignedIn(User) && User.IsInRole("Admin"))
{

}

OR

@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService authorizationService;

@if ((await authorizationService.AuthorizeAsync(User, "EditRolePolicy")).Succeeded)
{
    <a asp-controller="Administration" asp-action="EditRole"
       asp-route-id="@role.Id" class="btn btn-primary">
        Edit
    </a>
}


.net core Interview questions

 # .Net Core

Sunday, 13 March 2022

KendoUI combo box

Get kendo combo box

var account = $("#htiAccountNumber");
var accountCombo = account.data("kendoComboBox");

Set change event handler
accountCombo.bind("change", HTIOrderPage.AccountChangeHandler);

Make Ajax call in Jquery, Asp.net MVC

  $.ajax({
        type: "POST",
        dataType: "json",
        data: {},
        url: ORDER_E.GetAllActiveAccounts,
        success: function (data) {          
            if (data.success) {
                console.log(data);              
            }
        },
        statusCode: {
            403: function () { alert("Access denied"); }, 20: function (res) { HTI.ShowInvalidCharError(res) }
        }
    });

Factory Design pattern

 # Factory Design Pattern

Define an interface for creating an object, but let sub-classes decide which class to instantiate.

## Factory Example

public interface IEmployeeManager
{
    decimal GetBonus();
    decimal GetPay();
}

### ContractEmployeeManager.cs

public class ContractEmployeeManager : IEmployeeManager
{
    public decimal GetBonus()
    {
        return 5;
    }

    public decimal GetPay()
    {
        return 12;
    }
}

### PermanentEmployeeManager.cs

public class PermanentEmployeeManager : IEmployeeManager
{
    public decimal GetBonus()
    {
        return 10;
    }

    public decimal GetPay()
    {
        return 8;
    }
}

### EmployeeManagerFactory.cs

public class EmployeeManagerFactory
{
    public IEmployeeManager GetEmployeeManager(int employeeTypeID)
    {
        IEmployeeManager returnValue = null;
        if (employeeTypeID == 1)
        {
            returnValue = new PermanentEmployeeManager();
        }
        else if (employeeTypeID == 2)
        {
            returnValue = new ContractEmployeeManager();
        }
        return returnValue;
    }
}

### How to use factory manager class

EmployeeManagerFactory empFactory = new EmployeeManagerFactory();
IEmployeeManager empManager = empFactory.GetEmployeeManager(employee.EmployeeTypeID);


Saturday, 12 March 2022

Static vs singleton

 # Differences between Singleton and static classes

1. Static is a keyword and Singleton is a design pattern
2. Static classes can contain only static members
3. Singleton is an object creational pattern with one instance of the class
4. Singleton can implement interfaces, inherit from other classes and it aligns with the OOPS concepts


Tuesday, 8 March 2022

Thread Safety in Singleton Design Pattern using Lazy keyword

 # Thread Safety in Singleton Design Pattern using Lazy keyword

Lazy keyword provides support for lazy initialization. In order to make a property as lazy, we need to pass the type of object to the lazy keyword which is being lazily initialized.

By default, Lazy<T> objects are thread-safe. In multi-threaded scenarios, the first thread which tries to access the Value property of the lazy object will take care of thread safety when multiple threads are trying to access the Get Instance at the same time.

Therefore, it does not matter which thread initializes the object or if there are any thread race conditions that are trying to access this property.

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SingletonDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Parallel.Invoke(
                () => PrintStudentDetails(),
                () => PrintEmployeeDetails()
            );
            Console.ReadLine();
        }

        private static void PrintEmployeeDetails()
        {
            Singleton fromEmployee = Singleton.GetInstance;
            fromEmployee.PrintDetails("From Employee");
        }

        private static void PrintStudentDetails()
        {  
            Singleton fromStudent = Singleton.GetInstance;
            fromStudent.PrintDetails("From Student");
        }
    }
}

Singleton.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SingletonDemo
{
   
    public sealed class Singleton
    {
        private static int counter = 0;
       
        private Singleton()
        {
            counter++;
            Console.WriteLine("Counter Value " + counter.ToString());
        }
        private static readonly Lazy<Singleton> instance =
new Lazy<Singleton>(()=>new Singleton());
       
        public static Singleton GetInstance
        {
            get
            {
                return instance.Value;
            }
        }
       
        public void PrintDetails(string message)
        {
            Console.WriteLine(message);
        }       
    }
}

Threads

 
# Thread safety

- When multiple threads accessing same variable or memory space at same time, sometimes one threads reads the variable and another thread write to variable at same time. Due to which program becomes error prone, which does not give expected result. To ensure safe execution of program during multithreading we follow certain mechanisms which are commonly known as thread safety.

## Thread safety removes the following conditions in the code:
1. Race Condition - two threads accessing variable at same time, one thread reads, another writes
2. Deadlocks - occurs when one thread waiting for another thread to release a resource.

### Question: Is the C# Static Constructor Thread -Safe?

Static constructors are guaranteed to be run only once per application domain, before any instances of a class are created or any static members are accessed. Using a Static Constructor actually is Thread-Safe.

## Parallel execution in threads
Parallel.Invoke method of .NET Framework 4.0, we can easily make parallel call to two methods.
    Parallel.Invoke(
        () => PrintStudentdetails(),
        () => PrintEmployeeDetails()
    );
    
## Lazy Initialization
The lazy initialization of an object improves the performance and avoids unnecessary computation till the point the object is accessed. Further, it reduces the memory footprint during the startup of the program. Reducing the memory print will help faster loading of the application.

## Non-Lazy or Eager Loading
Eager loading is nothing but to initialize the required object before it’s being accessed.  Which means, we instantiate the object and keep it ready and use it when we need it. This type of initialization is used in lower memory footprints. Also, in eager loading, the common language runtime takes care of the variable initialization and its thread safety. Hence, we don’t need to write any explicit coding for thread safety.


Singleton Design pattern


- it belongs to creational design pattern
- it deals with object creation mechanisms
- it is used to ensure that only one instance of a class is instantiated
- that single instance created is responsible to coordinate actions across the application

- Guidelines for creating singleton class
1. Mark class sealed so that we will restrict it from being inherited. Also if someone creates nested class within singleton class then user can create any number of instances for nested class which breaks our main goal of single instance.
2. Create a private static instance of singleton class inside it.
3. Make a public property GetInstance, which will first check whether we already initialized class or not, using private variable. If class is already created return that or else initialize singleton class and return its instance.
4. Create a private constructor. Private constructor ensures that instance of class can only be created internally not externally.
5. Also inside public property GetInstance lock an object so that instance creation will be thread safe. No two threads will access property at same time.

## Lazy Initialization in Singleton
GetInstance Property is responsible for the Singleton Instance creation. Singleton object is not instantiated until and unless GetInstance is invoked. Hence, there is a delay in instance creation till the GetInstance is accessed. This Delay in Instance creation is called Lazy Initialization.

## How to use Multithreads in Singleton
The lazy initialization works perfectly well when we invoke the GetInstance in a Single threaded approach. However, there is a chance that we may end up creating multiple instances when multiple threads invoke the GetInstance at the same time.

## How to implement a Thread Safe singleton class
Locks are the best way to control thread race condition and they help us to overcome the present situation. Please refer to the Singleton.cs code for lock checks and double check locking.

```code c#
Singleton Class Implementation Example

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// First version of Singleton demo
/// </summary>
namespace SingletonDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Parallel.Invoke(
                () => PrintStudentdetails(),
                () => PrintEmployeeDetails()
                );
            Console.ReadLine();
        }

        private static void PrintEmployeeDetails()
        {
            /*
             * Assuming Singleton is created from employee class
             * we refer to the GetInstance property from the Singleton class
             */
            Singleton fromEmployee = Singleton.GetInstance;
            fromEmployee.PrintDetails("From Employee");
        }

        private static void PrintStudentdetails()
        {
            /*
             * Assuming Singleton is created from student class
             * we refer to the GetInstance property from the Singleton class
            */
            Singleton fromStudent = Singleton.GetInstance;
            fromStudent.PrintDetails("From Student");
        }
    }
}

Singleton.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// First Singleton version
/// </summary>
namespace SingletonDemo
{
    /*
     *  Sealed ensures the class being inherited and
     *  object instantiation is restricted in the derived class
     */
    public sealed class Singleton
    {
        private static int counter = 0;
        private static readonly object obj = new object();

        /*
         * Private property initilized with null
         * ensures that only one instance of the object is created
         * based on the null condition
         */
        private static Singleton instance = null;
       
        /*
         * public property is used to return only one instance of the class
         * leveraging on the private property
         */
        public static Singleton GetInstance
        {
            get
            {
                if (instance == null)
                {
                    lock (obj)
                    {
                        if (instance == null)
                            instance = new Singleton();
                    }
                }
                return instance;
            }
        }
        /*
         * Private constructor ensures that object is not
         * instantiated other than with in the class itself
         */
        private Singleton()
        {
            counter++;
            Console.WriteLine("Counter Value " + counter.ToString());
        }
        /*
         * Public method which can be invoked through the singleton instance
         */
        public void PrintDetails(string message)
        {
            Console.WriteLine(message);
        }
    }
}
```

Saturday, 5 March 2022

Design Patterns

 # What are design Pattern

- Design Patterns are reusable solutions to recurring problem.
- They are generally targeted at solving the problems of object generation and management.
- In other words, Design patterns acts as templates which can be applied to the real-world programming problems.

# Types of Design Patterns

- There are mainly 3 types of design patterns. They are Creational, Structural and Behavioural.

# Creational design patterns
- These patterns deal with object creation and initialization.
- Creational pattern gives the program more flexibility in deciding which objects need to be created for a given case.
- examples are: Singleton, Factory and Abstract Factory etc

# Structural design patterns
- This pattern deals with class and object composition.
- In simple words, This pattern focuses on decoupling interface, implementation of classes and its objects.
- examples are:  Adapter,  Facade and Bridge etc.

# Behavioural design patterns
- These patterns deal with communication between Classes and objects.
- Examples are: Chain of Responsibility, Command and Interpreter etc.


Interview Questions - Index

  1. .Net Basics
  2. Design Patterns
  3. Singletone Design Pattern - Creational design pattern 
  4. Thread Safety in Singleton Design Pattern using Lazy keyword
  5. Factory Design Pattern 
  6. SOLID Design Principles
    1. Single Responsibility
    2. Open / Closed principle
    3. Liskov substitution principle
    4. Interface segregation principle
    5. Dependency Inversion Principle
  7. Threads
  8. .net core 
  9. Misc definitions
        - Lazy Initialization vs Eager Loading
        - Static vs Singleton
  10. Rest API

Search This Blog

Creating your first "Alexa" Skill

Index What is Alexa What is Alexa Skill? Why is it required when Alexa already equipped with voice assistant? Dev...