European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET Core 5.0.2 Hosting - HostForLIFE :: How To Use Postman With ASP.NET Core Web API Testing?

clock March 8, 2021 06:12 by author Peter

Manual Testing with Postman

If you are a developer, tester, or a manager, sometimes understanding various methods of API can be a challenge when building and consuming the application.

Generating good documentation and help pages for your Web API using Postman with .NET Core is as easy as making some HTTP calls.

Let’s start downloading simple To-do projects from GitHub.
Download and run the below TodoMvcSolution

Download Postman

Postman is a Google Chrome application for testing API calls. You can download and install Postman from below web site.

Here are the APIs we can test -  Get, Post, Put and Delete for this application.


Here are the Web APIs we want to test.
    //Copyright 2017 (c) SmartIT. All rights reserved.  
    //By John Kocer  
    // This file is for Swagger test, this application does not use this file  
    using System.Collections.Generic;  
    using Microsoft.AspNetCore.Mvc;  
    using SmartIT.Employee.MockDB;   
      
    namespace TodoAngular.Ui.Controllers  
    {  
      [Produces("application/json")]  
      [Route("api/Todo")]  
      public class TodoApiController : Controller  
      {  
        TodoRepository _todoRepository = new TodoRepository();  
      
        [Route("~/api/GetAllTodos")]  
        [HttpGet]  
        public IEnumerable<SmartIT.Employee.MockDB.Todo> GetAllTodos()  
        {  
          return _todoRepository.GetAll();  
        }  
      
        [Route("~/api/AddTodo")]  
        [HttpPost]  
        public SmartIT.Employee.MockDB.Todo AddTodo([FromBody]SmartIT.Employee.MockDB.Todo item)  
        {  
          return _todoRepository.Add(item);  
        }  
      
        [Route("~/api/UpdateTodo")]  
        [HttpPut]  
        public SmartIT.Employee.MockDB.Todo UpdateTodo([FromBody]SmartIT.Employee.MockDB.Todo item)  
        {  
          return  _todoRepository.Update(item);  
        }  
      
        [Route("~/api/DeleteTodo/{id}")]  
        [HttpDelete]  
        public void Delete(int id)  
        {  
          var findTodo = _todoRepository.FindById(id);  
          if (findTodo != null)  
            _todoRepository.Delete(findTodo);  
        }  
      }  
    }

Note - Your local port number may be different than mine. Use your local port number.
 
http://localhost:63274/api/GetAllTodos // GET
http://localhost:63274/api/AddTodo //POST
http://localhost:63274/api/UpdateTodo //PUT
http://localhost:63274/api/DeleteTodo/5 // DELETE
 
Testing GET with Postman
    Testing GET is very easy. First, we need to set HTTP Action from the drop-down list as GET.
    Then, we need to type or paste into the API URL box.
    Then, click the blue SEND button.

If the GET is successful, we see the status: 200 OK.

Testing POST with Postman
    First, we need to set Http Action from the dropdown list as POST.
    Then, we need to type or paste into the API URL box.
    AddTodo API accepts a Todo object in JSON format. We need to pass a new Todo JSON data.
    To pass JSON data we need to Select Body Tap.
    Select the Raw
    Select JSON(Application/JSON) as text format.
    Write or paste your Todo JSON data.
    Then, click the blue SEND button.

If the POST is successful, we see the status: 200 OK.
 
You will see Status:200 for success and the return value in the Return Body tab. We sent Publish Postman Todo item with id=0 and we received id=5 as result.

Testing PUT with Postman

    First, we need to set HTTP Action from the dropdown list as PUT.
    Then, we need to type or paste into the API URL.
    UpdateTodo API accepts a Todo object in JSON format. We need to pass an existing Todo JSON data.
    To pass JSON data we need to Select Body Tab
    Select the Raw format
    Select JSON(Application/JSON) as text format.
    Write or paste your Todo JSON
    Then click the blue SEND

If the PUT is successful, we see the status: 200 OK.

 
 
You will see Status:200 for success and the return value in the Return Body Tab. We sent Publish Postman Todo item with "name": "Publish Postman-In progress" and we receive an updated todo result.


