Search This Blog

Friday, 14 October 2022

Quick Tech Tips: Asp.net MVC Quick Forms Authentication & Authorization steps

 Authentication / Authorization Filters STEPS

1. In global.asax file, add this line in Application_Start
    GlobalFilters.Filters.Add(new AuthorizeAttribute());
2. In Web.config  
  <authentication mode="Forms">
      <forms defaultUrl="Home/Index" loginUrl="Home/Index" />
  </authentication>
3. Changes in the code
   FormsAuthentication.SetCookie()

========================================================================
Authorization

1. In Web.config add the following
    <roleManager defaultProvider="myRoleProvider" enabled="true">
      <providers>
          <add name="myRoleProvider" type="MvcPlayground.Models.UserApplicationRoles"/>
      </providers>
      </roleManager>
2. The "type" attribute points to your class that will inherit from RoleProvider
3. Create a class UserApplicationRoles: RolesProvider
4. Override all methods, and implement whichever is applicable.
5. Add the Authorize Attribute above the action where role based authorization is required.
     [Authorize(Roles = "Admin, Customer")]

Quick Tips: Asp.net Webforms Validators

 Validators in Web forms

Validators in web forms are controls, that validate a user input based on a condition.

Multiple validators can validate the same input control

Validators are asp.net controls and they add client (JS) validations automatically based on property settings

Validators can only validate asp.net controls (not html controls)

1. RequiredFieldValidator: Empty values are not allowed.

Properties to set:

ControlToValidate

ErrorMessage

SetFocusOnError


2. CompareValidator: Compares the values in 2 controls

Properties to set:

ControlToValidate

ControlToCompare

ErrorMessage

SetFocusOnError

Operator (optional. If not set, it will compare for equality)

Type (optional. If not set, it will compare the values for string datatype)

3. RangeValidator

Properties to set:

ControlToValidate

ErrorMessage

SetFocusOnError

MaximumValue

MinimumValue

Type (optional. If not set, it will assume string datatype)


4. RegularExpressionValidator

Properties to set:

ControlToValidate

ErrorMessage

SetFocusOnError

ValidationExpression


5. CustomValidator: When none of the above fit the application requirement, custom validators are used

Properties to set:

ControlToValidate

ErrorMessage

SetFocusOnError

ClientValidationFunction

Tuesday, 11 October 2022

Quick Tech Bits: MVC 5 working with Ajax Helper (Ajax.BeginForm)

 Integration of Ajax with MVC 5

1. Use Nuget Packages. Install them for your MVC project
    a. Microsoft.jQuery.Unobtrusive.Ajax
    b. Microsoft.jQuery.Unobtrusive.Validation

2. Verify if configurations are added in Web.config.
   ** Collapse all the folders for your project. The last file in your project will have capital "W" in     "Web.config"
   Check if the following is available inside <appSettings>
    <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />

3. Open _Layout.cshtml. (Find this in Views => Shared => _Layout.cshtml)
   Add the following in the same sequence as mentioned
    <script src="~/Scripts/jquery-<version>.min.js"></script>
        <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
 
   ** <version> : Look at the correct version of the file in the Scripts folder

4. Add an Action in the controller. The action should return a PartialView("yourView").

5. Create the Views for your action. Add @using(Ajax.BeginForm())
   Syntax for Ajax.BeginForm
    "YourActionNameOnClick", "ControllerName",
        new AjaxOptions
        {
            InsertionMode = InsertionMode.Replace | InsertionMode.InsertAfter | InsertionMode.InsertBefore,
            HttpMethod = "Get | Post | Put | Delete",
            UpdateTargetId = "resultDiv"
        }
6. This completes the configuration for ajax using MVC, Ajax helpers

Saturday, 1 October 2022

Integration of .Net Web Api with Entity Framework – STEP BY STEP

 

There are more than one ways of integrating a .Net application with Entity Framework.

In this process, we shall be using

    1. Web Api’s scaffolded template for controller creation
    2.  Code First Approach in Entity Framework

Pre-requisites:

  1.             This integration is done using .Net 6   

                2.  Using Visual Studio 2022

Process

1.      Create a Web Api Core project using C#. File => New Project => Asp.net Core Web API

a.       


 

2.      The project created should look like this in the solution explorer. Here we have named the project as ForEF.

a.      


3.      Create a new API controller using the scaffolded template for Entity Framework. Right-click on Controllers folder => Add => Controller

a.      


 

 

4.      Next choose the API controller => Actions using Entity Framework

a.      





b.      



 

5.      On clicking add, it should begin installing Entity Framework Code packages from nuget.

 

a.       

 

b.      You might get an error as below.

                                                               i.      


 

c.       In this case, please do the following. Close the dialogs for controller creation. In the solution explorer, Right-Click on Dependencies folder of your project => Manage Nuget Packages

                                                               i.      


 

d.      You will notice that the missing package is already installed.

                                                               i.      


 

6.      Open the file WeatherForecast.cs , from the solution Explorer.  This file could be any file that acts as the model for your application. A model file is a file that contains

a.      A default constructor

b.       Only properties

c.       

 

7.      Add a property to it, and mark it with the [Key] Attribute.

a.      

 

b.      The property marked with [Key] attribute, will become the primary key in the database table. The model class becomes, the table name while the properties become columns of the table

8.      Now, repeat the steps 3, 4. Your controller should be created successfully.

9.      In the Solution Explorer, find the file called “appSettings.json” and open it. In this file, we will need to provide the Database name as part of “Database” Setting. Please refer screenshot below. Here we have named the database as “ForEF”. Save the file and close.

a.      



10.  To automatically migrate to the database, please follow the two commands.

a.      Open Package Manager Console. Tools Menu => Nuget Package Manager => Package Manager Console

                                                               i.      


b.      This will open the package manager console as below. Two things must be done before adding any commands

                                                              i.      Set your project as the Startup Project. [Right-click on your project => Set As Startup Project]

                                                             ii.      In the Package Manager Console, your project should be the selected project in the Dropdown list

                                                           iii.     




 

c.       Build your project manually. [Right-click on your project => Build]

d.      In the Package Manager Console, add the following commands

                                                              i.      To create a migration.

1.      Add-Migration

a.      




 

                                                             ii.      Once this command completes successfully, add in the next command, to generate a database in MS SQL Server Express. The command is as follows

1.      Update-Database

a.       

 

                                                           iii.      The migration should be successful.

11.  ALTERNATIVE STE. USE IF ABOVE FAILS: If the Package Manager Console commands fail, by showing a build failure even when the Project is compiling properly, please use this method

a.      Open Developer Console. [View Menu => Terminal]

b.      Navigate to your projectDirectory inside the Developer Console.Check if the following command works.

YourProject/> dotnet-ef --version 

                                                              i.      If the above command works, then go to step (c), else follow the next step

YourProject/>dotnet tool install --global dotnet-ef  

c.       Now add the following commands one after another. The below command will create a migration file.

YourProject/>dotnet ef migrations add v1  

d.      The next command below will execute the migration file to create the Database and tables.

YourProject/>dotnet ef database update 

12.  Use either Step (10) or (11). No need to follow both. If the above steps are successful, you can verify whether your database is created in the SQL Server Object Explorer. [View => SQL Server Object Explorer]

                                                               i.