Dot Net Programming

Tuesday, September 1, 2020

Top 20 .NET Core Interview Questions & Answers You Need to Know

September 01, 2020

Top 20 .NET Core Interview Questions & Answers You Need to Know



1) What is .NET Core?

.NET Core is a free and open-source, managed computer software framework for Windows, Linux, MacOS operating systems. It is suitable for building cloud based internet connected applications like web apps, IoT apps and mobile apps. ASP.NET Core apps can run on .NET Core or on full .NET framework.

2) What are the features of .NET Core?

Flexible Deployment: Can be included in your app or installed side-by-side user or machine-wide.
Cross-Platform: Run on Windows, MacOS and Linux can be ported to other OSes. The supported operating systems, CPUs and application scenarios will grow over time, provided by Microsoft, other companies, and individuals.
Command-Line Tools: All product scenarios can be exercised at the command-line.
Compatible: .NET Core is compatible with .NET Framework, Xamarin and Mono, via the .NET Standard Library.
Open Source: The .NET Core platform is open source, using MIT and Apache 2 licenses and documentation is licensed under CC-BY.

3) What is Middleware?

Middleware is software that’s assembled into an app pipeline to handle requests and responses. Each component: • Chooses whether to pass the request to next component in pipeline. • Can perform work before and after the next component in pipeline. Request delegates are used to build the request pipeline. The request delegates handle each HTTP request.

4) What is Krestrel?

Krestrel is a cross-platform web server for ASP.NET Core based on libuv, a cross-platform asynchronous I/O library. It is secure and good enough to use it without a reverse proxy server. You can set a krestrel server in the program.cs file.


 

public class Program

{

public static void Main(string[] args)

{

    var host = new WebHostBuilder()

        .UseContentRoot(Directory.GetCurrentDirectory())

        .UseKestrel()

        .UseIISIntegration()

        .UseStartup<Startup>()

        .ConfigureKestrel((context, options) =>

        {

            // Set properties and call methods on options

        })

        .Build();

    host.Run();

}

}

 


5) What is tag helper in ASP.NET Core?

ASP.NET Core provides an in-build tag helper, Tag helper enables the server-side code that creates and renders the HTML elements in the razor page.

Example : <input asp-for="Email" class="form-control" />

  6) What are the various JSON files in ASP.NET Core?
 • Global.json
 • Launchsettings.json
 • appsettings.json
 • bundleconfig.json
 • bower.json
 • package.json

7) What is startup class ASP.NET Core?

Startup class is the entry point of any ASP.NET Core application, this class contains the application configuration related details, and it has two main methods ConfigureServices() and Configure().

 
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddMvc().AddRazorOptions(opt =>
            {
                opt.PageViewLocationFormats.Add("/Pages/shared/{0}.cshtml");
            });
        }
     public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
        }
    }

 

8) How to enable session in ASP.NET Core?

The middleware for the session is provided by Microsoft.AspNetCore.Session. To use the session in ASP.NET Core application we need to add the middleware in pipeline.

 

public class Startup

 {

     public void ConfigureServices(IServiceCollection services)

     { 

         services.AddSession();

         services.AddMvc();

     }

     public void Configure(IApplicationBuilder app, IHostingEnvironment env)

     {

        app.UseSession();

     }

  }

 

9) What is WebListener?

WebListener is a web server for ASP.NET Core that that runs only on Windows, based on the Windows Http Server API. It runs directly on the Http.Sys kernel driver. WebListener can be used for direct connection to the internet without relying on IIS. It can only be used independently.

10) What is Metapackage in ASP.NET Core?

In ASP.NET Core project we don’t need to include individual package references in the .csproj file. There is one file called Microsoft.AspNetCore.All is added under NuGet, Now Microsoft.AspNetCore.All contains all the required packages. That’s the concept of metapackage.

11) What is a Razor pages in ASP.NET Core?