Testing DELETE with Postman

    First, we need to set Http Action from the dropdown list as DELETE.
    Then, we need to type or paste into the API URL box.
    DeleteTodo/5 API accepts an id on the  We need to pass an existing Todo with an Id value.
    Then, click the blue SEND button.

If the Delete is successful, we see the status: 200 OK.

HostForLIFE ASP.NET Core 5.0.2 Hosting
HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 

 



ASP.NET Core 5.0.2 Hosting - HostForLIFE :: How To Implement Database Views Using Entity Framework (EF) Code First Approach?

clock March 1, 2021 06:32 by author Peter

There are several situations where your applications may need to display data by combining two or more tables, sometimes even more than 7-8 tables. In such a scenario, using Entity framework may result in a slow performance because we need to process by selecting data from a table, then run some loops from other tables.

However, the database itself has many features to handle the performance in these cases, such as stored procedures or creating views that are most recommended and result in better performance.
 
On the other hand, entity framework, open source ORM framework, is gaining huge popularity among the .net developer because of numerous advantages and speedup the coding as well as quite handy to control database directly form code.
 
In this article, I will show how to how to take the advantages of database views in entity framework and overcome the problems of complex joining/query by creating a view and handling those views in Entity framework.
 
Database view

A view is considered as a virtual table which is formed based on SQL statement of other tables. This can be considered as a real table; however, we cannot do commands like delete or update. In simple terms, it contains query to pull data from table(s). We generally use WHERE, FUNCTION and/or JOIN to tables to form a view.
 
We create views for query simplicity: we can write complex queries to select data from various tables and instead of writing those complex queries each time; we create views to use it like simple tables. Other advantages are performance improvements, data security and ease of use.
 
We can create view two ways (MS SQL server): SQL Script and Query Designer.
 
SQL Script Syntax
    CREATE VIEW view_name AS    
    SELECT column1, column2.....    
    FROM table_name    
    WHERE [condition];     

We can write complex queries using where, function, join etc. or you can even do union.
 
Query Designer
We can take advantages of query designer as shown,


We can add tables, add relations (auto relations based primarykey-foreignkey), modify alias as depicted in above diagram. There is option to modify query manually and check the results.
 
Handling Views in Entity Framework
We can utilize views in entity framework database first approach easily considering a model. However, in entity framework code first approach, we need to do tricks. If we create models of views then it will create tables of those views in add-migration and database update command.
 
Tricks
We can handle views in entity framework in two ways.
 
Option 1
Create a view combining multiple tables in the database manually and subsequently add an entity for the view. Finally, we can add ignore for the entity OnmodelCreating Entity builder, as shown below.
 
Sample Code
    protected override void OnModelCreating(ModelBuilder modelBuilder)    
    {    
      if (IsMigration)    
        modelBuilder.Ignore<ViewEntityName>();    
     ...    
    }   

With above trick, we can simply take advantages of entity model and ignore in migrations and database update in code first approach.
 
Option 2
Alternatively, you can create an extension or property for handling views in the database. In this option, we can create a view manually in the database then add an extension or property.
 
Sample Code
    //Property    
    class DBContext    
    {    
        public IQueryable<YourView> YourView     
        {    
            get    
            {    
                return this.Database.SqlQuery<YourView>("select * from dbo.ViewName");    
            }    
        }    
    }   


Extension
    static class DbContextExtensions    
    {    
        public static IQueryable<ViewNameModel>(this DbContext context)    
        {    
            return context.Database.SqlQuery<ViewNameModel>("select * from dbo.ViewName");    
        }    
    }  

We can build database context extension to handle view and use it in our solution with code first approach.
 
There are some other alternative methods as well, however, I prefer these options, as they are easy to implement.
 
Conclusion
In this article, we have learned how to implement database views in entity framework in code first approach and take advantages of those views to handle complex queries and overcome the problem of complex joining/query in entity framework. Database views is quite effective for complex queries in terms of performance, ease of use, data security and most importantly query simplicity.


HostForLIFE ASP.NET Core 5.0.2 Hosting
HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET Core 5.0.2 Hosting - HostForLIFE :: How To Encrypt an AppSettings Key In Web.config?

clock February 22, 2021 06:20 by author Peter

Sometimes we come across a scenario where we need to encrypt a sensitive key in appSettings section in Web.config file. This blog demonstrates the  steps to encrypt a key and read the respective key in an ASP.NET application.

