How to select N Random Items from the List in C#

February 20, 2022 0 comments
This post is about, how to select N Random Items from any T list in C# 

 e.g. Say we have IList with total count of 1000 and we need to get 100 random items from the List. We should use following function to return N Random Items from any List in C#

public IEnumerable <T> PickRandom<T>(IEnumerable<T> list, int number)
{
    var random = new Random();
    var total = list.Count();
    var required = number;
    foreach (var item in list)
    {
        if (random.Next(total) < required)
        {
            required--;
            yield return item;
            if (required == 0)
            {
                break;
            }
        }
        total--;
    }
}

Calculate next due date based on start date frequency and current date in c#

April 17, 2021 0 comments

During one project development there is one scenario which made me write this post.
Scenario is as follows
Company has clients, each has different invoice start date and invoice frequency. I had to calculate and display next invoice date from current date + next month. i.e. invoice will always be raised in next month of service completion. e.g. Client A has invoice start date 01-Jan-2021 and invoice frequency is 5 months. Date when I am writing this post is 17-April-2021. So now next invoice date for Client A is 01-June-2021. For client B invoice start date is 01-March-2021 and invoice frequency is 3 months, then its next invoice date is 01-June-2021 and so on for all other client. 

To handle this scenarios I have written following function in c# which will always returns next invoice date from Current date. 


public class DateHelper
{
 public static DateTime nextInvoiceDate(DateTime? InvoicingStartDate,
    string invoicingFrequency)
     {
     int occurrence =
     (DateTime.Now.Month - Convert.ToInt32(InvoicingStartDate?.Month)) 
     / Convert.ToInt32(invoicingFrequency);
     
     int restInt = 
     (DateTime.Now.Month - Convert.ToInt32(InvoicingStartDate?.Month)) 
     % Convert.ToInt32(invoicingFrequency);
     DateTime next = InvoicingStartDate.Value;
            int multi;
            if (restInt == 0 && DateTime.Now < InvoicingStartDate)
            {
                if (Convert.ToInt32(invoicingFrequency) == 1 && occurrence < 0)
                {
                    multi = 1;
                }
                else
                {
                    multi = Convert.ToInt32(invoicingFrequency)
                    * Math.Abs(occurrence);
                }
                
            }
            else
            {
                if (Convert.ToInt32(invoicingFrequency) == 1)
                {
                    multi = Convert.ToInt32(invoicingFrequency)
                    * (Math.Abs(occurrence));
                }
                else
                {
                    multi = Convert.ToInt32(invoicingFrequency) 
                    * (Math.Abs(occurrence) + 1);
                }

            }
            return next.AddMonths(multi);

        }
    }
  • How to calculate a future date based on a given date ?
  • Calculate next due date based on start date frequency and current date ?
  • How to nearest future date from given date and frequency ?
  • Best way to calculate next date from start plus frequency
  • How to calculate next meeting date based on given frequency ?

How to compile Less, sass/scss, JSX, ES6, CoffeeScript in visual studio

October 26, 2020 0 comments

 It is very easy to compile LESS and SCSS files in visual studio. To do this we have to use Web Compiler extension. Web compiler extension generates css file from LESS and SCSS files on run time.


Lets Install the Extension


Simply download and install the extension. WebCompiler extension allows us to compile LESS, Sass, JSX, ES6 and CoffeeScript files.

Followings are the features of this extension
  • Compilation of LESS, Scss, Stylus, JSX, ES6 and CoffeeScript files
  • Saving a source file which triggers re-compilation automatically
  • Specify compiler options for each individual file
  • Error list is integrated
  • MSBuild support for CI scenarios
  • Minify the compiled output
  • Customizable minification options for each language
  • Displays a watermark when opening generated file
  • Shortcut to compile all specified files in solution
  • Task runner explorer is integrated
  • Command line interface
Lets assume we have Visual studio solution and it Contains SCSS files, it can contain files with any of these extensions .less.scss.styl.jsx.es6 or .coffee