This is a new feature introduced in ASP.NET Core 2.0. It follows a page-centric development model just like ASP.NET web forms. It supports all the feature of ASP.NET Core.

Example: 
 @page
<h1> Hello</h1> 
 <h2> Razor Pages </h2>

12) What is launch.settings.json file in ASP.NET Core?

It holds the project-specific configuration to launch the application including the environment variable.


//launchSettings.json

{

  "iisSettings": {

    "windowsAuthentication": false,

    "anonymousAuthentication": true,

    "iisExpress": {

      "applicationUrl": "http://localhost:63977",

      "sslPort": 44389

    }

  },

  "profiles": {

    "IIS Express": {

      "commandName": "IISExpress",

      "launchBrowser": true,

      "environmentVariables": {

        "ASPNETCORE_ENVIRONMENT": "Development"

      }

    },

  "TestApp": {

      "commandName": "Project",

      "launchBrowser": true,

      "applicationUrl": "https://localhost:5001;http://localhost:5000",

      "environmentVariables": {

        "ASPNETCORE_ENVIRONMENT": "Development"

      }

    }

  }

}

 

 

13) How automatic model binding in Razor pages works?

When we create a razor page, it provides the option to have model binding or not, in model binding there is a model created with the razor page, the model is inherited from: PageModel we need to use [BindingProperty] attribute to bind any property to model.


 

public class ContactModel : PageModel

 {

     [BindProperty]

     public string Email { get; set; }

 }

 

 

14) How to disable Tag Helper at element level?

We can disable Tag Helper at element level using the opt-out character (“!”). This character must apply opening and closing HTML tag. Example: </!span>

15) How many types of single page application templates provided by the .NET Core?

      Angular

      React

      React with Redux

      Javascript Services

16) What is the ConfigureServices method of Startup.cs?

ConfigureServices method gets call runtime to register services to DI container. After registering the dependent classes, you can use those clastyle="font-size:2.0rem;"sses anywhere in the application. The ConfigureServices method includes the IServiceCollection parameter to register services to the DI container.

17) What is the Configure method of Startup.cs?

Configure the method gets call runtime to configure the HTTP request pipeline for application. Configure use the instance of the IApplicationBuilder that is provided by In-Build IOC container. In other words, you add the middleware in this method like routing and other custom middleware as per your application requirements.

18) Dependency injection in .NET Core

The .NET Core has an In-build dependency mechanism. You have to add namespace Microsoft.Extensions.DependencyInjection in Startup.cs file to get enable IServiceCollection. In the ConfigureServices method, you can add your decencies to a container that will automatically resolve your dependencies and you can access your classes anywhere in the application. The built-in IoC container supports three kinds of lifetimes: Singleton: It creates and shares a single instance of service throughout the application's lifetime. Transient: It creates a new instance of the specified service type every time when it requested. This lifetime works best for lightweight, stateless services. Scoped: It creates an instance of the specified service type once per request and will be shared in a single request.

19) How to handle errors in Middleware?

You can capture synchronous and asynchronous exception instances from the middleware pipeline and generate an HTML response. Following code has if the condition in which you can call different methods for development, staging, production environment or you can pass the environment name in IsInvironment extension method.

Also, you can configure a custom error handling page to call the UseExceptionHandler method that adds a middleware to a pipeline that will catch the exception, log them, Re-executes the request in an alternate pipeline for the page or controller indicated. The request isn't re-executed if the response has started.

 

if (env.IsDevelopment())

{

   app.UseDeveloperExceptionPage();

}

else

{

   app.UseExceptionHandler("/Error");

   app.UseHsts();

}

 

20) Does real-time application support by .NET Core?

Yes, Asp.net's core signalR is an open-source library that gives real-time web functionality to the application.

Monday, August 31, 2020

Top 50 WCF Interview Questions

August 31, 2020

Top 50 WCF Interview Questions

1)      What is WCF?

2)      Why should we use WCF service?

3)      What are the features and advantage of WCF?

4)      What is the difference between WCF and Web services?