I have an appsettings key that is being called from .NET application. Before we are encrypting appsettings key in web.config.


Step 1 - Adding a section in configSections in web.config
    <configSections>
    <section name="secureAppSettings" type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    </configSections


Step 2 - Add secureAppSettings section under configuration
    <secureAppSettings>
    <add key="Password" value="XXXXXXXX"/>
    </secureAppSettings>

How To Encrypt a AppSettings Key In Web.config
Step 3 - Execute command from command prompt to encrypt secureAppSettings section
Open command prompt and execute the below commands.

cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
aspnet_regiis.exe -pef "secureAppSettings" "your application web config path" -prov "DataProtectionConfigurationProvider"

After execution of the above command, secure app settings section encrypted as below.


Step 4 - Accessing appsettings key from .NET code
To access the encrypted key value in code, we can write it like below.
    using System.Collections.Specialized;

    var passwordValue = "";
    var section = System.Web.Configuration.WebConfigurationManager.GetSection("secureAppSettings") as NameValueCollection;
    if (section != null && section["Password"] != null)
    {
    passwordValue = section["Password"];
    }

Excellent! We successfully encrypted to a key in appsettings in web.config. Similarly, we can do the same steps while deploying a Web application to IIS.

HostForLIFE ASP.NET 3.1.9 Hosting
HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET Core 3.1.9 Hosting - HostForLIFE :: Handling Larger JSON String Values In .NET And Avoiding Exceptions

clock February 16, 2021 06:49 by author Peter

Working with JSON within Web Services recently has become the latest and greatest simply because it plays so nicely with others and can often be very easily serialized and deserialized to fit your needs.
 
There is just something rewarding about having a massive collection of complex objects that can be thrown into a simple string and passed across however you see fit and then completely regenerated in its original collection in just a handful of code.
 
However sometimes these strings can get big and I mean really big, like exceeding default values big, and when this happens, exceptions happen. This post will cover a few ways that you can prevent a nasty InvalidOperationException that may look something like this with ease:
 

 
The Problem
You decide that paging data is for losers and decide to pull a graph of all of the data within your database, which will hypothetically contain thousands of complex objects, each with additional properties of their own. If your dataset is large enough, you’ll find yourself quickly exceeding the bounds that your Serializer can handle and you’ll be met with an exception and no data.
 
The Solution
There are three basic methods of handling this depending on your current environment:

    Setting the MaxJsonLength property default value within your web.config. (This will only apply to web-services that handle JSON).
     
    Setting the MaxJsonLength property of a JavascriptSerializer object to perform your serialization.
     
    If you are using MVC4 to handle returning your JSON values, you may want to override the default JsonResult() ActionResult and change the maximum size manually.
     
    Either of these changes will help you avoid any bumps in the road when passing across your large JSON values.

Option I: The MaxJsonLength Property for handling JSON in Web Services
The MaxJsonLength property which can be set within the web.config of your application controls the maximum size of the JSON strings that are accepted by the JsonSerializerclass. The default value is 102400 characters.
 
In order to increase the size of this value – you can just add the following code to your web.config file and set it to the value that you desire:

    <configuration>    
       <system.web.extensions>  
           <scripting>  
               <webServices>  
                   <!-- Update this value to change the value to   
                        a larger value that can accommodate your JSON   
                        strings -->  
                   <jsonSerialization maxJsonLength="86753090" />  
               </webServices>  
           </scripting>  
       </system.web.extensions>  
    </configuration>    


It is important to know that this setting within the web.config will only apply to actual Web Services that handle your JSON strings using the internal JsonSerializer. If you are still encountering issues after applying this change, you will likely want to continue reading and consider using an instance of the JsonSerializer class to handle setting this value.
 
Option II: Using the JavaScriptSerialzier and the MaxJsonLength Property to Handle Serializing JSON Values
Using an instance of a JavascriptSerializer will not actually inherit the previously defined within the web.config (as the web.config only applies to Web Services that handle the JSON) so you can easily just create an instance of the serializer and set the property accordingly:
    // Creates an instance of your JavaScriptSerializer   
    // and Setting the MaxJsonLength  
    var serializer = new JavaScriptSerializer() { MaxJsonLength = 86753090 };  
      
    // Perform your serialization  
    serializer.Serialize("Your JSON Contents");   