Any of above extensions can be compiled, for this article lets consider only scss extension, 
We have many scss files like the following image

How to compile scss in visual studio



We have style.scss file which combines all the scss files, it looks like as follows


@import 'variabls';
@import 'mixin';
@import 'common';
@import 'element/button';
@import 'section/header';
@import 'section/slider';
@import 'section/banner';
@import 'section/product';
@import 'section/blog';
@import 'section/newsletter';
@import 'section/shipping';
@import 'section/testimonial';
@import 'section/brand';
@import 'section/footer';
@import 'section/shop';
@import 'section/product-details';
@import 'section/cart-page';
@import 'section/checkout';
@import 'section/wishlist';
@import 'section/contact';
@import 'section/login';
@import 'section/faq';
@import 'section/my-account';
@import 'section/about';
@import 'section/services';
@import 'section/blog-page';
@import 'section/blog-details';
@import 'section/quick-view';
@import 'section/newsletter-popup';
@import 'section/404';
@import 'section/privacy-policy';

Now simply right click on the style.scss file and click on Web Compiler > Compile file.

compile scss in visual studio


A file named compilerconfig.json is created in the root of the project. This file looks like.
[
  {
    "outputFile": "wwwroot/assets/css/style.css",
    "inputFile": "wwwroot/assets/scss/style.scss"
  }
]
We can always change the outputFile path to our css folder, I have changed it in this example to css file. Similary there is one more file named compilerconfig.json.defaults which get generated and can be used to configure minification of js/css, check following file and you can modify it as per your requirements
{
  "compilers": {
    "less": {
      "autoPrefix": "",
      "cssComb": "none",
      "ieCompat": true,
      "strictMath": false,
      "strictUnits": false,
      "relativeUrls": true,
      "rootPath": "",
      "sourceMapRoot": "",
      "sourceMapBasePath": "",
      "sourceMap": false
    },
    "sass": {
      "autoPrefix": "",
      "includePath": "",
      "indentType": "space",
      "indentWidth": 2,
      "outputStyle": "nested",
      "Precision": 5,
      "relativeUrls": true,
      "sourceMapRoot": "",
      "lineFeed": "",
      "sourceMap": false
    },
    "stylus": {
      "sourceMap": false
    },
    "babel": {
      "sourceMap": false
    },
    "coffeescript": {
      "bare": false,
      "runtimeMode": "node",
      "sourceMap": false
    },
    "handlebars": {
      "root": "",
      "noBOM": false,
      "name": "",
      "namespace": "",
      "knownHelpersOnly": false,
      "forcePartial": false,
      "knownHelpers": [],
      "commonjs": "",
      "amd": false,
      "sourceMap": false
    }
  },
  "minifiers": {
    "css": {
      "enabled": true,
      "termSemicolons": true,
      "gzip": false
    },
    "javascript": {
      "enabled": true,
      "termSemicolons": true,
      "gzip": false
    }
  }
}
This is how we can compile Less, sass/scss, jsx, CoffeeScript in visual studio, we can also use this web pack to minify JS files.

The entity type 'IdentityUserLogin' requires a primary key to be defined.

June 21, 2020 0 comments
While developing Web application in Asp.net Core Razor page, I have come across following error


InvalidOperationException: The entity type 'IdentityUserLogin<string>' requires a primary key to be defined.
I was doing following thing in my application

  • I wanted to set Unique Key constraint on Email for my two models i.e. Vendor and Member model so I had added code below in my ApplicationDbContext file. (You may have different name for your DbContext file.)


 public class ApplicationDbContext : IdentityDbContext&lt;ApplicationUser>
    {
     public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
          : base(options)
        {

        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<Member>().HasIndex(m => m.Email).IsUnique();
            builder.Entity<Vendor>().HasIndex(v => v.Email).IsUnique();
        }

        public DbSet<Vendor> Vendors { get; set; }

        public DbSet<Member> Members { get; set; }
        
    }    
