ValcomWebStartup

Enter a topic name to show or a new topic name to create; then press Enter

Startup.cs Full File

The startup.cs file is a convention based configuration file that must exist in the root folder of the application. This file has the class definition, initialization, some properties and 2 functions. After the class and properties are initialized the 2 functions are then called automatically.

The various sections of this file are discussed below. Some sections that are common to all files are only discussed in this document.

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Diagnostics.Entity;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Data.Entity;
using Microsoft.Framework.Configuration;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Logging;
using Microsoft.Dnx.Runtime;
using ValcomWeb2New.Models;
using ValcomWeb2New.Services;
using ValcomWeb2New.Repositories;
namespace ValcomWeb2New
{
    public class Startup
    {
	public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
	{
	    // Setup configuration sources.
	    var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
		.AddJsonFile("config.json")
		.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);
	    if (env.IsDevelopment())
	    {
		// This reads the configuration keys from the secret store.
		// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
		builder.AddUserSecrets();
	    }
	    builder.AddEnvironmentVariables();
	    Configuration = builder.Build();
	}
	public IConfiguration Configuration { get; set; }
	// This method gets called by the runtime. Use this method to add services to the container.
	public void ConfigureServices(IServiceCollection services)
	{
	    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
	    // Add Entity Framework services to the services container.
	    services.AddEntityFramework()
		.AddSqlServer()
		.AddDbContext<ApplicationDbContext>(options =>
		    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
	    // Add Identity services to the services container.
	    services.AddIdentity<ApplicationUser, IdentityRole>()
		.AddEntityFrameworkStores<ApplicationDbContext>()
		.AddDefaultTokenProviders();
	    //services.AddScoped<ApplicationDbContext, ApplicationDbContext>();
	    // Configure the options for the authentication middleware.
	    // You can add options for Google, Twitter and other middleware as shown below.
	    // For more information see http://go.microsoft.com/fwlink/?LinkID=532715
	    //services.Configure<FacebookAuthenticationOptions>(options =>
	    //{
	    //    options.AppId = Configuration["Authentication:Facebook:AppId"];
	    //    options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
	    //});
	    //services.Configure<MicrosoftAccountAuthenticationOptions>(options =>
	    //{
	    //    options.ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"];
	    //    options.ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"];
	    //});
	    // Add MVC services to the services container.
	    services.AddMvc();
	    // Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers.
	    // You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json.
	    // services.AddWebApiConventions();
	    // Register application services.
	    services.AddScoped<IEmailSender, AuthMessageSender>();
	    services.AddScoped<ISmsSender, AuthMessageSender>();

	    services.AddSingleton<ICareersPageRepository, CareersPageDataRepository>();
	    services.AddSingleton<IContactPageDataRepository, ContactPageDataRepository>();
	    services.AddSingleton<IClientsAboutPageDataRepository, ClientsAboutPageDataRepository>();
	    services.AddSingleton<ICorporateProfileAboutPageDataRepository, CorporateProfileAboutPageDataRepository>();
	    services.AddSingleton<IHomePageDataRepository, HomePageDataRepository>();
	    services.AddSingleton<ILookupItemDataRepository, LookupItemDataRepository>();
	    services.AddSingleton<IOfficeContactDetailRepository, OfficeContactDetailRepository>();
	    services.AddSingleton<IOfficeDetailRepository, OfficeDetailRepository>();
	    services.AddSingleton<IPositionApplyAcknowledgePageDataRepository, PositionApplyAcknowledgePageDataRepository>();
	    services.AddSingleton<IPositionRepository, PositionRepository>();
	    services.AddSingleton<IPrivacyPageDataRepository, PrivacyPageDataRepository>();
	    services.AddSingleton<IServiceCategoriesRepository, ServiceCategoriesRepository>();
	    services.AddSingleton<IServiceItemPageDataRepository, ServiceItemPageDataRepository>();
	    services.AddSingleton<IServiceListRepository, ServiceListRepository>();
	    services.AddSingleton<IServicesPageDataRepository, ServicesPageDataRepository>();
	    services.AddSingleton<IValcomOverviewAboutPageDataRepository, ValcomOverviewAboutPageDataRepository>();
	}
	// Configure is called after ConfigureServices is called.
	public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
	{
	    loggerFactory.MinimumLevel = LogLevel.Information;
	    loggerFactory.AddConsole();
	    // Configure the HTTP request pipeline.
	    // Add the following to the request pipeline only in development environment.
	    if (env.IsDevelopment())
	    {
		app.UseBrowserLink();
		app.UseErrorPage();
		app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
	    }
	    else
	    {
		// Add Error handling middleware which catches all application specific errors and
		// sends the request to the following path or controller action.
		app.UseErrorHandler("/Home/Error");
	    }
	    // Add static files to the request pipeline.
	    app.UseStaticFiles();
	    // Add cookie-based authentication to the request pipeline.
	    app.UseIdentity();
	    // Add authentication middleware to the request pipeline. You can configure options such as Id and Secret in the ConfigureServices method.
	    // For more information see http://go.microsoft.com/fwlink/?LinkID=532715
	    // app.UseFacebookAuthentication();
	    // app.UseGoogleAuthentication();
	    // app.UseMicrosoftAccountAuthentication();
	    // app.UseTwitterAuthentication();
	    // Add MVC to the request pipeline.
	    app.UseMvc(routes =>
	    {
		routes.MapRoute(
		    name: "default",
		    template: "{controller=Home}/{action=Index}/{id?}");
		// Uncomment the following line to add a route for porting Web API 2 controllers.
		// routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
	    });
	    InitIdentityData.InitDbSeedData(app.ApplicationServices).Wait();
	}
    }
}