This will allow you to easily your larger data and adjust your maximum size easily.
 
Option III: Overriding the MVC4 JsonResult Action Result to Handle the Maximum Size
Much like the previous examples, every time that you are going to return a JsonResultyou can simply add the MaxJsonLength property to a specific value depending on the context of your specific action:
    return new JsonResult() {   
       Data = "Your Data",   
       MaxJsonLength = 86753090   
    };  


Or using the Json() method:
    JsonResult result = Json("Your Data");   
    result.MaxJsonLength = 8675309;   


However, if you want a more widespread solution that you could use within a single area of your application, you may want to consider overriding the JsonResult class and set your value within this newer class:

    // This ActionResult will override the existing JsonResult   
    // and will automatically set the maximum JSON length  
    protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)    
    {  
        return new JsonResult()  
        {  
            Data = data,  
            ContentType = contentType,  
            ContentEncoding = contentEncoding,  
            JsonRequestBehavior = behavior,  
            MaxJsonLength = Int32.MaxValue // Use this value to set your maximum size for all of your Requests  
        };  
    }  

From a JSON to a JMAN
Those are just a few methods that you should be able to use if you ever encounter an issue when passing larger JSON strings across your Controllers or through the use of Web Services. I am sure that there are likely several other ways to handle these same problems, but hopefully one of these will help you out if you are in a tight spot.

HostForLIFE ASP.NET 3.1.9 Hosting
HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 

 



ASP.NET Core 3.1.9 Hosting - HostForLIFE :: Unable To Resolve Service For Type ‘Swashbuckle.AspNetCore.Swagger.ISw

clock February 3, 2021 08:48 by author Peter

Recently, one of my team members faced this error while implementing Swagger in ASP.NET core.

Environment Details

  • Visual Studio 2019
  • ASP.NET Core 3.1
  • Swashbuckle.AspNetCore 5.6.3

Error
Unable to resolve service for type ‘Swashbuckle.AspNetCore.Swagger.ISwaggerProvider’ while attempting to Invoke middleware ‘Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware
 
The issue was with the Swagger generator. The swagger generator was not called or registered in container services of the startup file.
 
Below code: (startup.cs file) add services.AddSwaggerGen(),
    // This method gets called by the runtime. Use this method to add services to the container.  
    public void ConfigureServices(IServiceCollection services)  
    {  
        //...other methods added to servces  
        //...  
        //...  
      
        // Register the Swagger generator, defining 1 or more Swagger documents  
        services.AddSwaggerGen();  
      
        //....other methods added to servces  
        //...  
    }  


Additionally, you can modify the information displayed in swagger UI with the following code:
    // Register the Swagger generator, defining 1 or more Swagger documents  
    services.AddSwaggerGen(c =>  
    {  
        c.SwaggerDoc("v1", new OpenApiInfo  
        {  
            Version = "v1",  
            Title = "My Peter API",  
            Description = "Peter ASP.NET Core Web API",  
            TermsOfService = new Uri("https://Peter.com/terms"),  
            Contact = new OpenApiContact  
            {  
                Name = "Rijwan Ansari",  
                Email = string.Empty,  
                Url = new Uri("https://Peter.com/spboyer"),  
            },  
            License = new OpenApiLicense  
            {  
                Name = "Use under Open Source",  
                Url = new Uri("https://Peter.com/license"),  
            }  
        });  
    });  

This modification resolved the issue/error.

HostForLIFE ASP.NET 3.1.9 Hosting
HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 



ASP.NET Core 3.1.9 Hosting - HostForLIFE :: Seed Data In .Net Core Identity

clock January 27, 2021 08:15 by author Peter

While developing a real-time project, we should offer different authorizations to different users. This means, for example,  users who are "Admin" ,can access a timesheet, but users who are "HR" can rollout pay changes. Here we are trying to define different roles. A group of users belonging to a role will have same access or authorization. But users from different roles, will have different authorizations.

 
So, before hosting our application, we should define the basic roles in place. We don't expect consumers/end-users to define roles in general. We can achieve that using .Net core identity and entity framework.
 
Prerequisite
A .Net core project with Identity, Entity framework and language as C#.
 
In Entity framework , we can define default database table values before creating database model. This concept is called seeding. We are going to use seeding in order to define default users and roles here.
 