5)      What is a service contract in WCF?

6)      Explain what is SOA?

7)      What is transport in WCF?

8)      What is data contract in WCF?

9)      What is WCF binding and how many of them do you know?

10)   What are possible ways of hosting a WCF service?

11)   What is message contract in WCF?

12)   What is operation contract in WCF?

13)   What is contract in WCF service?

14)   WCF VS ASP.NET WEB API

15)   What is fault contract in WCF?

16)   What are end points and how many types of end points in WCF?

17)   What is address in WCF?

18)   Explain transactions in WCF?

19)   What is self hosting in WCF?

20)   What are the main components of WCF service?

21)   How do we host WCF service in IIS?

22)   What is one way operation?

23)   Why do we need one way service?

24)   What is WCF throttling?

25)   What is a service proxy in WCF?

26)   What is WCF concurrency and how many modes of concurrency in WCF?

27)   What is REST and how to create a WCF RESTful service?

28)   What is exception handling in WCF and what are the ways for WCF exception handling?

29)   What is tracing in WCF?

30)   Could we use WSHttpBinding with Request-CallBack exchange pattern?

31)   What replaces WCF in .Net Core?

32)   What is the knownType attribute in WCF?

33)   How to create Basic HTTP Binding in WCF?

34)   What is the difference between BasicHttPBindng and WsHttpBinding?

35)   What is transport level security in WCF?

36)   What is MSMQ in WCF?

37)   What is method overloading in WCF?

38)   What is WCF messaging layer?

39)   What is instance management in WCF?

40)   What is service versioning?

41)   What WCF data service?

42)   How does software as a service work?

43)   Which is the namespace used to access WCF?

44)   Why we use information cards in WCF?

45)   What is a formal agreement in WCF?

46)   How to create multiple methods in the same name?

47)   What is the address formats of the WCF transport schemas?

48)   How to set the timeout property for the WCF service client call?

49)   How can you generate proxies using Svcutil in WCF?

50)   What is the usage of receiveTimeout property in WCF?

 



Sunday, August 30, 2020

Difference between ref and out parameters in C#

August 30, 2020

 Ref and out keywords in c# are used to pass arguments within a method or function. Both indicate that an argument passed by reference. By default parameter are passed to a method by value. By using these keywords we can pass a parameter by reference.

Ref –

The ref keyword is used to pass an argument as a reference. This means that value of that parameter is changed in method, it get reflected in calling method.

Example : Ref  Keyword – C#

 
 public static string GetNextName(ref int id)  
  {  
    string returnText = "Next-" + id.ToString();  
    id += 1;  
    return returnText;  
  }  
 static void Main(string[] args)  
  {  
    int val = 1;  
    Console.WriteLine("Previous value of integer val:" + val.ToString());  
    string test = GetNextName(ref val);  
    Console.WriteLine("Current value of integer val:" + val.ToString());  
  } 
 

 

Output -

Previous value of integer val : 1

Current value of integer val : 2

 

Out –

The out keyword is used to pass arguments to method as a reference type and is primary used when a method has to return multiple values.

Example : Out  Keyword – C#

 
 public static string GetNextNameByOut(out int id)  
  {  
    id = 1;  
    string returnText = "Next-" + id.ToString();  
    return returnText;   
  }  
 static void Main(string[] args)  
  {  
    int val = 0;  
    Console.WriteLine("Previous value of integer val:" + val.ToString());  
    string test = GetNextNameByOut(out val);  
    Console.WriteLine("Current value of integer val:" + val.ToString());  
  } 
 

Output -

Previous value of integer val : 0

Current value of integer val : 1


Ref Vs Out

Ref Keyword            

Out Keyword

When ref keyword is used the data may pass in bi-directional.

When out keyword is used the data only passed in unidirectional.

In called method, It is not required to initialize the parameter passed as ref.

In called method, It is required to initialize the parameter passed as out.

Ref should not be used to return multiple values from method.

