Search This Blog

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.     




 

 

 

 

 

 

 

 

 

 

 

 

 

Thursday, 29 September 2022

Quick Tech Bits - React-Redux integration

To integrate react and redux, the installation of the library "react-redux" is required. The redux library should also be installed

 C:\Your_Project_Directory\>npm install redux react-redux 

** The github link for a simple sample application on this integration is available at this link

 Summarizing integration between and redux

1. import {connect} from 'react-redux' 

   This import should be done inside the react component that wishes to use the Redux Store


2. Write 2 functions in the above react component

i. mapStateToProps(): It will map the redux store to props of the react component

      Here, redux will allow the creation of props dynamically through code

ii. mapDispatchToProps(): Will take a function called dispatch as its parameter. This function will dispatch (invoke) the action that will invoke the reducer that will change the redux state. The changed redux state will be assigned to the object key (addUser)

that will be returned as a prop to the react component.


3. Call connect(). Connect(mapStateToProps, mapDispatchToProps)(YourReactComponent)

   This function will connect react & redux.


4. In react application, assuming that App.js is the container component, we add the Provider tag

   to integrate everything to a specific store of redux.

Inside App.js  

 <Provider store={yourReduxStoreObject}>

   <YourReactComponent/>

</Provider> 

 



Thursday, 22 September 2022

Approach for students / learners of new software technology

 When you create small applications while learning new technologies, use the following approach.

These steps are focussed on the .net technology. So if you are a beginner for .Net, then while practicing applications, use the following approach.

Notes:


Approach a requirement


1. Write it down in notepad. Take part of the requirement, break it down into classes, properties, methods. If there are multiple classes, check if the classes are related to each other.


2. At this stage, start the boiler plate code. This means, create the skeleton structure.

Eg: Create the classes, properties and empty functions as decoded in step 1.


3. Start coding the logic.

4. Write the logic to display the output in the correct file and project.

=================================================

APPROACH: If output is not as per expectation

ANSWER: DEBUG


To Debug in .Net using Visual Studio, place a breakpoint by clicking on the grey margin of the code editor in Visual Studio.


1. Place the breakpoint where you wish to assess the code output live.


2. Run your application. The execution will stop  at the breakpoint. Here you can hover over the individual properties, parameters, variables to see the live output value.


3. Use the following keyboard shortcuts to debug code

a. Fn + F10 : Debug the next line of code

b. Fn + F11 : Debug (Step) inside the function call

c. Fn + Shift + F10: You do not want to debug the code below, so you want to let the code execute normally and only start debugging after the current function execution completes. This is known as Step Out (Start debugging outside the existing function)

Wednesday, 14 September 2022

Modern SDLC - A peek into practical Agile

 Phases of SDLC



Lets see how a enterprise project can be worked upon as per Software Development Lifecycle (SDLC)

1. Discuss with Client

- Analysis: Convert Client requirements through examples into technical requirements

- O/p: Requirements Document: SRS - System Requirement Specification


2. Planning: PM comes out with an Estimation Document

- In an estimation document

- Total number of releases for the product

- Total Days required to Deliver

- Team size required

- Delivery Date


3. Implementation: Development

- Designing the Product

- How many modules

- Which Technologies to Use

- Classes, Projects,DBs, APIs

- HTML Wireframes

- Proof of Concept Applications created

- Coding : S.E

4. Testing

- Write all possible cases for a given requirement.

- All cases means: What is expected: Happy Case

   Loopholes / Bugs: Sad Case

5. Deployment

- Instruction Manuals for Client / Support Team

- Installation of the Product

- Servers & Security Certificates

- Configurations



======================================================================

But in today's fast paced world, where several companies would bid for a project, it becomes important to deliver fast which means within a short timeline.

The above process of SDLC, takes a long time (several months) to produce the final product (release to client).

The above SDLC process is also linear, which means, when the UI, development teams are at work, the QA (Quality Assurance Team) is not assigned to work. Parallel work environment is not possible with the traditional SDLC process

=======================================================================

SOLUTION:

AGILE: In this model, a product is delivered in several usable stable parts.

Hence multiple small and stable releases will be given to the client

Eg: Amazon.com delivered in 4 parts

V1: All requirements wrt Product Mgmt, Orders Mgmt, Payment Gateway Integration

V2: Additional requirements for Tracking of Orders

V3: Additional Requirements for Dropshipping and engagement

V4: Additional Requirements for Frachising

- Each Version will follow the Construction phase: Requirements Analysis -> Planning -> Design UI -> Develop

   -> Test -> User Acceptance (Client Acceptance) -> Release