Here if we see closely, I am missing base model Creating function. When I build and run code I get error saying 

 InvalidOperationException: The entity type 'IdentityUserLogin' requires a primary key to be defined.

 
The entity type 'IdentityUserLogin' requires a primary key to be defined.

To Resolve this error, I have added   base.OnModelCreating(builder);  in ApplicationDbContext 
check following code 



public class ApplicationDbContext : IdentityDbContext&lt;ApplicationUser>
    {
     public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
          : base(options)
        {

        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<Member>().HasIndex(m => m.Email).IsUnique();
            builder.Entity<Vendor>().HasIndex(v => v.Email).IsUnique();
            
              base.OnModelCreating(builder);
        }

        public DbSet<Vendor> Vendors { get; set; }

        public DbSet<Member> Members { get; set; }
        
    }     


This blog answers query - How to resolve The entity type 'IdentityUserLogin<string>' requires a primary key to be defined. 

How to disable JavaScript Debugging in Visual Studio

June 17, 2020 0 comments
Though it is a useful feature, while doing development I have observed browser locking due to JS Debugging in Visual Studio.

Though I know JS debugging in Visual studio is a useful feature, it becomes annoying because you have to open new instance of application. 

To Disable Java script debugging in visual studio go to Tools > Options

Disable JavaScript Debugging in Visual Studio


Click on Options and option window will open.

Then scroll down on the left menu to select option Debugging -> General . Then search for thes setting labelled “Enable JavaScript debugging for ASP.NET (Chrome and IE)” and uncheck it.


Disable JavaScript Debugging in Visual Studio - Debugging options


This is how we should disable Js debugging in visual studio 2019

How override ASP.NET Core Identity's password policy or How To Customize Password Policy in asp.net Core

February 07, 2020 0 comments
ASP.NET Core Identity uses default values for  password policy settings, in this article we shall see how to override or customize Asp.net Core Identity's password policy ?

By default, Identity requires that passwords contain an

  • uppercase character
  • lowercase character,
  • a digit
  • a non-alphanumeric character. 
  • Passwords must be at least six characters long. 

PasswordOptions
can be set in Startup.ConfigureServices.

To change password Policy, we shall add following lines of code in startup.cs file



 services.Configure(options =>
             {
                 // Password settings
                 options.Password.RequireDigit = true;
                 options.Password.RequiredLength = 6;
                 options.Password.RequireNonAlphanumeric = false;
                 options.Password.RequireUppercase = false;
                 options.Password.RequireLowercase = false;
             });




Asp.Net Core 2.2 - HTTP Error 500.0 - ANCM In-Process Handler Load Failure

May 16, 2019 1 comments
While deploying .net core web application, I got an Error saying

HTTP Error 500.0 - ANCM In-Process Handler Load Failure

Common causes of this issue:

  • The specified version of Microsoft.NetCore.App or Microsoft.AspNetCore.App was not found.
  • The in process request handler, Microsoft.AspNetCore.Server.IIS, was not referenced in the application.
  • ANCM could not find dotnet.

Troubleshooting steps:

  • Check the system event log for error messages
  • Enable logging the application process' stdout messages
  • Attach a debugger to the application process and inspect

For more information visit: https://go.microsoft.com/fwlink/?LinkID=2028526



When I checked web.config there is following line of code
 
        
      


Change AspNetCoreModuleV2 to AspNetCoreModule make the application work.
 
        
      

You may face this issue in Azure environment too.
Aspnetcore 2.2 Targetting .Net Framework, InProcess fails on azure app service with error TTP Error 500.0 - ANCM In-Process Handler Load Failure


http error 500.0 - ancm in-process handler load failure iis express

http error 500.0 - ancm in-process handler load failure localhost

http error 500.0 - ancm in-process handler load failure stackoverflow

ancm in-process handler load failure swagger

swagger http error 500.0 - ancm in-process handler load failure