I have a class AppDbContext which inherits from IdentityDbContext. We will need to override OnModelCreating() method to meet seeding. Here is the sample code.
 
Startup.cs
    public void ConfigureServices(IServiceCollection services)  
           {  
               #region database configuration              
               string connectionString = config.GetConnectionString("AppDb");  
      
               services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(connectionString));  
      
               services.AddIdentity<User, IdentityRole>()  
                   .AddEntityFrameworkStores<AppDbContext>();  
               #endregion                         
           }  


AppDbContext.cs
    public class AppDbContext : IdentityDbContext<User>  
        {  
            public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)  
            {  
      
            }  
      
            protected override void OnModelCreating(ModelBuilder builder)  
            {  
                base.OnModelCreating(builder);  
                this.SeedUsers(builder);  
                this.SeedUserRoles(builder);  
            }  
      
            private void SeedUsers(ModelBuilder builder)  
            {  
                User user = new User()  
                {  
                    Id = "b74ddd14-6340-4840-95c2-db12554843e5",  
                    UserName = "Admin",  
                    Email = "[email protected]",  
                    LockoutEnabled = false,  
                    PhoneNumber = "1234567890"  
                };  
      
                PasswordHasher<User> passwordHasher = new PasswordHasher<User>();  
                passwordHasher.HashPassword(user, "Admin*123");  
      
                builder.Entity<User>().HasData(user);  
            }  
      
            private void SeedRoles(ModelBuilder builder)  
            {  
                builder.Entity<IdentityRole>().HasData(  
                    new IdentityRole() { Id = "fab4fac1-c546-41de-aebc-a14da6895711", Name = "Admin", ConcurrencyStamp = "1", NormalizedName = "Admin" },  
                    new IdentityRole() { Id = "c7b013f0-5201-4317-abd8-c211f91b7330", Name = "HR", ConcurrencyStamp = "2", NormalizedName = "Human Resource" }  
                    );  
            }  
      
            private void SeedUserRoles(ModelBuilder builder)  
            {  
                builder.Entity<IdentityUserRole<string>>().HasData(  
                    new IdentityUserRole<string>() { RoleId = "fab4fac1-c546-41de-aebc-a14da6895711", UserId = "b74ddd14-6340-4840-95c2-db12554843e5" }  
                    );  
            }  
        }  


After adding this piece of code, we need to build the application. Now, let's open Package Manager Console . We need to run "add-migration user_role" and "update-database" commands in order to reflect seeding changes in database.

Now lets open SQL query window just to make sure EF has updated User, Role and UserRole table. Here you go.


As you can see, we have default users and roles before we deploy our application.
 
Note


You can see few GUIDs that I have used as ID, you can customize it based on your project design. 

 
We have succeeded in seeding user and role data. Thanks for coming this far in the article. Please feel free to give your valuable comments/suggestions/feedback.

 



ASP.NET Core 3.1.9 Hosting - HostForLIFE :: Can A Class Work Without Constructor In C#

clock January 19, 2021 08:26 by author Peter

A special method of the class that is automatically invoked when an instance of the class is created is called a constructor. A constructor is a special method that is used to initialize objects. The advantage of a constructor, is that it is called when an object of a class is created.
 

When we create instance of a class a default constructor  is invoked automatically having the same name as Class . Some key points,
    Constructor is used to initialize an object (instance) of a class.
    Constructor is a like a method without any return type.
    Constructor has the same name as class name.
    Constructor follows the access scope (Can be private, protected, public, Internal and external).
    Constructor can be overloaded.

Following is the list of constructors in C#.
    Default constructor
    Parameterized constructor
    Private Constructor
    Static Constructor
    Copy Constructor

Default Constructor
A constructor without any parameters is called a default constructor. If we do not create constructor the class will automatically call default constructor when an object is created.
 
Example of Default Constructor,
    using System;  
    namespace DefaultConstractor {  
        class addition {  
            int a, b;  
            public addition() //default contructor  
            {  
                a = 100;  
                b = 175;  
            }  
            public static void Main() {  
                addition obj = new addition(); //an object is created , constructor is called  
                Console.WriteLine(obj.a);  
                Console.WriteLine(obj.b);  
                Console.Read();  
            }  
        }  
    }  