Using Section

The using section details what namespaces are used in the Startup.cs file. Sometimes there will be unused namespaces in this region and they may be removed without causing any problems. There are 4 kinds of namespaces that may be used in an application (2 are shown here):

The major difficulty with using Visual Studio Code is that it is very difficult to determine what namespaces are available that can be used. The Object Browser functionality that is used for this purpose in other versions of Visual Studio does not exist in Code.

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Diagnostics.Entity;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Data.Entity;
using Microsoft.Framework.Configuration;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Logging;
using Microsoft.Dnx.Runtime;
using ValcomWeb2New.Models;
using ValcomWeb2New.Services;
using ValcomWeb2New.Repositories;

Namespace Identification

This is the definition of the namespace used by this file. In this case this is a root namespace used by the application throught all other internal namespaces

namespace ValcomWeb2New

Class Startup Initialization

This code reads the configuration files, gets environment variables and stores the information in the Configuration property.

	public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
	{
	    // Setup configuration sources.
	    var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
		.AddJsonFile("config.json")
		.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);
	    if (env.IsDevelopment())
	    {
		// This reads the configuration keys from the secret store.
		// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
		builder.AddUserSecrets();
	    }
	    builder.AddEnvironmentVariables();
	    Configuration = builder.Build();
	}

Property initialization

The line below is the definition of the Configuration property and the line following that sets the property.

	public IConfiguration Configuration { get; set; }
	    Configuration = builder.Build();

Function ConfigureServices