azure http error 500.0 - ancm in-process handler load failure

ancm in-process handler load failure azure

ancm could not find dotnet.

Mvc Core - Multiple custom attributes of the same type found - new scaffoled item - controller with view

April 27, 2019 0 comments
While working on myAttendance.io project in mvc.net core 2.2, I was creating a company and wanted to generate Controller with Views. My company Class is as follows


 public class Company : BaseModel
    {
        public string Logo { get; set; }

        [DisplayName("Company Name")]
        [Required]
        [MaxLength(150)]
        public string CompanyName { get; set; }

        [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Please enter a valid e-mail address")]
        [EmailAddress(ErrorMessage = "Please enter valid email address.")]
        [Required]
        [MaxLength(150)]
        public string Email { get; set; }
        [Required]
        [DataType(DataType.Url)]
        [Url(ErrorMessage = "Invalid URL!")]
        [MaxLength(150)]
        public string Web { get; set; }

        [Phone]
        [Required]
        [MaxLength(15)]
        public string Phone { get; set; }

        [Required]
        [MaxLength(10)]
        public string Currency { get; set; }
        [Required]
        [MaxLength(250)]
        public string Address { get; set; }

    }
When I tried adding New Scaffolded item, I got error saying
 There was an error running the selected code generator: 'Multiple custom attributes of the same type found'

Multiple custom attributes of the same type found

To resolve this error I had to remove
[DataType(DataType.Url)]
If we see model then I have already used
[Url(ErrorMessage = "Invalid URL!")]
This same is applicable for followings
[EmailAddress(ErrorMessage = "Please enter valid email address.")]

[Phone(ErrorMessage = "Please enter valide phone number.")]
We have EmailAddress and PhoneNumber as Datatype also
[DataType(DataType.EmailAddress)]

[DataType(DataType.PhoneNumber)]
So Just make sure we have DataType or corresponding Tag to avoid 'Multiple custom attributes of the same type found.'

InvalidOperationException Unable to resolve service for type Interface while attempting to activate Controller

April 17, 2019 0 comments
A dependency is any object that another object requires, Dependency Injection i.e. DI is used for objects which has complex dependencies. While working on one project in asp.net core 2.2 (MVC project, I came across this error)

An unhandled exception occurred while processing the request.

InvalidOperationException: Unable to resolve service for type 'myproject.Areas.myArea.Interfaces.IHolidayRepository' while attempting to activate 'myproject.Areas.myArea.Controllers.AdminController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)

Dependency Injection (DI) is already part of Core framework, We just have to register our dependencies in startup.cs file under ConfigurationService method.

services.AddTransient<IFoo, Foo>();
services.AddSingleton<IBar, Bar>();
services.AddScoped<IHello, Hello>();

ASP.NET services can be configured with the following:

Transient

Always Different - Transient objects are always different; a new instance is provided to every controller and every service.

Scoped

Same within a request - 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 (regardless of whether an instance is provided in ConfigureServices)

After Registering Dependency Injection in startup.cs file, we will not get InvalidOperationException Unable to resolve service for type Interface while attempting to activate Controller error.

Reference Article - https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/dependency-injection?view=aspnetcore-2.2

More than one DbContext named 'myproject.Models.myprojectContext' was found. Specify which one to use by providing its fully qualified name using its exact case

April 15, 2019 0 comments

I was developing a Web-Application in Asp.Net Core 2.2 . After I added the new identity with scaffold it generated me these codes:
For IdentityHostingStartup.cs




[assembly:
 HostingStartup(typeof(myproject.Areas.Identity.IdentityHostingStartup))]
namespace myproject.Areas.Identity
{
    public class IdentityHostingStartup : IHostingStartup
    {
     public void Configure(IWebHostBuilder builder)
      {
      builder.ConfigureServices((context, services) => {
      services.AddDbContext(options =>
       options.UseSqlServer(
       context.Configuration.GetConnectionString("myprojectContextConnection")));

        services.AddDefaultIdentity()
                .AddEntityFrameworkStores();
            });
        }
    }
}

Code in my Startup.cs (After adding Identity I made some modifications in startup.cs, with reference to this article)

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. 
        //Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure(options =>
            {
        // This lambda determines whether user consent for 
       //non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddRazorPagesOptions(options =>
        {
        options.AllowAreas = true;
        options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
        options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
        });

      services.ConfigureApplicationCookie(options =>
        {
        options.LoginPath = $"/Identity/Account/Login";
        options.LogoutPath = $"/Identity/Account/Logout";
        options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
        });

        services.Configure(Configuration.GetSection("EmailSettings"));
        services.AddSingleton();
        services.AddScoped();

        }

        // This method gets called by the runtime. 
       //Use this method to configure the HTTP request pipeline.
 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseAuthentication();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }

This was working fine, then I added new models and wanted to scaffold a model with controller and views using Entity Framework. After I set up everything and click ok, I started getting error saying : More than one DbContext named 'myproject.Models.myprojectContext' was found. Specify which one to use by providing its fully qualified name using its exact case.

More than one DbContext was found. Specify which one to use by providing its fully qualified name using its exact case.


 To resolve this issue I removed following lines of code from IdentityHostingStartup.cs

  services.AddDbContext(options =>
   options.UseSqlServer(
   context.Configuration.GetConnectionString("myprojectContextConnection")));

And I modified my startup.cs file to following

 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. 
        //Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
   {
    services.Configure(options =>
      {
      // This lambda determines whether user consent for 
      //non-essential cookies is needed for a given request.
       options.CheckConsentNeeded = context => true;
       options.MinimumSameSitePolicy = SameSiteMode.None;
      });

  services.AddDbContext(options =>
  options.UseSqlServer(Configuration
.GetConnectionString("myprojectContextConnection")));


  services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddRazorPagesOptions(options =>
    {
    options.AllowAreas = true;
    options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
    options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
     });

   services.ConfigureApplicationCookie(options =>
    {
    options.LoginPath = $"/Identity/Account/Login";
    options.LogoutPath = $"/Identity/Account/Logout";
    options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
     });

    services.Configure(Configuration.GetSection("EmailSettings"));
    services.AddSingleton();
    services.AddScoped();

    }

        // This method gets called by the runtime. 
        //Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change 
                //this for production scenarios,
                // see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseAuthentication();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }

Now I try generating Scaffold items it works without any error.

encrypt decrypt string in asp.net Core

March 22, 2019 0 comments
This article is all about Implementing Simple AES encryption decryption algorithm in Asp.net Core.

We can actually use the same code for .net framework 4.7.2 also.

Use using System.Security.Cryptography;
Just make sure the key which we use for encryption and decryption is same. In our case we are using following key (This key I have copied from some references I already have.)



private static string keyString = "E546C8DF278CD5931069B522E695D4F2";



For encryption use following function, I generally keep Helper functions as static function

public static string EncryptString(string text)
        {
            var key = Encoding.UTF8.GetBytes(keyString);

            using (var aesAlg = Aes.Create())
            {
                using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV))
                {
                    using (var msEncrypt = new MemoryStream())
                    {
                        using (var csEncrypt = new CryptoStream(msEncrypt, 
encryptor, CryptoStreamMode.Write))
                        using (var swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(text);
                        }

      var iv = aesAlg.IV;
      var decryptedContent = msEncrypt.ToArray();
      var result = new byte[iv.Length + decryptedContent.Length];
      Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
      Buffer.BlockCopy(decryptedContent, 0, result, iv.Length,
     decryptedContent.Length);

                        return Convert.ToBase64String(result);
                    }
                }
            }
        }

For decryption use following function