Parameter Constructor
A constructor with at least one parameter is called a parameterized constructor.
 
Private Constructor
Private constructors are used to restrict the instantiation of object using 'new' operator. A private constructor is a special instance constructor. It is commonly used in classes that contain static members only.
 
Static Constructor
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced
 
Copy Constructor
The constructor which creates an object by copying variables from another object is called a copy constructor.
 
Is it possible to have a class without Constructor?
If a class contains no instance constructor declarations, a default instance constructor is automatically provided. The only classes in C# which don't have any instance constructors are static classes, and they can't have constructors.
 
Example
    class Person {  
        //This class has no constructor  
        public void getPersonProfile() {  
            Console.WriteLine("Base class:getPersonProfile() have no constructor");  
        }  
    }  
    class Program {  
        static void Main(string[] args) {  
            //Create object of person  
            Person p = new Person();  
            p.getPersonProfile();  
        }  
    }  

HostForLIFE ASP.NET 3.1.9 Hosting
HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 



ASP.NET Core 3.1.9 Hosting - HostForLIFE :: What Is Startup Class And Program.cs In ASP.NET Core?

clock January 11, 2021 08:41 by author Peter

Program.cs is where the application starts. Program.cs file will work the same as Program.cs file in traditional console application of .NET Framework. Program.cs fille is the entry point of application and will be responsible to register Startup.cs fill, IISIntegration and Create a host using an instance of IWebHostBuilder, the Main method.

Global.asax is no longer  in ASP.NET Core application. Startup.cs file is a replacement of Global.asax file in ASP.NET Core.

Startup.cs file is entry point, and it will be called after Program.cs file is executed at application level.  It handles the request pipeline. Startup class triggers the second the application launches.

Description
 
What is Program.cs ?

Program.cs is where the application starts. Program.cs class file is entry point of our application and creates an instance of IWebHost which hosts a web application.
    public class Program {  
        public static void Main(string[] args) {  
            BuildWebHost(args).Run();  
        }  
        public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args).UseStartup < startup > ().Build();  
    }   


WebHost is used to create instance of IWebHost and IWebHostBuilder and IWebHostBuilder which are pre-configured defaults. The CreateDefaultBuilder() method creates a new instance of WebHostBuilder. UseStartup<startup>() method specifies the Startup class to be used by the web host. We can also specify our custom class in place of startup.

Build() method returns an instance of IWebHost and Run() starts web application until it stops.

Program.cs in ASP.NET Core makes it easy for us to setup a web host.
    public static IWebHostBuilder CreateDefaultBuilder(string[] args) {  
        var builder = new WebHostBuilder().UseKestrel().UseContentRoot(Directory.GetCurrentDirectory()).ConfigureAppConfiguration((hostingContext, config) => {  
            /* setup config */ }).ConfigureLogging((hostingContext, logging) => {  
            /* setup logging */ }).UseIISIntegration()  
        return builder;  
    }   


the UseKestrel() specify method is an extension, which specifies Kestrel as an internal web server. The Kestrel is an open-source, cross-platform web server for ASP.NET Core. Application is running with Asp.Net Core Module and it is necessary to enable IIS Integration (UseIISIntegration()), which configures the application base address and port.
 
It also configures UseIISIntegration(), UseContentRoot(), UseEnvironment("Development"), UseStartup<startup>() and other configurations are also available, like Appsetting.json and Environment Variable. UseContentRoot is used to denote current directory path.
 
We can also register logging and set minimium loglevel as shown below. It also overrides loglevel configured in appsetting.json file.
    .ConfigureLogging(logging => { logging.SetMinimumLevel(LogLevel.Warning); })   

In the same way we can also control body size of our request and response by enabling in program.cs file as below.
    .ConfigureKestrel((context, options) => { options.Limits.MaxRequestBodySize = 20000000; });   

ASP.net Core is cross-platform and open-source and also it is compatible to host into any server rather than IIS, external web server such as IIS, Apache, Nginx etc.
 
What is Startup file?
Now the question is, is startup.cs file is mandatory or not? Yes, startup.cs is mandatory, it can be decorated with any access modifier like public, private, internal. Multiple Startup classes are allowed in a single application. ASP.NET Core will select the appropriate class based on its enviroment.

