Windows 10 Set time automatically not working

December 28, 2019 0 comments
After completing fresh installation of Windows 10 Enterprise Edition, I was setting Date and Time and every time I restart computer it use to get back to some other timings.

I had set time automatically and also set time zone automatically as per the screenshot

Windows 10 Set time automatically not working
Windows 10 Set time automatically not working


To resolve this issue, I followed following steps
  1. Press Windows key + r ( + r).
  2. Type services.msc.
  3. Click Windows Time in the Name column.
    set time automatically is not working in windows 10
  4. Alternate click/ Right click and then click Properties.
  5. Change Startup type to Automatic (if it’s not already set to Automatic).
    Change startup type from manual to automatic if windows 10 set time automatically is not working
  6. Click Start if the service isn’t started.
Now Windows 10 Set time automatically starts working.

How to force HTTPS using a web.config file / Redirect Http to Https using web.config

December 27, 2019 0 comments
http to https using web.config, Use web.config to redirect HTTP to HTTPs, redirect to https using web config file in .net

How to redirect http to https using web config ? To do permanent redirect to https using web.config under Configuration section in web.config file simply add following Rewriting rules.
 

    
        
            
                
                
                    
                    
                        
                    
                    
                
            
        
    

This way we can redirect all Http request to Https using web.config

  • Web.config URL rewrite - force www prefix and https
  • Use web.config to redirect HTTP to HTTPs
  • How to configure your web.config to Redirect http to https
  • Web.config redirects with rewrite rules - https
  • 301 redirect entire site http to https using web.config
  • How to force HTTPS from web.config file

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>