- The cycle is known as SPRINT. Hence, in the above example, we can say there are 4 sprints.

- Requirements or deliverables identified by client will become User Stories

- The Large team is divided into Scrum Teams (smaller teams) each handling a collection of user stories

- Each team member of a single Scrum team will do analysis of assigned user story, work on the elements (parts)

  of a single user story, document the details of the user story and implement it.

- Each user story will have sub-stories (parts/elements) which will get assigned to specific team member

Eg: Product Management

- Create Product Page UI -- UI / Frontend Team member

- BLL -- Backend Developer

- Expected Results, how your module should work, workflow and technical descriptions -- QA Team 

member

- Operations Team member - manage Checkin/checkout, integration & deployment of code, configure
























Thursday, 25 August 2022

Quick Tech Bits - N-Tier Architectecture Calls Vs Data

 

Here is a quick diagram of how the call hierarchy vs  data flow hierarchy in an n-tier architecture takes place.

  • The Face in the diagram is the end user who interacts with the Presentation Layer (PL) of your product.
  • The Services Layer (SL) is introduced if the Presentation Layer becomes polyglotic. If your product is a website (Using Java) like Gmail and is also available as Gmail Android App, IPhone App, then all these three applications will need to be synced with the same business logic, Database Servers right?
    • Hence we need a project that uses Rest Services (WebApis), SOAP Services so that all the Apps can access the Business Logic, Databases in a language and framework agnostic way over http.
  • The Business Logic (BL) consists of the product's core logic and is basically a collection of Class Library  projects (producing portable executables like Dlls)
  • The Data Access Layer (DAL) uses a set of technology adapters that can communicate with DBMS residing on different servers.


CALL Hierarchy (marked in red)

When the end-user clicks a button on the UI 

==> A call to ==> Services Layer takes place 

=>which=>calls the ==> Business Logic Layer Methods 

=>which=>calls the==> Data Access Layer 

==>finally calling ==> DBMS Queries / Stored Procedures / Functions / Views / Commands


DATA FLOW Hierarchy

The data is returned after the call in the reverse direction (marked in green)

Looking at the Data Flow Hierarchy, as a developer you can know which projects created in the respective layers need to be referenced and how.

The direction of adding project reference in the N-tier architecture is the same as the Data Flow Hierarchy direction.

Eg: Data flows from DAL to BL, hence DAL project will be added as a reference to BL project

Data Flow Hierarchy is used to seed your product architecture, create boiler-plate code for the product.

Hope this helps.





SQL Cursor Syntax - Quick Tech Bits

 Cursor: 

  • Is used to do a different processing row by row of the select query
  • The column names displayed need to be formatted or validated or processed before showing output. This process can give different results per row. 
  • Hence cursor is used

Eg: Showing culture specific / language specific outputs for the same data. Here cursor can be used

Eg: Creating a comma-separated string for a given table data


- TIP: Imagine you are working with a file when writing the cursor syntax. Makes it easier to visualize and understand the syntax

- File is created, then opened, then processed line-by-line, then closed and removed from memory.

- The same holds for a cursor


- SYNTAX

1.     DECLARE <cursorName> CURSOR FOR
2.               <select query>
3.     OPEN <cursorName>
4.     FETCH NEXT FROM <cursorName>
5.     INTO <variable names one each for selected  columns>
6.    
7.     <your logic for processing>
8.    
9.     CLOSE <cursorName>
10.   DEALLOCATE <cursorName>

*** CURSOR SHOULD ALWAYS BE USED AS THE LAST RESORT 

*** DUE TO PERFORMANCE CONCERNS

Check this repo for an example script of the MoviesDb and run the Cursor example.

The script files below should be run in Microsoft SQL Management Studio / Visual Studio in the same order.

MoviesDB Script: Creates a MoviesDB database with sample data

Cursor Script: Contains an example for cursor & how it can be replaced with a normal SQL query.

Hope this helps.

Wednesday, 3 August 2022

C# Change console Forecolor

 

While working on console applications in .net, its nice to display different colored fonts for different statuses.

For example: Warnings should show up in yellow, errors in red, success messages in fluorescent green.

This is particularly useful when you write Logger modules for your products.

#1 Change Foreground Color

1.  Console.ForegroundColor = ConsoleColor.Green;
2.  Console.WriteLine($"Update successful!");
3.   
4.  Console.ForegroundColor = ConsoleColor.Red;
5.  Console.WriteLine($"There was an error: Invalid input");
6.   
7.  Console.ForegroundColor = ConsoleColor.Yellow;
8.  Console.WriteLine($"Please use Pascal naming conventions"); 
9.    

# Output