If a class Startup{EnvironmentName} exists, that class will be called for that EnvironmentName or Environment Specific startup file will be executed to avoid frequent changes of code/setting/configuration based on environment.
 
ASP.NET Core supports multiple environment variables like Development, Production and Staging. It reads the environment variable ASPNETCORE_ENVIRONMENT at application startup and store value into Hosting Environment interface.

Should we need to define class name with startup.cs? No, it is not necessary, that class name should be Startup.

We can define two methods in startup file like ConfigureServices and Configure along with constructor.

Startup file example
    public class Startup {  
        // Use this method to add services to the container.  
        public void ConfigureServices(IServiceCollection services) {  
            ...  
        }  
        // Use this method to configure the HTTP request pipeline.  
        public void Configure(IApplicationBuilder app) {  
            ...  
        }  
    }   

ConfigureServices Method
This is an optional method in Startup class which is used to configure services for application. When any request comes to the application, he ConfigureService method will be called first.

ConfigureServices method includes IServiceCollection parameter to register services. This method must be declared with a public access modifier, so that environment will be able to read the content from metadata.
    public void ConfigureServices(IServiceCollection services)  
    {  
       services.AddMvc();  
    }  

Configure Method

The Configure method is used to specify how the application will respond in each HTTP request. This method is mostly used for registering middleware in HTTP pipeline. This method method accept IApplicationBuilder parameter along with some other services like IHostingEnvironment and ILoggerFactory. Once we add some service in ConfigureService method, it will be available to Configure method to be used.
    public void Configure(IApplicationBuilder app)  
    {  
       app.UseMvc();  
    }   


Above example shows how to enable MVC feature in our framework. We need to register UseMvc() into Configure and also need to register service AddMvc() into ConfigureServices. UseMvc is know as middlware. Middleware is new concept introduce with Asp.net Core, thereaew  many inbuilt middleware available, and some are as below.
    app.UseHttpsRedirection();  
    app.UseStaticFiles();  
    app.UseRouting();  
    app.UseAuthorization();  
    UseCookiePolicy();  
    UseSession();   


Middleware can be configure in http pipeline using Use, Run, and Map.
 
Run Extension
The nature of Run extension is to short circuit the HTTP pipeline immediately. It is a shorthand way of adding middleware to the pipeline that does not call any other middleware which is next to it and immediately returns HTTP response.
 
Use Extension
It will transfer next invoker, so that HTTP request will be transferred to the next middleware after execution of current use if the next invoker is present.
 
Map Extension
Map simply accepts a path and a function that configures a separate middleware pipeline.
 
app.Map("/MyDelegate", MyDelegate);
 
To get more detailed information about middleware Click here
 
ASP.net core has built-in support for Dependency Injection. We can configure services to DI container using this method. Following ways are to configure method in startup class.
 
AddTransient
Transient objects are always different; a new instance is provided to every controller and every service.
 
Scoped
Scoped objects are the same within a request, but different across different requests.
 
Singleton
Singleton objects are the same for every object and every request.
 
Can we remove startup.cs and merge entire class with Program.cs ?
 
Answer is : Yes we can merge entire class  in to single file.

Here we have gone through basic understanding of how program.cs and startup.cs file is important for our Asp.net Core application and how both can be configured, we have also had a  little walk though  Environment Variable and middleware and how to configure middleware and dependency injection. Additionally we have seen how UseIIsintegration() and UseKestrel() can be configured.

HostForLIFE ASP.NET 3.1.9 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 



European ASP.NET Core Hosting :: ASP.NET Core 2.0 Empty Project

clock January 6, 2021 07:38 by author Peter

In this article, we will create an empty ASP.NET Core project that doesn’t include default features, i.e., an empty shell.

Step to be followed

First, create a new empty project using Visual Studio 2017.
    File > New > Project
    Under “.NET Core”, select “ASP.NET Core Web Application”. Enter Name and Location. Click OK.
    Select “Empty”. Click OK.

Next, remove the code from Program.cs and Startup.cs so that they look like below (keeping the necessary "using" statements).
    public class Program {  
        public static void Main(string[] args) {  
            BuildWebHost(args).Run();  
        }  
        public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args).UseStartup().Build();  
    }  
    public class Startup {  
        public Startup(IHostingEnvironment env, ILoggerFactory loggerFactory, IConfiguration config) {}  
        public void ConfigureServices(IServiceCollection services) {  
            // setup dependency injection in service container  
        }  
        public void Configure(IApplicationBuilder app, IHostingEnvironment env) {  
            // setup request pipeline using middleware  
        }  
    }  


