Beyond the Tutorials: A Realistic Look at Coding in the Real World – Part 2
Tags: programming, tutorial, dotnetcore, angular
Published: 2023-01-28 12:20:54

<!-- wp:paragraph -->
<p>Programming tutorials shows us a land of promise where everything happens as you think; as soon as you think. But real world doesn’t work that way most of the times. Here; you spend hours debugging some CORS error or thinking why your database table Id column is not auto-incrementing. For the last 2 days; I am participating in a coding&nbsp;<a href="https://asifulhaque.com/common-interview-questions-for-sr-software-engineers-and-how-to-answer-them/">interview</a>&nbsp;which spans 2 days and these series of blog is based on that experience – what am I thinking at each stage; what is the issue and how I am resolving them. This is the second part of that.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Adding DB Context</h2>
<!-- /wp:heading -->

<!-- wp:code -->
<pre class="wp-block-code"><code>namespace dev_test
{
    public class DatabaseContext : DbContext
    {
        public DatabaseContext()
        : base()
        {
        }

        public DbSet&lt;User&gt; Users { get; set; }
        public DbSet&lt;Survey&gt; Surveys { get; set; }
        public DbSet&lt;Question&gt; Questions { get; set; }
        public DbSet&lt;Answer&gt; Answers { get; set; }
    }
}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>At this point; while adding stuff to DatabaseContext file; error was shown and needed to add nuget package Microsoft.EntityFrameworkCore and relevant packages. <br>Added the following line to appsettings.json file - </p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>"ConnectionStrings": {
    "DBConnection": "server=(localdb)\\MSSQLLocalDB;database=dev_test;Trusted_Connection=true"
  }</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>As there is no startup.cs file in the project; adding following line was not possible.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>services.AddDbContext&lt;MyDbContext&gt;(options =&gt;
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>At this point; modified the Program.cs class to look like this-</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>using dev_test;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext&lt;DatabaseContext&gt;(options =&gt;
  options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>And got the following error: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'. Installed nuget packages and added "using Arch.EntityFrameworkCore;" before the file. Now getting "options is not null here" error. Turns out; "using Arch.EntityFrameworkCore;"  was not the right solution; it should be - <br><code>"using Microsoft.EntityFrameworkCore;"</code></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The difference between the packages "Arch.EntityFrameworkCore" and "Microsoft.EntityFrameworkCore" is that Arch.EntityFrameworkCore is a third-party package that provides additional functionality on top of the standard Microsoft.EntityFrameworkCore package. It may contain additional classes, methods, and features that are not included in the Microsoft.EntityFrameworkCore package. On the other hand, Microsoft.EntityFrameworkCore is an official package from Microsoft that provides the core functionality for working with Entity and databases in .NET applications. It is the foundation for all Entity Framework Core functionality, and it is typically included as a dependency in other packages that provide additional functionality.<br>After that the program.cs file looks like this -</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>using Microsoft.EntityFrameworkCore;
using dev_test;

var builder = WebApplication.CreateBuilder(args);

var connectionString = builder.Configuration.GetConnectionString("DBConnection");
builder.Services.AddDbContext&lt;DatabaseContext&gt;(x =&gt; x.UseSqlServer(connectionString));

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
...</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Tried to run the project but got the following error -<br><code>fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]<br>An unhandled exception has occurred while executing the request.<br>Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorException: Ambiguous HTTP method for action - dev_test.Controllers.UserController.Get (dev_test). Actions require an explicit HttpMethod binding for Swagger/OpenAPI 3.0</code></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Added <code>[HttpGet]</code> and <code>[HttpPost]</code> before the <code>UserController</code> actions; and it worked out perfectly fine.<br>Also; removed the default WeatherController and associated files.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>When running this project in Swagger; it gives the following error - <br><code>System.InvalidOperationException: Unable to resolve service for type 'dev_test.Services.Contracts.IUserService' while attempting to activate 'dev_test.Controllers.UserController'.</code><br>Which means we forgot to register the dependencies. After adding them to our program.cs; it works perfectly fine.<br></p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":866,"sizeSlug":"large","linkDestination":"none"} -->
<figure class="wp-block-image size-large"><img src="https://asifulhaque.com/wp-content/uploads/2023/01/image-1024x387.png" alt="" class="wp-image-866"/><figcaption class="wp-element-caption">Registering repository and service</figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Another problem arises though; the database isn't connecting as I am trying to connect over local server. Changing <code>"DBConnection": "server=(localdb)\MSSQLLocalDB;database=dev_test;Trusted_Connection=true"</code> to <code>"DBConnection":"Server=localhost;Database=dev_test;Trusted_Connection=True;MultipleActiveResultSets=true,TrustServerCertificate=True"</code> has solved the connection issue; but it is throwing "Invalid value for key 'Multiple Active Result Sets' error." <br>Changing yet again to <code>"DBConnection": "Server=localhost;Database=dev_test;Trusted_Connection=True;TrustServerCertificate=True"</code> solved the issue; but showing "Invalid object name 'Users'." error. <br>Turns out; in dbcontext; name should be singular instead of plural like this:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>using dev_test.DTOs; // <mark style="background-color:rgba(0, 0, 0, 0);color:#c13d3d" class="has-inline-color">WRONG CODE</mark>
using Microsoft.EntityFrameworkCore;

namespace dev_test
{
    public class DatabaseContext : DbContext
    {
        public DatabaseContext(DbContextOptions&lt;DatabaseContext&gt; options) : base(options){}
        public DbSet&lt;User&gt; Users { get; set; }
        public DbSet&lt;Survey&gt; Surveys { get; set; }
        public DbSet&lt;Question&gt; Questions { get; set; }
        public DbSet&lt;Answer&gt; Answers { get; set; }
    }
}</code></pre>
<!-- /wp:code -->

<!-- wp:code -->
<pre class="wp-block-code"><code>using dev_test.DTOs; // <mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-accent-color">RIGHT CODE</mark>
using Microsoft.EntityFrameworkCore;

namespace dev_test
{
    public class DatabaseContext : DbContext
    {
        public DatabaseContext(DbContextOptions&lt;DatabaseContext&gt; options) : base(options){}
        public DbSet&lt;User&gt; User { get; set; }
        public DbSet&lt;Survey&gt; Survey { get; set; }
        public DbSet&lt;Question&gt; Question { get; set; }
        public DbSet&lt;Answer&gt; Answer { get; set; }
    }
}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>And for getting the user list; the controller signature should be - public ActionResult&gt; Get()</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Our user insert is working for the time being; though it is requiring us to manually put an different id each time. We need to address this issue later. <br>But first; we need to create our front-end application. <br>Let's get into it and use angular-cli command to create an angular project with routing.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Setting Up Angular Project</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>We set up the angular project the common way; start with angular-cli project; remove app.component.html file; add some component of our own and set up a service file to call to the backend. The initial setup might look like this -</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":884,"sizeSlug":"full","linkDestination":"none"} -->
<figure class="wp-block-image size-full"><img src="https://asifulhaque.com/wp-content/uploads/2023/01/image-1.png" alt="" class="wp-image-884"/><figcaption class="wp-element-caption">Angular project structure</figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>And the ever innocuous user-list.component.ts might look like this - </p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpClientService } from 'src/app/http-client.service';