public static string DecryptString(string cipherText)
        {
            var fullCipher = Convert.FromBase64String(cipherText);

            var iv = new byte[16];
            var cipher = new byte[16];

            Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length);
            Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, iv.Length);
            var key = Encoding.UTF8.GetBytes(keyString);

            using (var aesAlg = Aes.Create())
            {
                using (var decryptor = aesAlg.CreateDecryptor(key, iv))
                {
                    string result;
                    using (var msDecrypt = new MemoryStream(cipher))
                    {
                        using (var csDecrypt = new CryptoStream(msDecrypt,
 decryptor, CryptoStreamMode.Read))
                        {
                            using (var srDecrypt = new StreamReader(csDecrypt))
                            {
                                result = srDecrypt.ReadToEnd();
                            }
                        }
                    }

                    return result;
                }
            }
        }

How to Get client ip address in .net core 2.x

March 16, 2019 0 comments
To get client IP address in Asp.net core 2.x, you have to inject HttpContextAccessor 

Declare private variable in class


   private IHttpContextAccessor _accessor;


Initialize above private variable in default constructor and retrieve IP address as showed in following code


public class HomeController : Controller
    {
        private readonly IUserRepository userRepository;
        private IHttpContextAccessor _accessor;

        public HomeController(IUserRepository userRepository,
        IHttpContextAccessor accessor)
        {
            this.userRepository = userRepository;
            this._accessor = accessor;
        }
        public IActionResult Index()
        {
   ViewBag.IpAddress = 
_accessor.HttpContext.Connection.RemoteIpAddress.ToString();
   return View();
        }
    }



Make sure you initialize IHTTPContextAccessor in startup.cs


services.TryAddSingleton<ihttpcontextaccessor httpcontextaccessor="">();
</ihttpcontextaccessor>


If you don't register IHTTPContextAccessor .net core will give you following error

 InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate

.net core get host ip address

Get Client ip address in .net core 2.0

SqlException: Cannot open database "DATABASE" requested by the login. The login failed. Login failed for user 'IIS APPPOOL\APPPOOLNAME'.

March 14, 2019 0 comments
While deploying web based and Mobile based Attendance system on IIS and MSSQL2017, I got following error.
  1. Project developed using Entity Framework Core and MVC .net Core 2.2
  2. To deploy web application in IIS, I published core 2.2 web application and put it under IIS.
  3. Assigned new APP Pool with with No Managed Code for .NET CLR Version.
I got following SQL related error

An unhandled exception occurred while processing the request.

SqlException: Cannot open database "DATABASE" requested by the login. The login failed. Login failed for user 'IIS APPPOOL\apppoolname'.

System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, object providerInfo, string newPassword, SecureString newSecurePassword, bool redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, bool applyTransientFaultHandling, string accessToken)

To resolve this issue, simply create User named 'IIS APPPOOL\apppoolname in SQL

SqlException: Cannot open database "DATABASE" requested by the login. The login failed. Login failed for user 'IIS APPPOOL\apppoolname'

After creating user, assign it to your respective database and give db permissions to that user.

This will resolve the issue.



Swapping to Development environment will display more detailed information about the error that occurred.

March 14, 2019 0 comments
While developing Employee Mobile based and Web based Attendance system in .net core 2.2.
  1. I published application using VS2017
  2. Then I put this application in IIS and assigned an Application Pool with No Managed Code for .NET CLR Version.
  3. When I was running my application on Chrome browser, I got following error.

Swapping to Development environment will display more detailed information about the error that occurred.
Error. An error occurred while processing your request. Development Mode Swapping to Development environment will display more detailed information about the error that occurred.
Development environment should not be enabled in deployed applications, as it can result in sensitive information from exceptions being displayed to end users. For local debugging, development environment can be enabled by setting the ASPNETCORE_ENVIRONMENT environment variable to Development, and restarting the application.

To resolve this error and check actual error in details, open web.config file and add following code



<aspnetcore>
  <environmentvariables>
       <environmentvariable name="ASPNETCORE_ENVIRONMENT" value="Development">
   </environmentvariable></environmentvariables>
</aspnetcore>