This function is setting up the Dependency Injection container and storing the configuration of various services used by MVC. It shows that Entity Framework is being used with the database in a SQL Server.

	// This method gets called by the runtime. Use this method to add services to the container.
	public void ConfigureServices(IServiceCollection services)
	{
	    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
	    // Add Entity Framework services to the services container.
	    services.AddEntityFramework()
		.AddSqlServer()
		.AddDbContext<ApplicationDbContext>(options =>
		    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
	    // Add Identity services to the services container.
	    services.AddIdentity<ApplicationUser, IdentityRole>()
		.AddEntityFrameworkStores<ApplicationDbContext>()
		.AddDefaultTokenProviders();
	    //services.AddScoped<ApplicationDbContext, ApplicationDbContext>();
	    // Configure the options for the authentication middleware.
	    // You can add options for Google, Twitter and other middleware as shown below.
	    // For more information see http://go.microsoft.com/fwlink/?LinkID=532715
	    //services.Configure<FacebookAuthenticationOptions>(options =>
	    //{
	    //    options.AppId = Configuration["Authentication:Facebook:AppId"];
	    //    options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
	    //});
	    //services.Configure<MicrosoftAccountAuthenticationOptions>(options =>
	    //{
	    //    options.ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"];
	    //    options.ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"];
	    //});
	    // Add MVC services to the services container.
	    services.AddMvc();
	    // Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers.
	    // You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json.
	    // services.AddWebApiConventions();
	    // Register application services.
	    services.AddScoped<IEmailSender, AuthMessageSender>();
	    services.AddScoped<ISmsSender, AuthMessageSender>();

	    services.AddSingleton<ICareersPageRepository, CareersPageDataRepository>();
	    services.AddSingleton<IContactPageDataRepository, ContactPageDataRepository>();
	    services.AddSingleton<IClientsAboutPageDataRepository, ClientsAboutPageDataRepository>();
	    services.AddSingleton<ICorporateProfileAboutPageDataRepository, CorporateProfileAboutPageDataRepository>();
	    services.AddSingleton<IHomePageDataRepository, HomePageDataRepository>();
	    services.AddSingleton<ILookupItemDataRepository, LookupItemDataRepository>();
	    services.AddSingleton<IOfficeContactDetailRepository, OfficeContactDetailRepository>();
	    services.AddSingleton<IOfficeDetailRepository, OfficeDetailRepository>();
	    services.AddSingleton<IPositionApplyAcknowledgePageDataRepository, PositionApplyAcknowledgePageDataRepository>();
	    services.AddSingleton<IPositionRepository, PositionRepository>();
	    services.AddSingleton<IPrivacyPageDataRepository, PrivacyPageDataRepository>();
	    services.AddSingleton<IServiceCategoriesRepository, ServiceCategoriesRepository>();
	    services.AddSingleton<IServiceItemPageDataRepository, ServiceItemPageDataRepository>();
	    services.AddSingleton<IServiceListRepository, ServiceListRepository>();
	    services.AddSingleton<IServicesPageDataRepository, ServicesPageDataRepository>();
	    services.AddSingleton<IValcomOverviewAboutPageDataRepository, ValcomOverviewAboutPageDataRepository>();
	}

Dependency Injection Setup

These lines ensure that calls to the interface specified result in being able to use the actual classes that implement this interface.. In addition to supporting dependency injection it also allows for testing based on the interface.

	    // Register application services.
	    services.AddScoped<IEmailSender, AuthMessageSender>();
	    services.AddScoped<ISmsSender, AuthMessageSender>();

	    services.AddSingleton<ICareersPageRepository, CareersPageDataRepository>();
	    services.AddSingleton<IContactPageDataRepository, ContactPageDataRepository>();
	    services.AddSingleton<IClientsAboutPageDataRepository, ClientsAboutPageDataRepository>();
	    services.AddSingleton<ICorporateProfileAboutPageDataRepository, CorporateProfileAboutPageDataRepository>();
	    services.AddSingleton<IHomePageDataRepository, HomePageDataRepository>();
	    services.AddSingleton<ILookupItemDataRepository, LookupItemDataRepository>();
	    services.AddSingleton<IOfficeContactDetailRepository, OfficeContactDetailRepository>();
	    services.AddSingleton<IOfficeDetailRepository, OfficeDetailRepository>();
	    services.AddSingleton<IPositionApplyAcknowledgePageDataRepository, PositionApplyAcknowledgePageDataRepository>();
	    services.AddSingleton<IPositionRepository, PositionRepository>();
	    services.AddSingleton<IPrivacyPageDataRepository, PrivacyPageDataRepository>();
	    services.AddSingleton<IServiceCategoriesRepository, ServiceCategoriesRepository>();
	    services.AddSingleton<IServiceItemPageDataRepository, ServiceItemPageDataRepository>();
	    services.AddSingleton<IServiceListRepository, ServiceListRepository>();
	    services.AddSingleton<IServicesPageDataRepository, ServicesPageDataRepository>();
	    services.AddSingleton<IValcomOverviewAboutPageDataRepository, ValcomOverviewAboutPageDataRepository>();

Function Configure

This function is responsible to setup logging, and application pipeline. It also loads default deta to the database in the last line.

	public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
	{
	    loggerFactory.MinimumLevel = LogLevel.Information;
	    loggerFactory.AddConsole();
	    // Configure the HTTP request pipeline.
	    // Add the following to the request pipeline only in development environment.
	    if (env.IsDevelopment())
	    {
		app.UseBrowserLink();
		app.UseErrorPage();
		app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
	    }
	    else
	    {
		// Add Error handling middleware which catches all application specific errors and
		// sends the request to the following path or controller action.
		app.UseErrorHandler("/Home/Error");
	    }
	    // Add static files to the request pipeline.
	    app.UseStaticFiles();
	    // Add cookie-based authentication to the request pipeline.
	    app.UseIdentity();
	    // Add authentication middleware to the request pipeline. You can configure options such as Id and Secret in the ConfigureServices method.
	    // For more information see http://go.microsoft.com/fwlink/?LinkID=532715
	    // app.UseFacebookAuthentication();
	    // app.UseGoogleAuthentication();
	    // app.UseMicrosoftAccountAuthentication();
	    // app.UseTwitterAuthentication();
	    // Add MVC to the request pipeline.
	    app.UseMvc(routes =>
	    {
		routes.MapRoute(
		    name: "default",
		    template: "{controller=Home}/{action=Index}/{id?}");
		// Uncomment the following line to add a route for porting Web API 2 controllers.
		// routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
	    });
	    InitIdentityData.InitDbSeedData(app.ApplicationServices).Wait();
	}

Version: 11   Revised: 2015-10-01 10:16:52 Last Updated by: 2001:470:b0ad:1:e5b6:2d69:3897:336a Rename Show Links to Topic