Out should be used to return multiple values from method.

Ref is useful when we already know the parameter value and called method can only modify the data.

Out is useful when we don't know the parameter value before calling the method.


Saturday, August 29, 2020

Major Events in Global.asax File

August 29, 2020

 

 Global.asax file is derived from the HttpApplication class and contains code for responding to application-level events raised by ASP.NET. Global.asax file, also known as ASP.NET application file, is located in root directory of an ASP.NET application.



Note 1 : The Global.asax is an optional file. Use it only when there is a need for it.

Note 2 : If a user requests the Global.asax file, the request is rejected . External users can not use it.

The following are some of the important events in the Global.asax file:

Application_Init : The Application_Init event is fired when an application initializes the first time.

Application_Start  : The Application_Start event is fired the first time when an application starts.

Application_AutorizeRequest : Application_AutorizeRequest event is  fired on successful authentication of users credentials. You can use this method to authorization rights to user.

Application_ResolveRequestCache : Application_ResolveRequestCache is fired on successful completion of an authorization request.

Application_Disposed : Application_Disposed  event is fired when the web application is destroyed.

Session_Start : Session_Start event is fired when session starts on each new user requesting a page.

Application_BeginRequest :  The Application_BeginRequest event is fired when each time new user request come in.

Application_EndRequest : The Application_EndRequest event is fired at the end of each request.

Application_AuthenticateRequest : The Application_AuthenticateRequest event indicates that a request is ready to be  authenticated. If you are using forms Authentication, this event can be used to check for the user’s roles & rights.

Application_Error : The Application_Error event fired when an error occurs.

Session_End : The Session_End event is fired when the session of a user ends.

Application_End : The Application_End event is fired when the web application ends.

Sunday, August 23, 2020

Partitioning Operator: Take & TakeWhile

August 23, 2020

In LINQ, Partition Operators are used for separating the given sequence into two portions without

Sorting the element and return the one of the portions


Method

Description

Take

This operator is used fetch the first “n” number of elements from the data source where “n” is integer which is passed as a parameter to the Take method.

TakeWhile

This operator behaves similarly to the take() method except that instead of taking the first “n” element of sequence , It takes all of initial elements of sequence that meet the criteria specified by the predicate, and stops on the first element that doesn’t meet the criteria

 

Example: Take() Method – C#

 

IList<string> strList = new List<string>(){ "One", "Two", "Three" };
 
var newList = strList.Take(2);
 
foreach(var str in newList)
    Console.WriteLine(str);

 

 

Output -

One

Two

 

Example: TakeWhile() Method – C#

 
IList<string> strList = new List<string>() { 
                                            "Three", 
                                            "Four", 
                                            "Five", 
                                            "Hundred"  };
 
var result = strList.TakeWhile(s => s.Length > 4);
 
foreach(string str in result)
        Console.WriteLine(str);

 


Output -

Three


Saturday, August 15, 2020

Partitioning Operator: Skip & SkipWhile

August 15, 2020

 

In LINQ, Partition Operators are used for separating the given sequence into two portions without

Sorting the element and return the one of the portions


Method

Description

Skip

This operator is used to skip the specified number of elements in a sequence return the remaining elements.

SkipWhile

This operator is used to skip the elements in a sequence based on the condition, Which is defined as true

 

Example: Skip() Method – C#

 

IList<string> strList = new List<string>(){"Hindi""Marathi""Math""Science"};

 

var newList = strList.Skip(2);

 

foreach(var str in newList)

    Console.WriteLine(str);

 

 

Output -

Math

Science

 

Example: SkipWhile() Method – C#

 
IList<string> strList = new List<string>() { 
                                            "One", 
                                            "Two", 
                                            "Three", 
                                            "Four", 
                                            "Five", 
                                            "Six"  };
 
var resultList = strList.SkipWhile(s => s.Length < 4);
 
foreach(string str in resultList)
        Console.WriteLine(str);

 



Output -

Three
Four
Five
Six