@Component({
  selector: 'app-use-list',
  templateUrl: './use-list.component.html',
  styleUrls: &#91;'./use-list.component.scss']
})
export class UseListComponent implements OnInit {
  userList = &#91;];
  constructor(client: HttpClientService) {
    client.getData("user").subscribe((res) =&gt; console.log(res));
  }

  ngOnInit(): void {

  }
}
</code></pre>
<!-- /wp:code -->

<!-- wp:image {"id":933,"sizeSlug":"large","linkDestination":"none"} -->
<figure class="wp-block-image size-large"><img src="https://asifulhaque.com/wp-content/uploads/2023/01/is-programming-hard-a-guide-to-getting-started-in-2022-scaled-1-1024x819.jpeg" alt="Tutorials_2" class="wp-image-933"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>But here comes the issues. While running this project; we conveniently greeted with an error like this - </p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":885,"sizeSlug":"large","linkDestination":"none"} -->
<figure class="wp-block-image size-large"><img src="https://asifulhaque.com/wp-content/uploads/2023/01/image-2-1024x161.png" alt="" class="wp-image-885"/><figcaption class="wp-element-caption">The ever dreadful CORS error!</figcaption></figure>
<!-- /wp:image -->

<!-- wp:image {"id":887,"sizeSlug":"full","linkDestination":"none"} -->
<figure class="wp-block-image size-full"><img src="https://asifulhaque.com/wp-content/uploads/2023/01/image-3.png" alt="" class="wp-image-887"/><figcaption class="wp-element-caption">Adding these 2 lines fixes the problem. Nice! </figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p><strong>Other episodes in this series:</strong><br><a href="https://asifulhaque.com/when-programming-tutorials-doesnt-work-part-1/">First Part</a><br><a href="https://asifulhaque.com/beyond-the-tutorials-a-realistic-look-at-coding-in-the-real-world-part-2/">Second Part</a><br><a href="https://asifulhaque.com/beyond-the-tutorials-a-realistic-look-at-coding-in-the-real-world-part-3/">Third Part</a><br><a href="https://asifulhaque.com/beyond-the-tutorials-a-realistic-look-at-coding-in-the-real-world-part-4/">Fourth Part</a><br>And the code is given is updated into - <br><a href="https://github.com/asifbuetcse/dev-test" target="_blank" rel="noreferrer noopener">Github</a></p>
<!-- /wp:paragraph -->