Empty project template in Visual Studio 2017 creates a project with Program.cs and Startup.cs classes.

Program.cs
Just like a Console application, "public static void Main()" is the starting point of ASP.NET Core applications. We’re setting up a host (WebHost) that references the server handling requests (Kestrel). This is achieved using CreateDefaultBuilder() method that configures -
    Kestrel- cross-platform web server
    Root- content root will use the web project’s root folder
    IIS- as the reverse proxy server
    Startup- points to a class that sets up configuration, services, and pipeline (see next section).
    Configuration- adds JSON and environment variables to IConfiguration available via Dependency Injection (see the next section).
    Logging- adds a Console and Debugs the logging providers.

Once configured, we Build() and Run() the host, at which point, the main thread is blocked and the host starts listening to the request from the Server.

When setting up WebHostBuilder, you could set values for various settings via UseSetting()method, which takes in a key/value pair for a property. These properties include applicationName (string), contentRoot (string), detailedErrors (bool), environment (string), URLs (semicolon separated list) and Webroot (string). Some of these properties can also be set via extension methods on WebHostBuilder.

Startup.cs

This class sets up the application dependency injection services and requests pipeline for our application, using the following methods.
    ConfigureServices(): add services to the service container
    Configure(): setup request pipeline using Middleware.

The parameters for these methods can be seen in the code attachment above.

These methods are called in the same sequence as listed above. The important point to remember about the sequence in which they run is that the service container is available after ConfigureServices, i.e., in Configure() method, and not before that.



European ASP.NET Core Hosting :: Working With AutoMapper

clock December 22, 2020 09:10 by author Peter

This article provides some guidelines on how to use AutoMapper in C#.
We have come across a lot of situations when we need to copy data from one object to another. Normally, we follow the below mentioned approach to achieve this. Let’s say we have two classes declared as below,

First Class:
    public class UserObject  
       {  
           public int Id;  
           public string Name;  
           public string Address;  
       }  

Second Class:
    public class UserAnotherObject  
    {  
        public int Id;  
        public string Name;  
        public string Address;  
    }
 

Now, if an object of the first class have some data in it and we want to copy that data to an object of the second class, we would be using the following approach for this:
    UserObject uObj = new UserObject();                         //an object of First Class  
               UserAnotherObject uAnotherObj = new UserAnotherObject();    //an object of Second   
      
               uAnotherObj.Id = uObj.Id;  
               uAnotherObj.Name = uObj.Name;  
               uAnotherObj.Address = uObj.Address;   


This is undoubtedly a tedious and repetitive task in case the object has a lot of properties.

Now, to overcome this task we can use a Nuget Package called the Auto-Mapper. Its working is quite simple to explain, in that it creates copy of one object into another but a bit automatically on the basis of Datatypes and names of the properties.

In order to use AutoMapper we would have to install it first from the Nuget Package Manager as pictorially explained below:

Step 1: Go to Manage NuGet Packages.. option in the project.
 

Step 2: Search and install AutoMapper to your project.

Step 3: Include the required Library on the page.
    using AutoMapper.Mappers;   

Now that this been done, we create a Mapper between the UserObject class and UserAnotherObject class. This will be done using the following line.

    AutoMapper.Mapper.CreateMap<UserObject, UserAnotherObject>();   

After creating this Mapper, let’s put some data into the object of the class UserObject that we made above,
    uObj.Id = 123;  
    uObj.Name = "Peter";  
    uObj.Address = "London";  


Now that we have the data, let’s copy the data from the object of UserObject class into the object of class UserAnotherObject using the AutoMapper that we just created above.
    uAnotherObj = AutoMapper.Mapper.Map<UserAnotherObject>(uObj);   

This copies the complete data from the uObj object to uAnotherObj object.

Note:
We need to keep it in mind that Auto Mapper copies data to properties in the target object with the same name as the properties name in the source object. The name should be the same but NOT CASE-SENSITIVE i.e. the name in source object can be “id” and that in the target object can be “ID”.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in