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;
             });




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